Following the SymfonyCasts tutorial, I attempted to automate the setting of the Creator field of my entity after denormalization with a State Processor class. Since the code provided in the tutorial seemed outdated, I copied and edited the passwordhasher class provided by the documentation.
Here’s my state processor:
namespace AppState;
use AppEntityCommunity;
use ApiPlatformMetadataOperation;
use ApiPlatformStateProcessorInterface;
use SymfonyBundleSecurityBundleSecurity;
final readonly class CommunityCreatorSetter implements ProcessorInterface
{
public function __construct(
private ProcessorInterface $processor,
private Security $security
) {
}
/**
* @param Community $data
*/
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): Community
{
if ($data->getCreator() != null) {
return $this->processor->process($data, $operation, $uriVariables, $context);
}
$data->setCreator($this->security->getUser());
return $this->processor->process($data, $operation, $uriVariables, $context);
}
}
Community entity methods:
public function getCreator(): ?User
{
return $this->creator;
}
public function setCreator(?User $creator): static
{
$this->creator = $creator;
if ($creator !== null) {
$membership = new Membership();
$membership->setMember($creator);
$membership->setSubreddit($this);
$this->members->add($membership);
}
return $this;
}
Error on requests:
{
"@id": "/api/errors/500",
"@type": "hydra:Error",
"title": "An error occurred",
"detail": "Unable to call method "getCreator" of non-object "object".",
"status": 500,
"type": "/errors/500",
"trace": [
{
"file": "/app/vendor/symfony/expression-language/Node/BinaryNode.php",
"line": 103,
"function": "evaluate",
"class": "Symfony\Component\ExpressionLanguage\Node\GetAttrNode",
"type": "->"
},
{
"file": "/app/vendor/symfony/expression-language/Node/BinaryNode.php",
"line": 118,
"function": "evaluate",
"class": "Symfony\Component\ExpressionLanguage\Node\BinaryNode",
"type": "->"
},
{
"file": "/app/vendor/symfony/expression-language/ExpressionLanguage.php",
"line": 59,
"function": "evaluate",
"class": "Symfony\Component\ExpressionLanguage\Node\BinaryNode",
"type": "->"
},
{
"file": "/app/vendor/api-platform/core/src/Symfony/Security/ResourceAccessChecker.php",
"line": 56,
"function": "evaluate",
"class": "Symfony\Component\ExpressionLanguage\ExpressionLanguage",
"type": "->"
},
{
"file": "/app/vendor/api-platform/core/src/Serializer/AbstractItemNormalizer.php",
"line": 446,
"function": "isGranted",
"class": "ApiPlatform\Symfony\Security\ResourceAccessChecker",
"type": "->"
},
{
"file": "/app/vendor/api-platform/core/src/Serializer/AbstractItemNormalizer.php",
"line": 430,
"function": "canAccessAttribute",
"class": "ApiPlatform\Serializer\AbstractItemNormalizer",
"type": "->"
},
It seems there is some error with Item normalization. Do I need to make some custom serializer or annotation to allow symfony to access the methods?