|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace TheCodingMachine\GraphQLite\Mappers\Parameters; |
| 6 | + |
| 7 | +use phpDocumentor\Reflection\DocBlock; |
| 8 | +use phpDocumentor\Reflection\Type; |
| 9 | +use ReflectionMethod; |
| 10 | +use ReflectionParameter; |
| 11 | +use TheCodingMachine\GraphQLite\Annotations\ParameterAnnotations; |
| 12 | +use TheCodingMachine\GraphQLite\Annotations\Prefetch; |
| 13 | +use TheCodingMachine\GraphQLite\InvalidCallableRuntimeException; |
| 14 | +use TheCodingMachine\GraphQLite\InvalidPrefetchMethodRuntimeException; |
| 15 | +use TheCodingMachine\GraphQLite\ParameterizedCallableResolver; |
| 16 | +use TheCodingMachine\GraphQLite\Parameters\ParameterInterface; |
| 17 | +use TheCodingMachine\GraphQLite\Parameters\PrefetchDataParameter; |
| 18 | + |
| 19 | +use function assert; |
| 20 | + |
| 21 | +/** |
| 22 | + * Handles {@see Prefetch} annotated parameters. |
| 23 | + */ |
| 24 | +class PrefetchParameterMiddleware implements ParameterMiddlewareInterface |
| 25 | +{ |
| 26 | + public function __construct( |
| 27 | + private readonly ParameterizedCallableResolver $parameterizedCallableResolver, |
| 28 | + ) |
| 29 | + { |
| 30 | + } |
| 31 | + |
| 32 | + public function mapParameter(ReflectionParameter $parameter, DocBlock $docBlock, Type|null $paramTagType, ParameterAnnotations $parameterAnnotations, ParameterHandlerInterface $next): ParameterInterface |
| 33 | + { |
| 34 | + $prefetch = $parameterAnnotations->getAnnotationByType(Prefetch::class); |
| 35 | + |
| 36 | + if ($prefetch === null) { |
| 37 | + return $next->mapParameter($parameter, $docBlock, $paramTagType, $parameterAnnotations); |
| 38 | + } |
| 39 | + |
| 40 | + $method = $parameter->getDeclaringFunction(); |
| 41 | + |
| 42 | + assert($method instanceof ReflectionMethod); |
| 43 | + |
| 44 | + // Map callable specified by #[Prefetch] into a real callable and parse all of the GraphQL parameters. |
| 45 | + try { |
| 46 | + [$resolver, $parameters] = $this->parameterizedCallableResolver->resolve($prefetch->callable, $method->getDeclaringClass(), 1); |
| 47 | + } catch (InvalidCallableRuntimeException $e) { |
| 48 | + throw InvalidPrefetchMethodRuntimeException::fromInvalidCallable($method, $parameter->getName(), $e); |
| 49 | + } |
| 50 | + |
| 51 | + return new PrefetchDataParameter( |
| 52 | + fieldName: $method->getName(), |
| 53 | + resolver: $resolver, |
| 54 | + parameters: $parameters, |
| 55 | + ); |
| 56 | + } |
| 57 | +} |
0 commit comments