Skip to content

Commit c34671b

Browse files
authored
fix(state): improve DX around the generic ObjectProvider (#5051)
1 parent d2ee8fa commit c34671b

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed

CreateProvider.php

+6-2
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
namespace ApiPlatform\State;
1515

16+
use ApiPlatform\Exception\RuntimeException;
1617
use ApiPlatform\Metadata\Get;
1718
use ApiPlatform\Metadata\HttpOperation;
1819
use ApiPlatform\Metadata\Link;
@@ -58,8 +59,11 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
5859
}
5960

6061
$relation = $this->decorated->provide(new Get(uriVariables: $relationUriVariables, class: $relationClass), $uriVariables);
61-
$refl = new \ReflectionClass($operation->getClass());
62-
$resource = $refl->newInstanceWithoutConstructor();
62+
try {
63+
$resource = new ($operation->getClass());
64+
} catch (\Throwable $e) {
65+
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);
66+
}
6367
$this->propertyAccessor->setValue($resource, $key, $relation);
6468

6569
return $resource;

ObjectProvider.php

+7-4
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,11 @@
1313

1414
namespace ApiPlatform\State;
1515

16+
use ApiPlatform\Exception\RuntimeException;
1617
use ApiPlatform\Metadata\Operation;
1718

1819
/**
19-
* An ItemProvider that just create a new object.
20+
* An ItemProvider that just creates a new object.
2021
*
2122
* @author Antoine Bluchet <[email protected]>
2223
*
@@ -26,8 +27,10 @@ final class ObjectProvider implements ProviderInterface
2627
{
2728
public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?object
2829
{
29-
$refl = new \ReflectionClass($operation->getClass());
30-
31-
return $refl->newInstanceWithoutConstructor();
30+
try {
31+
return new ($operation->getClass());
32+
} catch (\Throwable $e) {
33+
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);
34+
}
3235
}
3336
}

0 commit comments

Comments
 (0)