|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace TheCodingMachine\GraphQLite\Mappers\Root; |
| 6 | + |
| 7 | +use GraphQL\Type\Definition\InputType; |
| 8 | +use GraphQL\Type\Definition\NamedType; |
| 9 | +use GraphQL\Type\Definition\OutputType; |
| 10 | +use GraphQL\Type\Definition\Type as GraphQLType; |
| 11 | +use phpDocumentor\Reflection\DocBlock; |
| 12 | +use phpDocumentor\Reflection\Type; |
| 13 | +use phpDocumentor\Reflection\Types\Callable_; |
| 14 | +use ReflectionMethod; |
| 15 | +use ReflectionProperty; |
| 16 | +use TheCodingMachine\GraphQLite\Mappers\CannotMapTypeException; |
| 17 | + |
| 18 | +/** |
| 19 | + * This mapper maps callable types into their return types, so that fields can defer their execution. |
| 20 | + */ |
| 21 | +class CallableTypeMapper implements RootTypeMapperInterface |
| 22 | +{ |
| 23 | + public function __construct( |
| 24 | + private readonly RootTypeMapperInterface $next, |
| 25 | + private readonly RootTypeMapperInterface $topRootTypeMapper, |
| 26 | + ) { |
| 27 | + } |
| 28 | + |
| 29 | + public function toGraphQLOutputType(Type $type, OutputType|null $subType, ReflectionMethod|ReflectionProperty $reflector, DocBlock $docBlockObj): OutputType&GraphQLType |
| 30 | + { |
| 31 | + if (! $type instanceof Callable_) { |
| 32 | + return $this->next->toGraphQLOutputType($type, $subType, $reflector, $docBlockObj); |
| 33 | + } |
| 34 | + |
| 35 | + if ($type->getParameters()) { |
| 36 | + throw CannotMapTypeException::createForUnexpectedCallableParameters(); |
| 37 | + } |
| 38 | + |
| 39 | + $returnType = $type->getReturnType(); |
| 40 | + |
| 41 | + if (! $returnType) { |
| 42 | + throw CannotMapTypeException::createForMissingCallableReturnType(); |
| 43 | + } |
| 44 | + |
| 45 | + return $this->topRootTypeMapper->toGraphQLOutputType($returnType, null, $reflector, $docBlockObj); |
| 46 | + } |
| 47 | + |
| 48 | + public function toGraphQLInputType(Type $type, InputType|null $subType, string $argumentName, ReflectionMethod|ReflectionProperty $reflector, DocBlock $docBlockObj): InputType&GraphQLType |
| 49 | + { |
| 50 | + if (! $type instanceof Callable_) { |
| 51 | + return $this->next->toGraphQLInputType($type, $subType, $argumentName, $reflector, $docBlockObj); |
| 52 | + } |
| 53 | + |
| 54 | + throw CannotMapTypeException::createForCallableAsInput(); |
| 55 | + } |
| 56 | + |
| 57 | + public function mapNameToType(string $typeName): NamedType&GraphQLType |
| 58 | + { |
| 59 | + return $this->next->mapNameToType($typeName); |
| 60 | + } |
| 61 | +} |
0 commit comments