-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CreateProvider.php
77 lines (65 loc) · 2.86 KB
/
CreateProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\State;
use ApiPlatform\Exception\RuntimeException;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Link;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Post;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
/**
* An ItemProvider for POST operations on generated subresources.
*
* @see ApiPlatform\Tests\Fixtures\TestBundle\Entity\SubresourceEmployee
*
* @author Antoine Bluchet <[email protected]>
*
* @experimental
*/
final class CreateProvider implements ProviderInterface
{
public function __construct(private ProviderInterface $decorated, private ?PropertyAccessorInterface $propertyAccessor = null)
{
$this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?object
{
if (!$uriVariables || !$operation instanceof HttpOperation || null !== $operation->getController()) {
return $this->decorated->provide($operation, $uriVariables, $context);
}
$operationUriVariables = $operation->getUriVariables();
$relationClass = current($operationUriVariables)->getFromClass();
$key = key($operationUriVariables);
$relationUriVariables = [];
foreach ($operationUriVariables as $parameterName => $value) {
if ($key === $parameterName) {
$relationUriVariables['id'] = new Link(identifiers: $value->getIdentifiers(), fromClass: $value->getFromClass(), parameterName: $key);
continue;
}
$relationUriVariables[$parameterName] = $value;
}
$relation = $this->decorated->provide(new Get(uriVariables: $relationUriVariables, class: $relationClass), $uriVariables);
if (!$relation) {
throw new NotFoundHttpException('Not Found');
}
try {
$resource = new ($operation->getClass());
} catch (\Throwable $e) {
throw new RuntimeException(sprintf('An error occurred while trying to create an instance of the "%s" resource. Consider writing your own "%s" implementation and setting it as `provider` on your operation instead.', $operation->getClass(), ProviderInterface::class), 0, $e);
}
$property = $operationUriVariables[$key]->getToProperty() ?? $key;
$this->propertyAccessor->setValue($resource, $property, $relation);
return $resource;
}
}