Skip to content

Instantly share code, notes, and snippets.

@grachevko
Created February 1, 2022 07:29
Show Gist options
  • Save grachevko/4be8bb79da486441c07f63b9e0f7e8f1 to your computer and use it in GitHub Desktop.
Save grachevko/4be8bb79da486441c07f63b9e0f7e8f1 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace App\JsonRpc\ArgumentResolver;
use App\Doctrine\Registry;
use App\JsonRpc\Attributes\Entity;
use LogicException;
use Premier\ArgumentResolver\ArgumentMetadata;
use Premier\ArgumentResolver\ArgumentValueResolverInterface;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use function class_exists;
use function is_array;
use function sprintf;
use function str_starts_with;
use function substr;
final class EntityArgumentValueResolver implements ArgumentValueResolverInterface
{
public function __construct(
private Registry $registry,
private PropertyAccessorInterface $propertyAccessor,
) {
}
/**
* {@inheritdoc}
*/
public function supports(mixed $data, ArgumentMetadata $argument): bool
{
return $argument->getAttribute() instanceof Entity;
}
/**
* {@inheritdoc}
*/
public function resolve(mixed $data, ArgumentMetadata $argument): iterable
{
$type = $argument->getType();
if (null === $type) {
throw new LogicException(sprintf('Entity typehint required to use %s attribute.', Entity::class));
}
if (!class_exists($type)) {
throw new LogicException(sprintf('Class "%s" not exists, are you sure to use %s attribute with it?', $type, Entity::class));
}
/** @var Entity $attribute */
$attribute = $argument->getAttribute();
$criteria = is_array($attribute->idPath)
? $attribute->idPath
: ['id' => sprintf('@[request][%s]', $attribute->idPath)]
;
foreach ($criteria as $key => $value) {
if (str_starts_with($value, '@')) {
$criteria[$key] = $this->propertyAccessor->getValue($data, substr($value, 1));
}
}
yield $argument->isNullable()
? $this->registry->findOneBy($type, $criteria)
: $this->registry->getOneBy($type, $criteria);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment