We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.
Total Complexity | 204 |
Total Lines | 992 |
Duplicated Lines | 0 % |
Coverage | 95.89% |
Changes | 11 | ||
Bugs | 1 | Features | 0 |
Complex classes like AnnotationParser often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use AnnotationParser, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
48 | class AnnotationParser implements PreParserInterface |
||
49 | { |
||
50 | private static array $classesMap = []; |
||
51 | private static array $providers = []; |
||
52 | private static array $doctrineMapping = []; |
||
53 | private static array $graphClassCache = []; |
||
54 | |||
55 | private const GQL_SCALAR = 'scalar'; |
||
56 | private const GQL_ENUM = 'enum'; |
||
57 | private const GQL_TYPE = 'type'; |
||
58 | private const GQL_INPUT = 'input'; |
||
59 | private const GQL_UNION = 'union'; |
||
60 | private const GQL_INTERFACE = 'interface'; |
||
61 | |||
62 | /** |
||
63 | * @see https://facebook.github.io/graphql/draft/#sec-Input-and-Output-Types |
||
64 | */ |
||
65 | private const VALID_INPUT_TYPES = [self::GQL_SCALAR, self::GQL_ENUM, self::GQL_INPUT]; |
||
66 | private const VALID_OUTPUT_TYPES = [self::GQL_SCALAR, self::GQL_TYPE, self::GQL_INTERFACE, self::GQL_UNION, self::GQL_ENUM]; |
||
67 | |||
68 | /** |
||
69 | * {@inheritdoc} |
||
70 | * |
||
71 | * @throws InvalidArgumentException |
||
72 | * @throws ReflectionException |
||
73 | */ |
||
74 | 25 | public static function preParse(SplFileInfo $file, ContainerBuilder $container, array $configs = []): void |
|
77 | 25 | } |
|
78 | |||
79 | /** |
||
80 | * @throws InvalidArgumentException |
||
81 | * @throws ReflectionException |
||
82 | */ |
||
83 | 25 | public static function parse(SplFileInfo $file, ContainerBuilder $container, array $configs = []): array |
|
84 | { |
||
85 | 25 | return self::processFile($file, $container, $configs, false); |
|
86 | } |
||
87 | |||
88 | /** |
||
89 | * @internal |
||
90 | */ |
||
91 | 63 | public static function reset(): void |
|
92 | { |
||
93 | 63 | self::$classesMap = []; |
|
94 | 63 | self::$providers = []; |
|
95 | 63 | self::$graphClassCache = []; |
|
96 | 63 | } |
|
97 | |||
98 | /** |
||
99 | * Process a file. |
||
100 | * |
||
101 | * @throws InvalidArgumentException|ReflectionException|AnnotationException |
||
102 | */ |
||
103 | 25 | private static function processFile(SplFileInfo $file, ContainerBuilder $container, array $configs, bool $preProcess): array |
|
104 | { |
||
105 | 25 | self::$doctrineMapping = $configs['doctrine']['types_mapping']; |
|
106 | 25 | $container->addResource(new FileResource($file->getRealPath())); |
|
107 | |||
108 | try { |
||
109 | 25 | $className = $file->getBasename('.php'); |
|
110 | 25 | if (preg_match('#namespace (.+);#', file_get_contents($file->getRealPath()), $matches)) { |
|
111 | 25 | $className = trim($matches[1]).'\\'.$className; |
|
112 | } |
||
113 | |||
114 | 25 | $gqlTypes = []; |
|
115 | 25 | $graphClass = self::getGraphClass($className); |
|
116 | |||
117 | 25 | foreach ($graphClass->getAnnotations() as $classAnnotation) { |
|
118 | 25 | $gqlTypes = self::classAnnotationsToGQLConfiguration( |
|
119 | 25 | $graphClass, |
|
120 | $classAnnotation, |
||
121 | $configs, |
||
122 | $gqlTypes, |
||
123 | $preProcess |
||
124 | ); |
||
125 | } |
||
126 | |||
127 | 25 | return $preProcess ? self::$classesMap : $gqlTypes; |
|
128 | 10 | } catch (\InvalidArgumentException $e) { |
|
129 | 10 | throw new InvalidArgumentException(sprintf('Failed to parse GraphQL annotations from file "%s".', $file), $e->getCode(), $e); |
|
130 | } |
||
131 | } |
||
132 | |||
133 | 25 | private static function classAnnotationsToGQLConfiguration( |
|
134 | GraphClass $graphClass, |
||
135 | object $classAnnotation, |
||
136 | array $configs, |
||
137 | array $gqlTypes, |
||
138 | bool $preProcess |
||
139 | ): array { |
||
140 | 25 | $gqlConfiguration = $gqlType = $gqlName = null; |
|
141 | |||
142 | switch (true) { |
||
143 | 25 | case $classAnnotation instanceof GQL\Type: |
|
144 | 25 | $gqlType = self::GQL_TYPE; |
|
145 | 25 | $gqlName = $classAnnotation->name ?? $graphClass->getShortName(); |
|
146 | 25 | if (!$preProcess) { |
|
147 | 25 | $gqlConfiguration = self::typeAnnotationToGQLConfiguration($graphClass, $classAnnotation, $gqlName, $configs); |
|
148 | |||
149 | 25 | if ($classAnnotation instanceof GQL\Relay\Connection) { |
|
150 | 24 | if (!$graphClass->implementsInterface(ConnectionInterface::class)) { |
|
151 | throw new InvalidArgumentException(sprintf('The annotation @Connection on class "%s" can only be used on class implementing the ConnectionInterface.', $graphClass->getName())); |
||
152 | } |
||
153 | |||
154 | 24 | if (!(isset($classAnnotation->edge) xor isset($classAnnotation->node))) { |
|
155 | throw new InvalidArgumentException(sprintf('The annotation @Connection on class "%s" is invalid. You must define either the "edge" OR the "node" attribute, but not both.', $graphClass->getName())); |
||
156 | } |
||
157 | |||
158 | 24 | $edgeType = $classAnnotation->edge ?? false; |
|
159 | 24 | if (!$edgeType) { |
|
160 | 24 | $edgeType = $gqlName.'Edge'; |
|
161 | 24 | $gqlTypes[$edgeType] = [ |
|
162 | 24 | 'type' => 'object', |
|
163 | 'config' => [ |
||
164 | 'builders' => [ |
||
165 | 24 | ['builder' => 'relay-edge', 'builderConfig' => ['nodeType' => $classAnnotation->node]], |
|
166 | ], |
||
167 | ], |
||
168 | ]; |
||
169 | } |
||
170 | |||
171 | 24 | if (!isset($gqlConfiguration['config']['builders'])) { |
|
172 | 24 | $gqlConfiguration['config']['builders'] = []; |
|
173 | } |
||
174 | |||
175 | 24 | array_unshift($gqlConfiguration['config']['builders'], ['builder' => 'relay-connection', 'builderConfig' => ['edgeType' => $edgeType]]); |
|
176 | } |
||
177 | } |
||
178 | 25 | break; |
|
179 | |||
180 | 24 | case $classAnnotation instanceof GQL\Input: |
|
181 | 24 | $gqlType = self::GQL_INPUT; |
|
182 | 24 | $gqlName = $classAnnotation->name ?? self::suffixName($graphClass->getShortName(), 'Input'); |
|
183 | 24 | if (!$preProcess) { |
|
184 | 24 | $gqlConfiguration = self::inputAnnotationToGQLConfiguration($graphClass, $classAnnotation); |
|
185 | } |
||
186 | 24 | break; |
|
187 | |||
188 | 24 | case $classAnnotation instanceof GQL\Scalar: |
|
189 | 24 | $gqlType = self::GQL_SCALAR; |
|
190 | 24 | if (!$preProcess) { |
|
191 | 24 | $gqlConfiguration = self::scalarAnnotationToGQLConfiguration($graphClass, $classAnnotation); |
|
192 | } |
||
193 | 24 | break; |
|
194 | |||
195 | 24 | case $classAnnotation instanceof GQL\Enum: |
|
196 | 24 | $gqlType = self::GQL_ENUM; |
|
197 | 24 | if (!$preProcess) { |
|
198 | 24 | $gqlConfiguration = self::enumAnnotationToGQLConfiguration($graphClass, $classAnnotation); |
|
199 | } |
||
200 | 24 | break; |
|
201 | |||
202 | 24 | case $classAnnotation instanceof GQL\Union: |
|
203 | 24 | $gqlType = self::GQL_UNION; |
|
204 | 24 | if (!$preProcess) { |
|
205 | 24 | $gqlConfiguration = self::unionAnnotationToGQLConfiguration($graphClass, $classAnnotation); |
|
206 | } |
||
207 | 24 | break; |
|
208 | |||
209 | 24 | case $classAnnotation instanceof GQL\TypeInterface: |
|
210 | 24 | $gqlType = self::GQL_INTERFACE; |
|
211 | 24 | if (!$preProcess) { |
|
212 | 24 | $gqlConfiguration = self::typeInterfaceAnnotationToGQLConfiguration($graphClass, $classAnnotation); |
|
213 | } |
||
214 | 24 | break; |
|
215 | |||
216 | 24 | case $classAnnotation instanceof GQL\Provider: |
|
217 | 24 | if ($preProcess) { |
|
218 | 24 | self::$providers[] = ['metadata' => $graphClass, 'annotation' => $classAnnotation]; |
|
219 | } |
||
220 | |||
221 | 24 | return []; |
|
222 | } |
||
223 | |||
224 | 25 | if (null !== $gqlType) { |
|
225 | 25 | if (!$gqlName) { |
|
226 | 24 | $gqlName = isset($classAnnotation->name) ? $classAnnotation->name : $graphClass->getShortName(); |
|
227 | } |
||
228 | |||
229 | 25 | if ($preProcess) { |
|
230 | 25 | if (isset(self::$classesMap[$gqlName])) { |
|
231 | 1 | throw new InvalidArgumentException(sprintf('The GraphQL type "%s" has already been registered in class "%s"', $gqlName, self::$classesMap[$gqlName]['class'])); |
|
232 | } |
||
233 | 25 | self::$classesMap[$gqlName] = ['type' => $gqlType, 'class' => $graphClass->getName()]; |
|
234 | } else { |
||
235 | 25 | $gqlTypes = [$gqlName => $gqlConfiguration] + $gqlTypes; |
|
236 | } |
||
237 | } |
||
238 | |||
239 | 25 | return $gqlTypes; |
|
240 | } |
||
241 | |||
242 | /** |
||
243 | * @throws ReflectionException |
||
244 | */ |
||
245 | 25 | private static function getGraphClass(string $className): GraphClass |
|
246 | { |
||
247 | 25 | self::$graphClassCache[$className] ??= new GraphClass($className); |
|
248 | |||
249 | 25 | return self::$graphClassCache[$className]; |
|
250 | } |
||
251 | |||
252 | 25 | private static function typeAnnotationToGQLConfiguration( |
|
253 | GraphClass $graphClass, |
||
254 | GQL\Type $classAnnotation, |
||
255 | string $gqlName, |
||
256 | array $configs |
||
257 | ): array { |
||
258 | 25 | $isMutation = $isDefault = $isRoot = false; |
|
259 | 25 | if (isset($configs['definitions']['schema'])) { |
|
260 | 24 | $defaultSchemaName = isset($configs['definitions']['schema']['default']) ? 'default' : array_key_first($configs['definitions']['schema']); |
|
261 | 24 | foreach ($configs['definitions']['schema'] as $schemaName => $schema) { |
|
262 | 24 | $schemaQuery = $schema['query'] ?? null; |
|
263 | 24 | $schemaMutation = $schema['mutation'] ?? null; |
|
264 | |||
265 | 24 | if ($gqlName === $schemaQuery) { |
|
266 | 24 | $isRoot = true; |
|
267 | 24 | if ($defaultSchemaName === $schemaName) { |
|
268 | 24 | $isDefault = true; |
|
269 | } |
||
270 | 24 | } elseif ($gqlName === $schemaMutation) { |
|
271 | 24 | $isMutation = true; |
|
272 | 24 | $isRoot = true; |
|
273 | 24 | if ($defaultSchemaName === $schemaName) { |
|
274 | 24 | $isDefault = true; |
|
275 | } |
||
276 | } |
||
277 | } |
||
278 | } |
||
279 | |||
280 | 25 | $currentValue = $isRoot ? sprintf("service('%s')", self::formatNamespaceForExpression($graphClass->getName())) : 'value'; |
|
281 | |||
282 | 25 | $gqlConfiguration = self::graphQLTypeConfigFromAnnotation($graphClass, $classAnnotation, $currentValue); |
|
283 | |||
284 | 25 | $providerFields = self::getGraphQLFieldsFromProviders($graphClass, $isMutation ? GQL\Mutation::class : GQL\Query::class, $gqlName, $isDefault); |
|
285 | 25 | $gqlConfiguration['config']['fields'] = array_merge($gqlConfiguration['config']['fields'], $providerFields); |
|
286 | |||
287 | 25 | if ($classAnnotation instanceof GQL\Relay\Edge) { |
|
288 | 24 | if (!$graphClass->implementsInterface(EdgeInterface::class)) { |
|
289 | throw new InvalidArgumentException(sprintf('The annotation @Edge on class "%s" can only be used on class implementing the EdgeInterface.', $graphClass->getName())); |
||
290 | } |
||
291 | 24 | if (!isset($gqlConfiguration['config']['builders'])) { |
|
292 | 24 | $gqlConfiguration['config']['builders'] = []; |
|
293 | } |
||
294 | 24 | array_unshift($gqlConfiguration['config']['builders'], ['builder' => 'relay-edge', 'builderConfig' => ['nodeType' => $classAnnotation->node]]); |
|
295 | } |
||
296 | |||
297 | 25 | return $gqlConfiguration; |
|
298 | } |
||
299 | |||
300 | 25 | private static function graphQLTypeConfigFromAnnotation(GraphClass $graphClass, GQL\Type $typeAnnotation, string $currentValue): array |
|
301 | { |
||
302 | 25 | $typeConfiguration = []; |
|
303 | 25 | $fieldsFromProperties = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $graphClass->getPropertiesExtended(), GQL\Field::class, $currentValue); |
|
304 | 25 | $fieldsFromMethods = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $graphClass->getMethods(), GQL\Field::class, $currentValue); |
|
305 | |||
306 | 25 | $typeConfiguration['fields'] = array_merge($fieldsFromProperties, $fieldsFromMethods); |
|
307 | 25 | $typeConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $typeConfiguration; |
|
308 | |||
309 | 25 | if (isset($typeAnnotation->interfaces)) { |
|
310 | 24 | $typeConfiguration['interfaces'] = $typeAnnotation->interfaces; |
|
311 | } else { |
||
312 | 25 | $interfaces = array_keys(self::searchClassesMapBy(function ($gqlType, $configuration) use ($graphClass) { |
|
313 | 24 | ['class' => $interfaceClassName] = $configuration; |
|
314 | |||
315 | 24 | $interfaceMetadata = self::getGraphClass($interfaceClassName); |
|
316 | 24 | if ($interfaceMetadata->isInterface() && $graphClass->implementsInterface($interfaceMetadata->getName())) { |
|
317 | 24 | return true; |
|
318 | } |
||
319 | |||
320 | 24 | return $graphClass->isSubclassOf($interfaceClassName); |
|
321 | 25 | }, self::GQL_INTERFACE)); |
|
322 | |||
323 | 25 | sort($interfaces); |
|
324 | 25 | $typeConfiguration['interfaces'] = $interfaces; |
|
325 | } |
||
326 | |||
327 | 25 | if (isset($typeAnnotation->resolveField)) { |
|
328 | 24 | $typeConfiguration['resolveField'] = self::formatExpression($typeAnnotation->resolveField); |
|
329 | } |
||
330 | |||
331 | 25 | if (isset($typeAnnotation->builders) && !empty($typeAnnotation->builders)) { |
|
332 | 24 | $typeConfiguration['builders'] = array_map(function ($fieldsBuilderAnnotation) { |
|
333 | 24 | return ['builder' => $fieldsBuilderAnnotation->builder, 'builderConfig' => $fieldsBuilderAnnotation->builderConfig]; |
|
334 | 24 | }, $typeAnnotation->builders); |
|
335 | } |
||
336 | |||
337 | 25 | if (isset($typeAnnotation->isTypeOf)) { |
|
338 | 24 | $typeConfiguration['isTypeOf'] = $typeAnnotation->isTypeOf; |
|
339 | } |
||
340 | |||
341 | 25 | $publicAnnotation = self::getFirstAnnotationMatching($graphClass->getAnnotations(), GQL\IsPublic::class); |
|
342 | 25 | if (null !== $publicAnnotation) { |
|
343 | 24 | $typeConfiguration['fieldsDefaultPublic'] = self::formatExpression($publicAnnotation->value); |
|
344 | } |
||
345 | |||
346 | 25 | $accessAnnotation = self::getFirstAnnotationMatching($graphClass->getAnnotations(), GQL\Access::class); |
|
347 | 25 | if (null !== $accessAnnotation) { |
|
348 | 24 | $typeConfiguration['fieldsDefaultAccess'] = self::formatExpression($accessAnnotation->value); |
|
349 | } |
||
350 | |||
351 | 25 | return ['type' => $typeAnnotation->isRelay ? 'relay-mutation-payload' : 'object', 'config' => $typeConfiguration]; |
|
352 | } |
||
353 | |||
354 | /** |
||
355 | * Create a GraphQL Interface type configuration from annotations on properties. |
||
356 | */ |
||
357 | 24 | private static function typeInterfaceAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\TypeInterface $interfaceAnnotation): array |
|
358 | { |
||
359 | 24 | $interfaceConfiguration = []; |
|
360 | |||
361 | 24 | $fieldsFromProperties = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $graphClass->getPropertiesExtended()); |
|
362 | 24 | $fieldsFromMethods = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $graphClass->getMethods()); |
|
363 | |||
364 | 24 | $interfaceConfiguration['fields'] = array_merge($fieldsFromProperties, $fieldsFromMethods); |
|
365 | 24 | $interfaceConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $interfaceConfiguration; |
|
366 | |||
367 | 24 | $interfaceConfiguration['resolveType'] = self::formatExpression($interfaceAnnotation->resolveType); |
|
368 | |||
369 | 24 | return ['type' => 'interface', 'config' => $interfaceConfiguration]; |
|
370 | } |
||
371 | |||
372 | /** |
||
373 | * Create a GraphQL Input type configuration from annotations on properties. |
||
374 | */ |
||
375 | 24 | private static function inputAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\Input $inputAnnotation): array |
|
376 | { |
||
377 | 24 | $inputConfiguration = array_merge([ |
|
378 | 24 | 'fields' => self::getGraphQLInputFieldsFromAnnotations($graphClass, $graphClass->getPropertiesExtended()), |
|
379 | 24 | ], self::getDescriptionConfiguration($graphClass->getAnnotations())); |
|
380 | |||
381 | 24 | return ['type' => $inputAnnotation->isRelay ? 'relay-mutation-input' : 'input-object', 'config' => $inputConfiguration]; |
|
382 | } |
||
383 | |||
384 | /** |
||
385 | * Get a GraphQL scalar configuration from given scalar annotation. |
||
386 | */ |
||
387 | 24 | private static function scalarAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\Scalar $scalarAnnotation): array |
|
388 | { |
||
389 | 24 | $scalarConfiguration = []; |
|
390 | |||
391 | 24 | if (isset($scalarAnnotation->scalarType)) { |
|
392 | 24 | $scalarConfiguration['scalarType'] = self::formatExpression($scalarAnnotation->scalarType); |
|
393 | } else { |
||
394 | $scalarConfiguration = [ |
||
395 | 24 | 'serialize' => [$graphClass->getName(), 'serialize'], |
|
396 | 24 | 'parseValue' => [$graphClass->getName(), 'parseValue'], |
|
397 | 24 | 'parseLiteral' => [$graphClass->getName(), 'parseLiteral'], |
|
398 | ]; |
||
399 | } |
||
400 | |||
401 | 24 | $scalarConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $scalarConfiguration; |
|
402 | |||
403 | 24 | return ['type' => 'custom-scalar', 'config' => $scalarConfiguration]; |
|
404 | } |
||
405 | |||
406 | /** |
||
407 | * Get a GraphQL Enum configuration from given enum annotation. |
||
408 | */ |
||
409 | 24 | private static function enumAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\Enum $enumAnnotation): array |
|
410 | { |
||
411 | 24 | $enumValues = $enumAnnotation->values ? $enumAnnotation->values : []; |
|
412 | |||
413 | 24 | $values = []; |
|
414 | |||
415 | 24 | foreach ($graphClass->getConstants() as $name => $value) { |
|
416 | 24 | $valueAnnotation = current(array_filter($enumValues, fn ($enumValueAnnotation) => $enumValueAnnotation->name == $name)); |
|
417 | 24 | $valueConfig = []; |
|
418 | 24 | $valueConfig['value'] = $value; |
|
419 | |||
420 | 24 | if ($valueAnnotation && isset($valueAnnotation->description)) { |
|
421 | 24 | $valueConfig['description'] = $valueAnnotation->description; |
|
422 | } |
||
423 | |||
424 | 24 | if ($valueAnnotation && isset($valueAnnotation->deprecationReason)) { |
|
425 | 24 | $valueConfig['deprecationReason'] = $valueAnnotation->deprecationReason; |
|
426 | } |
||
427 | |||
428 | 24 | $values[$name] = $valueConfig; |
|
429 | } |
||
430 | |||
431 | 24 | $enumConfiguration = ['values' => $values]; |
|
432 | 24 | $enumConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $enumConfiguration; |
|
433 | |||
434 | 24 | return ['type' => 'enum', 'config' => $enumConfiguration]; |
|
435 | } |
||
436 | |||
437 | /** |
||
438 | * Get a GraphQL Union configuration from given union annotation. |
||
439 | */ |
||
440 | 24 | private static function unionAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\Union $unionAnnotation): array |
|
478 | } |
||
479 | |||
480 | /** |
||
481 | * @phpstan-param ReflectionMethod|ReflectionProperty $reflector |
||
482 | * @phpstan-param class-string<GQL\Field> $fieldAnnotationName |
||
483 | * |
||
484 | * @throws AnnotationException |
||
485 | */ |
||
486 | 24 | private static function getTypeFieldConfigurationFromReflector(GraphClass $graphClass, Reflector $reflector, string $fieldAnnotationName, string $currentValue = 'value'): array |
|
609 | } |
||
610 | |||
611 | /** |
||
612 | * Create GraphQL input fields configuration based on annotations. |
||
613 | * |
||
614 | * @param ReflectionProperty[] $reflectors |
||
615 | * |
||
616 | * @throws AnnotationException |
||
617 | */ |
||
618 | 24 | private static function getGraphQLInputFieldsFromAnnotations(GraphClass $graphClass, array $reflectors): array |
|
619 | { |
||
620 | 24 | $fields = []; |
|
621 | |||
622 | 24 | foreach ($reflectors as $reflector) { |
|
623 | 24 | $annotations = $graphClass->getAnnotations($reflector); |
|
624 | |||
625 | /** @var GQL\Field|null $fieldAnnotation */ |
||
626 | 24 | $fieldAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Field::class); |
|
627 | |||
628 | // No field annotation found |
||
629 | 24 | if (!$fieldAnnotation) { |
|
630 | continue; |
||
631 | } |
||
632 | |||
633 | // Ignore field with resolver when the type is an Input |
||
634 | 24 | if (isset($fieldAnnotation->resolve)) { |
|
635 | return []; |
||
636 | } |
||
637 | |||
638 | 24 | $fieldName = $reflector->getName(); |
|
639 | 24 | $fieldType = $fieldAnnotation->type ?? self::guessType($graphClass, $annotations); |
|
640 | 24 | $fieldConfiguration = []; |
|
641 | 24 | if ($fieldType) { |
|
642 | // Resolve a PHP class from a GraphQL type |
||
643 | 24 | $resolvedType = self::$classesMap[$fieldType] ?? null; |
|
644 | // We found a type but it is not allowed |
||
645 | 24 | if (null !== $resolvedType && !in_array($resolvedType['type'], self::VALID_INPUT_TYPES)) { |
|
646 | throw new InvalidArgumentException(sprintf('The type "%s" on "%s" is a "%s" not valid on an Input @Field. Only Input, Scalar and Enum are allowed.', $fieldType, $reflector->getName(), $resolvedType['type'])); |
||
647 | } |
||
648 | |||
649 | 24 | $fieldConfiguration['type'] = $fieldType; |
|
650 | } |
||
651 | |||
652 | 24 | $fieldConfiguration = array_merge(self::getDescriptionConfiguration($annotations, true), $fieldConfiguration); |
|
653 | 24 | $fields[$fieldName] = $fieldConfiguration; |
|
654 | } |
||
655 | |||
656 | 24 | return $fields; |
|
657 | } |
||
658 | |||
659 | /** |
||
660 | * Create GraphQL type fields configuration based on annotations. |
||
661 | * |
||
662 | * @phpstan-param class-string<GQL\Field> $fieldAnnotationName |
||
663 | * |
||
664 | * @param ReflectionProperty[]|ReflectionMethod[] $reflectors |
||
665 | * |
||
666 | * @throws AnnotationException |
||
667 | */ |
||
668 | 25 | private static function getGraphQLTypeFieldsFromAnnotations(GraphClass $graphClass, array $reflectors, string $fieldAnnotationName = GQL\Field::class, string $currentValue = 'value'): array |
|
669 | { |
||
670 | 25 | $fields = []; |
|
671 | |||
672 | 25 | foreach ($reflectors as $reflector) { |
|
673 | 24 | $fields = array_merge($fields, self::getTypeFieldConfigurationFromReflector($graphClass, $reflector, $fieldAnnotationName, $currentValue)); |
|
674 | } |
||
675 | |||
676 | 25 | return $fields; |
|
677 | } |
||
678 | |||
679 | /** |
||
680 | * @phpstan-param class-string<GQL\Query|GQL\Mutation> $expectedAnnotation |
||
681 | * |
||
682 | * Return fields config from Provider methods. |
||
683 | * Loop through configured provider and extract fields targeting the targetType. |
||
684 | */ |
||
685 | 25 | private static function getGraphQLFieldsFromProviders(GraphClass $graphClass, string $expectedAnnotation, string $targetType, bool $isDefaultTarget = false): array |
|
686 | { |
||
687 | 25 | $fields = []; |
|
688 | 25 | foreach (self::$providers as ['metadata' => $providerMetadata, 'annotation' => $providerAnnotation]) { |
|
689 | 24 | $defaultAccessAnnotation = self::getFirstAnnotationMatching($providerMetadata->getAnnotations(), GQL\Access::class); |
|
690 | 24 | $defaultIsPublicAnnotation = self::getFirstAnnotationMatching($providerMetadata->getAnnotations(), GQL\IsPublic::class); |
|
691 | |||
692 | 24 | $defaultAccess = $defaultAccessAnnotation ? self::formatExpression($defaultAccessAnnotation->value) : false; |
|
693 | 24 | $defaultIsPublic = $defaultIsPublicAnnotation ? self::formatExpression($defaultIsPublicAnnotation->value) : false; |
|
694 | |||
695 | 24 | $methods = []; |
|
696 | // First found the methods matching the targeted type |
||
697 | 24 | foreach ($providerMetadata->getMethods() as $method) { |
|
698 | 24 | $annotations = $providerMetadata->getAnnotations($method); |
|
699 | |||
700 | 24 | $annotation = self::getFirstAnnotationMatching($annotations, [GQL\Mutation::class, GQL\Query::class]); |
|
701 | 24 | if (null === $annotation) { |
|
702 | continue; |
||
703 | } |
||
704 | |||
705 | 24 | $annotationTargets = $annotation->targetType ?? null; |
|
706 | |||
707 | 24 | if (null === $annotationTargets) { |
|
708 | 24 | if ($isDefaultTarget) { |
|
709 | 24 | $annotationTargets = [$targetType]; |
|
710 | 24 | if (!$annotation instanceof $expectedAnnotation) { |
|
711 | 24 | continue; |
|
712 | } |
||
713 | } else { |
||
714 | 24 | continue; |
|
715 | } |
||
716 | } |
||
717 | |||
718 | 24 | if (!in_array($targetType, $annotationTargets)) { |
|
719 | 24 | continue; |
|
720 | } |
||
721 | |||
722 | 24 | if (!$annotation instanceof $expectedAnnotation) { |
|
723 | 2 | if (GQL\Mutation::class == $expectedAnnotation) { |
|
724 | 1 | $message = sprintf('The provider "%s" try to add a query field on type "%s" (through @Query on method "%s") but "%s" is a mutation.', $providerMetadata->getName(), $targetType, $method->getName(), $targetType); |
|
725 | } else { |
||
726 | 1 | $message = sprintf('The provider "%s" try to add a mutation on type "%s" (through @Mutation on method "%s") but "%s" is not a mutation.', $providerMetadata->getName(), $targetType, $method->getName(), $targetType); |
|
727 | } |
||
728 | |||
729 | 2 | throw new InvalidArgumentException($message); |
|
730 | } |
||
731 | 24 | $methods[$method->getName()] = $method; |
|
732 | } |
||
733 | |||
734 | 24 | $currentValue = sprintf("service('%s')", self::formatNamespaceForExpression($providerMetadata->getName())); |
|
735 | 24 | $providerFields = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $methods, $expectedAnnotation, $currentValue); |
|
736 | 24 | foreach ($providerFields as $fieldName => $fieldConfig) { |
|
737 | 24 | if ($providerAnnotation->prefix) { |
|
738 | 24 | $fieldName = sprintf('%s%s', $providerAnnotation->prefix, $fieldName); |
|
739 | } |
||
740 | |||
741 | 24 | if ($defaultAccess && !isset($fieldConfig['access'])) { |
|
742 | 24 | $fieldConfig['access'] = $defaultAccess; |
|
743 | } |
||
744 | |||
745 | 24 | if ($defaultIsPublic && !isset($fieldConfig['public'])) { |
|
746 | 24 | $fieldConfig['public'] = $defaultIsPublic; |
|
747 | } |
||
748 | |||
749 | 24 | $fields[$fieldName] = $fieldConfig; |
|
750 | } |
||
751 | } |
||
752 | |||
753 | 25 | return $fields; |
|
754 | } |
||
755 | |||
756 | /** |
||
757 | * Get the config for description & deprecation reason. |
||
758 | */ |
||
759 | 25 | private static function getDescriptionConfiguration(array $annotations, bool $withDeprecation = false): array |
|
760 | { |
||
761 | 25 | $config = []; |
|
762 | 25 | $descriptionAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Description::class); |
|
763 | 25 | if (null !== $descriptionAnnotation) { |
|
764 | 24 | $config['description'] = $descriptionAnnotation->value; |
|
765 | } |
||
766 | |||
767 | 25 | if ($withDeprecation) { |
|
768 | 24 | $deprecatedAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Deprecated::class); |
|
769 | 24 | if (null !== $deprecatedAnnotation) { |
|
770 | 24 | $config['deprecationReason'] = $deprecatedAnnotation->value; |
|
771 | } |
||
772 | } |
||
773 | |||
774 | 25 | return $config; |
|
775 | } |
||
776 | |||
777 | /** |
||
778 | * Format an array of args to a list of arguments in an expression. |
||
779 | */ |
||
780 | 24 | private static function formatArgsForExpression(array $args): string |
|
781 | { |
||
782 | 24 | $mapping = []; |
|
783 | 24 | foreach ($args as $name => $config) { |
|
784 | 24 | $mapping[] = sprintf('%s: "%s"', $name, $config['type']); |
|
785 | } |
||
786 | |||
787 | 24 | return sprintf('arguments({%s}, args)', implode(', ', $mapping)); |
|
788 | } |
||
789 | |||
790 | /** |
||
791 | * Format a namespace to be used in an expression (double escape). |
||
792 | */ |
||
793 | 24 | private static function formatNamespaceForExpression(string $namespace): string |
|
794 | { |
||
795 | 24 | return str_replace('\\', '\\\\', $namespace); |
|
796 | } |
||
797 | |||
798 | /** |
||
799 | * Get the first annotation matching given class. |
||
800 | * |
||
801 | * @phpstan-template T of object |
||
802 | * @phpstan-param class-string<T>|class-string<T>[] $annotationClass |
||
803 | * @phpstan-return T|null |
||
804 | * |
||
805 | * @param string|array $annotationClass |
||
806 | * |
||
807 | * @return object|null |
||
808 | */ |
||
809 | 25 | private static function getFirstAnnotationMatching(array $annotations, $annotationClass) |
|
810 | { |
||
811 | 25 | if (is_string($annotationClass)) { |
|
812 | 25 | $annotationClass = [$annotationClass]; |
|
813 | } |
||
814 | |||
815 | 25 | foreach ($annotations as $annotation) { |
|
816 | 25 | foreach ($annotationClass as $class) { |
|
817 | 25 | if ($annotation instanceof $class) { |
|
818 | 24 | return $annotation; |
|
819 | } |
||
820 | } |
||
821 | } |
||
822 | |||
823 | 25 | return null; |
|
824 | } |
||
825 | |||
826 | /** |
||
827 | * Format an expression (ie. add "@=" if not set). |
||
828 | */ |
||
829 | 24 | private static function formatExpression(string $expression): string |
|
830 | { |
||
831 | 24 | return '@=' === substr($expression, 0, 2) ? $expression : sprintf('@=%s', $expression); |
|
832 | } |
||
833 | |||
834 | /** |
||
835 | * Suffix a name if it is not already. |
||
836 | */ |
||
837 | 24 | private static function suffixName(string $name, string $suffix): string |
|
838 | { |
||
839 | 24 | return substr($name, -strlen($suffix)) === $suffix ? $name : sprintf('%s%s', $name, $suffix); |
|
840 | } |
||
841 | |||
842 | /** |
||
843 | * Try to guess a field type base on his annotations. |
||
844 | * |
||
845 | * @throws RuntimeException |
||
846 | */ |
||
847 | 24 | private static function guessType(GraphClass $graphClass, array $annotations): string |
|
848 | { |
||
849 | 24 | $columnAnnotation = self::getFirstAnnotationMatching($annotations, Column::class); |
|
850 | 24 | if (null !== $columnAnnotation) { |
|
851 | 24 | $type = self::resolveTypeFromDoctrineType($columnAnnotation->type); |
|
852 | 24 | $nullable = $columnAnnotation->nullable; |
|
853 | 24 | if ($type) { |
|
854 | 24 | return $nullable ? $type : sprintf('%s!', $type); |
|
855 | } else { |
||
856 | 1 | throw new RuntimeException(sprintf('Unable to auto-guess GraphQL type from Doctrine type "%s"', $columnAnnotation->type)); |
|
857 | } |
||
858 | } |
||
859 | |||
860 | $associationAnnotations = [ |
||
861 | 24 | OneToMany::class => true, |
|
862 | OneToOne::class => false, |
||
863 | ManyToMany::class => true, |
||
864 | ManyToOne::class => false, |
||
865 | ]; |
||
866 | |||
867 | 24 | $associationAnnotation = self::getFirstAnnotationMatching($annotations, array_keys($associationAnnotations)); |
|
868 | 24 | if (null !== $associationAnnotation) { |
|
869 | 24 | $target = self::fullyQualifiedClassName($associationAnnotation->targetEntity, $graphClass->getNamespaceName()); |
|
870 | 24 | $type = self::resolveTypeFromClass($target, ['type']); |
|
871 | |||
872 | 24 | if ($type) { |
|
873 | 24 | $isMultiple = $associationAnnotations[get_class($associationAnnotation)]; |
|
874 | 24 | if ($isMultiple) { |
|
875 | 24 | return sprintf('[%s]!', $type); |
|
876 | } else { |
||
877 | 24 | $isNullable = false; |
|
878 | 24 | $joinColumn = self::getFirstAnnotationMatching($annotations, JoinColumn::class); |
|
879 | 24 | if (null !== $joinColumn) { |
|
880 | 24 | $isNullable = $joinColumn->nullable; |
|
881 | } |
||
882 | |||
883 | 24 | return sprintf('%s%s', $type, $isNullable ? '' : '!'); |
|
884 | } |
||
885 | } else { |
||
886 | 1 | throw new RuntimeException(sprintf('Unable to auto-guess GraphQL type from Doctrine target class "%s" (check if the target class is a GraphQL type itself (with a @GQL\Type annotation).', $target)); |
|
887 | } |
||
888 | } |
||
889 | |||
890 | throw new InvalidArgumentException(sprintf('No Doctrine ORM annotation found.')); |
||
891 | } |
||
892 | |||
893 | /** |
||
894 | * Resolve a FQN from classname and namespace. |
||
895 | * |
||
896 | * @internal |
||
897 | */ |
||
898 | 24 | public static function fullyQualifiedClassName(string $className, string $namespace): string |
|
905 | } |
||
906 | |||
907 | /** |
||
908 | * Resolve a GraphQLType from a doctrine type. |
||
909 | */ |
||
910 | 24 | private static function resolveTypeFromDoctrineType(string $doctrineType): ?string |
|
911 | { |
||
912 | 24 | if (isset(self::$doctrineMapping[$doctrineType])) { |
|
913 | 24 | return self::$doctrineMapping[$doctrineType]; |
|
914 | } |
||
915 | |||
916 | switch ($doctrineType) { |
||
917 | 24 | case 'integer': |
|
918 | 24 | case 'smallint': |
|
919 | 24 | case 'bigint': |
|
920 | 24 | return 'Int'; |
|
921 | 24 | case 'string': |
|
922 | 1 | case 'text': |
|
923 | 24 | return 'String'; |
|
924 | 1 | case 'bool': |
|
925 | 1 | case 'boolean': |
|
926 | return 'Boolean'; |
||
927 | 1 | case 'float': |
|
928 | 1 | case 'decimal': |
|
929 | return 'Float'; |
||
930 | default: |
||
931 | 1 | return null; |
|
932 | } |
||
933 | } |
||
934 | |||
935 | /** |
||
936 | * Transform a method arguments from reflection to a list of GraphQL argument. |
||
937 | */ |
||
938 | 24 | private static function guessArgs(ReflectionMethod $method): array |
|
939 | { |
||
940 | 24 | $arguments = []; |
|
941 | 24 | foreach ($method->getParameters() as $index => $parameter) { |
|
942 | 24 | if (!$parameter->hasType()) { |
|
943 | 1 | throw new InvalidArgumentException(sprintf('Argument n°%s "$%s" on method "%s" cannot be auto-guessed as there is not type hint.', $index + 1, $parameter->getName(), $method->getName())); |
|
944 | } |
||
945 | |||
946 | try { |
||
947 | // @phpstan-ignore-next-line |
||
948 | 24 | $gqlType = self::resolveGraphQLTypeFromReflectionType($parameter->getType(), self::VALID_INPUT_TYPES, $parameter->isDefaultValueAvailable()); |
|
949 | } catch (Exception $e) { |
||
950 | throw new InvalidArgumentException(sprintf('Argument n°%s "$%s" on method "%s" cannot be auto-guessed : %s".', $index + 1, $parameter->getName(), $method->getName(), $e->getMessage())); |
||
951 | } |
||
952 | |||
953 | 24 | $argumentConfig = []; |
|
954 | 24 | if ($parameter->isDefaultValueAvailable()) { |
|
955 | 24 | $argumentConfig['defaultValue'] = $parameter->getDefaultValue(); |
|
956 | } |
||
957 | |||
958 | 24 | $argumentConfig['type'] = $gqlType; |
|
959 | |||
960 | 24 | $arguments[$parameter->getName()] = $argumentConfig; |
|
961 | } |
||
962 | |||
963 | 24 | return $arguments; |
|
964 | } |
||
965 | |||
966 | 24 | private static function resolveGraphQLTypeFromReflectionType(ReflectionNamedType $type, array $filterGraphQLTypes = [], bool $isOptional = false): string |
|
967 | { |
||
968 | 24 | $sType = $type->getName(); |
|
969 | 24 | if ($type->isBuiltin()) { |
|
970 | 24 | $gqlType = self::resolveTypeFromPhpType($sType); |
|
971 | 24 | if (null === $gqlType) { |
|
972 | 24 | throw new RuntimeException(sprintf('No corresponding GraphQL type found for builtin type "%s"', $sType)); |
|
973 | } |
||
974 | } else { |
||
975 | 24 | $gqlType = self::resolveTypeFromClass($sType, $filterGraphQLTypes); |
|
976 | 24 | if (null === $gqlType) { |
|
977 | throw new RuntimeException(sprintf('No corresponding GraphQL %s found for class "%s"', $filterGraphQLTypes ? implode(',', $filterGraphQLTypes) : 'object', $sType)); |
||
978 | } |
||
979 | } |
||
980 | |||
981 | 24 | return sprintf('%s%s', $gqlType, ($type->allowsNull() || $isOptional) ? '' : '!'); |
|
982 | } |
||
983 | |||
984 | /** |
||
985 | * Resolve a GraphQL Type from a class name. |
||
986 | */ |
||
987 | 24 | private static function resolveTypeFromClass(string $className, array $wantedTypes = []): ?string |
|
988 | { |
||
989 | 24 | foreach (self::$classesMap as $gqlType => $config) { |
|
990 | 24 | if ($config['class'] === $className) { |
|
991 | 24 | if (in_array($config['type'], $wantedTypes)) { |
|
992 | 24 | return $gqlType; |
|
993 | } |
||
994 | } |
||
995 | } |
||
996 | |||
997 | 1 | return null; |
|
998 | } |
||
999 | |||
1000 | /** |
||
1001 | * Search the classes map for class by predicate. |
||
1002 | * |
||
1003 | * @return array |
||
1004 | */ |
||
1005 | 25 | private static function searchClassesMapBy(callable $predicate, string $type) |
|
1006 | { |
||
1007 | 25 | $classNames = []; |
|
1008 | 25 | foreach (self::$classesMap as $gqlType => $config) { |
|
1009 | 25 | if ($config['type'] !== $type) { |
|
1010 | 25 | continue; |
|
1011 | } |
||
1012 | |||
1013 | 24 | if ($predicate($gqlType, $config)) { |
|
1014 | 24 | $classNames[$gqlType] = $config; |
|
1015 | } |
||
1016 | } |
||
1017 | |||
1018 | 25 | return $classNames; |
|
1019 | } |
||
1020 | |||
1021 | /** |
||
1022 | * Convert a PHP Builtin type to a GraphQL type. |
||
1023 | */ |
||
1024 | 24 | private static function resolveTypeFromPhpType(string $phpType): ?string |
|
1040 | } |
||
1041 | } |
||
1042 | } |
||
1043 |