We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.
| Total Complexity | 172 |
| Total Lines | 906 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Complex classes like MetadataParser 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 MetadataParser, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 44 | abstract class MetadataParser implements PreParserInterface |
||
| 45 | { |
||
| 46 | const ANNOTATION_NAMESPACE = 'Overblog\GraphQLBundle\Annotation\\'; |
||
| 47 | const METADATA_FORMAT = '%s'; |
||
| 48 | |||
| 49 | private static ClassesTypesMap $map; |
||
| 50 | private static array $typeGuessers = []; |
||
| 51 | private static array $providers = []; |
||
| 52 | private static array $reflections = []; |
||
| 53 | |||
| 54 | private const GQL_SCALAR = 'scalar'; |
||
| 55 | private const GQL_ENUM = 'enum'; |
||
| 56 | private const GQL_TYPE = 'type'; |
||
| 57 | private const GQL_INPUT = 'input'; |
||
| 58 | private const GQL_UNION = 'union'; |
||
| 59 | private const GQL_INTERFACE = 'interface'; |
||
| 60 | |||
| 61 | /** |
||
| 62 | * @see https://facebook.github.io/graphql/draft/#sec-Input-and-Output-Types |
||
| 63 | */ |
||
| 64 | private const VALID_INPUT_TYPES = [self::GQL_SCALAR, self::GQL_ENUM, self::GQL_INPUT]; |
||
| 65 | private const VALID_OUTPUT_TYPES = [self::GQL_SCALAR, self::GQL_TYPE, self::GQL_INTERFACE, self::GQL_UNION, self::GQL_ENUM]; |
||
| 66 | |||
| 67 | /** |
||
| 68 | * {@inheritdoc} |
||
| 69 | * |
||
| 70 | * @throws InvalidArgumentException |
||
| 71 | * @throws ReflectionException |
||
| 72 | */ |
||
| 73 | public static function preParse(SplFileInfo $file, ContainerBuilder $container, array $configs = []): void |
||
| 74 | { |
||
| 75 | $container->setParameter('overblog_graphql_types.classes_map', self::processFile($file, $container, $configs, true)); |
||
| 76 | } |
||
| 77 | |||
| 78 | /** |
||
| 79 | * @throws InvalidArgumentException |
||
| 80 | * @throws ReflectionException |
||
| 81 | */ |
||
| 82 | public static function parse(SplFileInfo $file, ContainerBuilder $container, array $configs = []): array |
||
| 83 | { |
||
| 84 | return self::processFile($file, $container, $configs, false); |
||
| 85 | } |
||
| 86 | |||
| 87 | /** |
||
| 88 | * @internal |
||
| 89 | */ |
||
| 90 | public static function reset(array $configs): void |
||
| 91 | { |
||
| 92 | self::$map = new ClassesTypesMap(); |
||
| 93 | self::$typeGuessers = [ |
||
| 94 | new DocBlockTypeGuesser(self::$map), |
||
| 95 | new TypeHintTypeGuesser(self::$map), |
||
| 96 | new DoctrineTypeGuesser(self::$map, $configs['doctrine']['types_mapping']), |
||
| 97 | ]; |
||
| 98 | self::$providers = []; |
||
| 99 | self::$reflections = []; |
||
| 100 | } |
||
| 101 | |||
| 102 | /** |
||
| 103 | * Process a file. |
||
| 104 | * |
||
| 105 | * @throws InvalidArgumentException|ReflectionException|AnnotationException |
||
| 106 | */ |
||
| 107 | private static function processFile(SplFileInfo $file, ContainerBuilder $container, array $configs, bool $preProcess): array |
||
| 108 | { |
||
| 109 | $container->addResource(new FileResource($file->getRealPath())); |
||
| 110 | |||
| 111 | try { |
||
| 112 | $className = $file->getBasename('.php'); |
||
| 113 | if (preg_match('#namespace (.+);#', file_get_contents($file->getRealPath()), $matches)) { |
||
| 114 | $className = trim($matches[1]).'\\'.$className; |
||
| 115 | } |
||
| 116 | |||
| 117 | $gqlTypes = []; |
||
| 118 | $reflectionClass = self::getClassReflection($className); |
||
| 119 | |||
| 120 | foreach (static::getMetadatas($reflectionClass) as $classMetadata) { |
||
| 121 | if ($classMetadata instanceof Meta) { |
||
| 122 | $gqlTypes = self::classMetadatasToGQLConfiguration( |
||
| 123 | $reflectionClass, |
||
| 124 | $classMetadata, |
||
| 125 | $configs, |
||
| 126 | $gqlTypes, |
||
| 127 | $preProcess |
||
| 128 | ); |
||
| 129 | } |
||
| 130 | } |
||
| 131 | |||
| 132 | return $preProcess ? self::$map->toArray() : $gqlTypes; |
||
| 133 | } catch (\InvalidArgumentException $e) { |
||
| 134 | throw new InvalidArgumentException(sprintf('Failed to parse GraphQL metadata from file "%s".', $file), $e->getCode(), $e); |
||
| 135 | } |
||
| 136 | } |
||
| 137 | |||
| 138 | private static function classMetadatasToGQLConfiguration( |
||
| 139 | ReflectionClass $reflectionClass, |
||
| 140 | Meta $classMetadata, |
||
| 141 | array $configs, |
||
| 142 | array $gqlTypes, |
||
| 143 | bool $preProcess |
||
| 144 | ): array { |
||
| 145 | $gqlConfiguration = $gqlType = $gqlName = null; |
||
| 146 | |||
| 147 | switch (true) { |
||
| 148 | case $classMetadata instanceof Metadata\Type: |
||
| 149 | $gqlType = self::GQL_TYPE; |
||
| 150 | $gqlName = $classMetadata->name ?? $reflectionClass->getShortName(); |
||
| 151 | if (!$preProcess) { |
||
| 152 | $gqlConfiguration = self::typeMetadataToGQLConfiguration($reflectionClass, $classMetadata, $gqlName, $configs); |
||
| 153 | |||
| 154 | if ($classMetadata instanceof Metadata\Relay\Connection) { |
||
| 155 | if (!$reflectionClass->implementsInterface(ConnectionInterface::class)) { |
||
| 156 | throw new InvalidArgumentException(sprintf('The metadata %s on class "%s" can only be used on class implementing the ConnectionInterface.', self::formatMetadata('Connection'), $reflectionClass->getName())); |
||
| 157 | } |
||
| 158 | |||
| 159 | if (!(isset($classMetadata->edge) xor isset($classMetadata->node))) { |
||
| 160 | throw new InvalidArgumentException(sprintf('The metadata %s on class "%s" is invalid. You must define either the "edge" OR the "node" attribute, but not both.', self::formatMetadata('Connection'), $reflectionClass->getName())); |
||
| 161 | } |
||
| 162 | |||
| 163 | $edgeType = $classMetadata->edge ?? false; |
||
| 164 | if (!$edgeType) { |
||
| 165 | $edgeType = $gqlName.'Edge'; |
||
| 166 | $gqlTypes[$edgeType] = [ |
||
| 167 | 'type' => 'object', |
||
| 168 | 'config' => [ |
||
| 169 | 'builders' => [ |
||
| 170 | ['builder' => 'relay-edge', 'builderConfig' => ['nodeType' => $classMetadata->node]], |
||
| 171 | ], |
||
| 172 | ], |
||
| 173 | ]; |
||
| 174 | } |
||
| 175 | |||
| 176 | if (!isset($gqlConfiguration['config']['builders'])) { |
||
| 177 | $gqlConfiguration['config']['builders'] = []; |
||
| 178 | } |
||
| 179 | |||
| 180 | array_unshift($gqlConfiguration['config']['builders'], ['builder' => 'relay-connection', 'builderConfig' => ['edgeType' => $edgeType]]); |
||
| 181 | } |
||
| 182 | } |
||
| 183 | break; |
||
| 184 | |||
| 185 | case $classMetadata instanceof Metadata\Input: |
||
| 186 | $gqlType = self::GQL_INPUT; |
||
| 187 | $gqlName = $classMetadata->name ?? self::suffixName($reflectionClass->getShortName(), 'Input'); |
||
| 188 | if (!$preProcess) { |
||
| 189 | $gqlConfiguration = self::inputMetadataToGQLConfiguration($reflectionClass, $classMetadata); |
||
| 190 | } |
||
| 191 | break; |
||
| 192 | |||
| 193 | case $classMetadata instanceof Metadata\Scalar: |
||
| 194 | $gqlType = self::GQL_SCALAR; |
||
| 195 | if (!$preProcess) { |
||
| 196 | $gqlConfiguration = self::scalarMetadataToGQLConfiguration($reflectionClass, $classMetadata); |
||
| 197 | } |
||
| 198 | break; |
||
| 199 | |||
| 200 | case $classMetadata instanceof Metadata\Enum: |
||
| 201 | $gqlType = self::GQL_ENUM; |
||
| 202 | if (!$preProcess) { |
||
| 203 | $gqlConfiguration = self::enumMetadataToGQLConfiguration($reflectionClass, $classMetadata); |
||
| 204 | } |
||
| 205 | break; |
||
| 206 | |||
| 207 | case $classMetadata instanceof Metadata\Union: |
||
| 208 | $gqlType = self::GQL_UNION; |
||
| 209 | if (!$preProcess) { |
||
| 210 | $gqlConfiguration = self::unionMetadataToGQLConfiguration($reflectionClass, $classMetadata); |
||
| 211 | } |
||
| 212 | break; |
||
| 213 | |||
| 214 | case $classMetadata instanceof Metadata\TypeInterface: |
||
| 215 | $gqlType = self::GQL_INTERFACE; |
||
| 216 | if (!$preProcess) { |
||
| 217 | $gqlConfiguration = self::typeInterfaceMetadataToGQLConfiguration($reflectionClass, $classMetadata); |
||
| 218 | } |
||
| 219 | break; |
||
| 220 | |||
| 221 | case $classMetadata instanceof Metadata\Provider: |
||
| 222 | if ($preProcess) { |
||
| 223 | self::$providers[] = ['reflectionClass' => $reflectionClass, 'metadata' => $classMetadata]; |
||
| 224 | } |
||
| 225 | |||
| 226 | return []; |
||
| 227 | } |
||
| 228 | |||
| 229 | if (null !== $gqlType) { |
||
| 230 | if (!$gqlName) { |
||
| 231 | $gqlName = isset($classMetadata->name) ? $classMetadata->name : $reflectionClass->getShortName(); |
||
| 232 | } |
||
| 233 | |||
| 234 | if ($preProcess) { |
||
| 235 | if (self::$map->hasType($gqlName)) { |
||
|
|
|||
| 236 | throw new InvalidArgumentException(sprintf('The GraphQL type "%s" has already been registered in class "%s"', $gqlName, self::$map->getType($gqlName)['class'])); |
||
| 237 | } |
||
| 238 | self::$map->addClassType($gqlName, $reflectionClass->getName(), $gqlType); |
||
| 239 | } else { |
||
| 240 | $gqlTypes = [$gqlName => $gqlConfiguration] + $gqlTypes; |
||
| 241 | } |
||
| 242 | } |
||
| 243 | |||
| 244 | return $gqlTypes; |
||
| 245 | } |
||
| 246 | |||
| 247 | /** |
||
| 248 | * @throws ReflectionException |
||
| 249 | */ |
||
| 250 | private static function getClassReflection(string $className): ReflectionClass |
||
| 251 | { |
||
| 252 | self::$reflections[$className] ??= new ReflectionClass($className); |
||
| 253 | |||
| 254 | return self::$reflections[$className]; |
||
| 255 | } |
||
| 256 | |||
| 257 | private static function typeMetadataToGQLConfiguration( |
||
| 258 | ReflectionClass $reflectionClass, |
||
| 259 | Metadata\Type $classMetadata, |
||
| 260 | string $gqlName, |
||
| 261 | array $configs |
||
| 262 | ): array { |
||
| 263 | $isMutation = $isDefault = $isRoot = false; |
||
| 264 | if (isset($configs['definitions']['schema'])) { |
||
| 265 | $defaultSchemaName = isset($configs['definitions']['schema']['default']) ? 'default' : array_key_first($configs['definitions']['schema']); |
||
| 266 | foreach ($configs['definitions']['schema'] as $schemaName => $schema) { |
||
| 267 | $schemaQuery = $schema['query'] ?? null; |
||
| 268 | $schemaMutation = $schema['mutation'] ?? null; |
||
| 269 | |||
| 270 | if ($gqlName === $schemaQuery) { |
||
| 271 | $isRoot = true; |
||
| 272 | if ($defaultSchemaName === $schemaName) { |
||
| 273 | $isDefault = true; |
||
| 274 | } |
||
| 275 | } elseif ($gqlName === $schemaMutation) { |
||
| 276 | $isMutation = true; |
||
| 277 | $isRoot = true; |
||
| 278 | if ($defaultSchemaName === $schemaName) { |
||
| 279 | $isDefault = true; |
||
| 280 | } |
||
| 281 | } |
||
| 282 | } |
||
| 283 | } |
||
| 284 | |||
| 285 | $currentValue = $isRoot ? sprintf("service('%s')", self::formatNamespaceForExpression($reflectionClass->getName())) : 'value'; |
||
| 286 | |||
| 287 | $gqlConfiguration = self::graphQLTypeConfigFromAnnotation($reflectionClass, $classMetadata, $currentValue); |
||
| 288 | |||
| 289 | $providerFields = self::getGraphQLFieldsFromProviders($reflectionClass, $isMutation ? Metadata\Mutation::class : Metadata\Query::class, $gqlName, $isDefault); |
||
| 290 | $gqlConfiguration['config']['fields'] = array_merge($gqlConfiguration['config']['fields'], $providerFields); |
||
| 291 | |||
| 292 | if ($classMetadata instanceof Metadata\Relay\Edge) { |
||
| 293 | if (!$reflectionClass->implementsInterface(EdgeInterface::class)) { |
||
| 294 | throw new InvalidArgumentException(sprintf('The metadata %s on class "%s" can only be used on class implementing the EdgeInterface.', self::formatMetadata('Edge'), $reflectionClass->getName())); |
||
| 295 | } |
||
| 296 | if (!isset($gqlConfiguration['config']['builders'])) { |
||
| 297 | $gqlConfiguration['config']['builders'] = []; |
||
| 298 | } |
||
| 299 | array_unshift($gqlConfiguration['config']['builders'], ['builder' => 'relay-edge', 'builderConfig' => ['nodeType' => $classMetadata->node]]); |
||
| 300 | } |
||
| 301 | |||
| 302 | return $gqlConfiguration; |
||
| 303 | } |
||
| 304 | |||
| 305 | private static function graphQLTypeConfigFromAnnotation(ReflectionClass $reflectionClass, Metadata\Type $typeAnnotation, string $currentValue): array |
||
| 306 | { |
||
| 307 | $typeConfiguration = []; |
||
| 308 | $metadatas = static::getMetadatas($reflectionClass); |
||
| 309 | |||
| 310 | $fieldsFromProperties = self::getGraphQLTypeFieldsFromAnnotations($reflectionClass, self::getClassProperties($reflectionClass), Metadata\Field::class, $currentValue); |
||
| 311 | $fieldsFromMethods = self::getGraphQLTypeFieldsFromAnnotations($reflectionClass, $reflectionClass->getMethods(), Metadata\Field::class, $currentValue); |
||
| 312 | |||
| 313 | $typeConfiguration['fields'] = array_merge($fieldsFromProperties, $fieldsFromMethods); |
||
| 314 | $typeConfiguration = self::getDescriptionConfiguration($metadatas) + $typeConfiguration; |
||
| 315 | |||
| 316 | if (!empty($typeAnnotation->interfaces)) { |
||
| 317 | $typeConfiguration['interfaces'] = $typeAnnotation->interfaces; |
||
| 318 | } else { |
||
| 319 | $interfaces = array_keys(self::$map->searchClassesMapBy(function ($gqlType, $configuration) use ($reflectionClass) { |
||
| 320 | ['class' => $interfaceClassName] = $configuration; |
||
| 321 | |||
| 322 | $interfaceMetadata = self::getClassReflection($interfaceClassName); |
||
| 323 | if ($interfaceMetadata->isInterface() && $reflectionClass->implementsInterface($interfaceMetadata->getName())) { |
||
| 324 | return true; |
||
| 325 | } |
||
| 326 | |||
| 327 | return $reflectionClass->isSubclassOf($interfaceClassName); |
||
| 328 | }, self::GQL_INTERFACE)); |
||
| 329 | |||
| 330 | sort($interfaces); |
||
| 331 | $typeConfiguration['interfaces'] = $interfaces; |
||
| 332 | } |
||
| 333 | |||
| 334 | if (isset($typeAnnotation->resolveField)) { |
||
| 335 | $typeConfiguration['resolveField'] = self::formatExpression($typeAnnotation->resolveField); |
||
| 336 | } |
||
| 337 | |||
| 338 | $buildersAnnotations = array_merge(self::getMetadataMatching($metadatas, Metadata\FieldsBuilder::class), $typeAnnotation->builders); |
||
| 339 | if (!empty($buildersAnnotations)) { |
||
| 340 | $typeConfiguration['builders'] = array_map(function ($fieldsBuilderAnnotation) { |
||
| 341 | return ['builder' => $fieldsBuilderAnnotation->builder, 'builderConfig' => $fieldsBuilderAnnotation->builderConfig]; |
||
| 342 | }, $buildersAnnotations); |
||
| 343 | } |
||
| 344 | |||
| 345 | if (isset($typeAnnotation->isTypeOf)) { |
||
| 346 | $typeConfiguration['isTypeOf'] = $typeAnnotation->isTypeOf; |
||
| 347 | } |
||
| 348 | |||
| 349 | $publicMetadata = self::getFirstMetadataMatching($metadatas, Metadata\IsPublic::class); |
||
| 350 | if (null !== $publicMetadata) { |
||
| 351 | $typeConfiguration['fieldsDefaultPublic'] = self::formatExpression($publicMetadata->value); |
||
| 352 | } |
||
| 353 | |||
| 354 | $accessMetadata = self::getFirstMetadataMatching($metadatas, Metadata\Access::class); |
||
| 355 | if (null !== $accessMetadata) { |
||
| 356 | $typeConfiguration['fieldsDefaultAccess'] = self::formatExpression($accessMetadata->value); |
||
| 357 | } |
||
| 358 | |||
| 359 | return ['type' => $typeAnnotation->isRelay ? 'relay-mutation-payload' : 'object', 'config' => $typeConfiguration]; |
||
| 360 | } |
||
| 361 | |||
| 362 | /** |
||
| 363 | * Create a GraphQL Interface type configuration from metadatas on properties. |
||
| 364 | */ |
||
| 365 | private static function typeInterfaceMetadataToGQLConfiguration(ReflectionClass $reflectionClass, Metadata\TypeInterface $interfaceAnnotation): array |
||
| 366 | { |
||
| 367 | $interfaceConfiguration = []; |
||
| 368 | |||
| 369 | $fieldsFromProperties = self::getGraphQLTypeFieldsFromAnnotations($reflectionClass, self::getClassProperties($reflectionClass)); |
||
| 370 | $fieldsFromMethods = self::getGraphQLTypeFieldsFromAnnotations($reflectionClass, $reflectionClass->getMethods()); |
||
| 371 | |||
| 372 | $interfaceConfiguration['fields'] = array_merge($fieldsFromProperties, $fieldsFromMethods); |
||
| 373 | $interfaceConfiguration = self::getDescriptionConfiguration(static::getMetadatas($reflectionClass)) + $interfaceConfiguration; |
||
| 374 | |||
| 375 | $interfaceConfiguration['resolveType'] = self::formatExpression($interfaceAnnotation->resolveType); |
||
| 376 | |||
| 377 | return ['type' => 'interface', 'config' => $interfaceConfiguration]; |
||
| 378 | } |
||
| 379 | |||
| 380 | /** |
||
| 381 | * Create a GraphQL Input type configuration from metadatas on properties. |
||
| 382 | */ |
||
| 383 | private static function inputMetadataToGQLConfiguration(ReflectionClass $reflectionClass, Metadata\Input $inputAnnotation): array |
||
| 384 | { |
||
| 385 | $inputConfiguration = array_merge([ |
||
| 386 | 'fields' => self::getGraphQLInputFieldsFromMetadatas($reflectionClass, self::getClassProperties($reflectionClass)), |
||
| 387 | ], self::getDescriptionConfiguration(static::getMetadatas($reflectionClass))); |
||
| 388 | |||
| 389 | return ['type' => $inputAnnotation->isRelay ? 'relay-mutation-input' : 'input-object', 'config' => $inputConfiguration]; |
||
| 390 | } |
||
| 391 | |||
| 392 | /** |
||
| 393 | * Get a GraphQL scalar configuration from given scalar metadata. |
||
| 394 | */ |
||
| 395 | private static function scalarMetadataToGQLConfiguration(ReflectionClass $reflectionClass, Metadata\Scalar $scalarAnnotation): array |
||
| 396 | { |
||
| 397 | $scalarConfiguration = []; |
||
| 398 | |||
| 399 | if (isset($scalarAnnotation->scalarType)) { |
||
| 400 | $scalarConfiguration['scalarType'] = self::formatExpression($scalarAnnotation->scalarType); |
||
| 401 | } else { |
||
| 402 | $scalarConfiguration = [ |
||
| 403 | 'serialize' => [$reflectionClass->getName(), 'serialize'], |
||
| 404 | 'parseValue' => [$reflectionClass->getName(), 'parseValue'], |
||
| 405 | 'parseLiteral' => [$reflectionClass->getName(), 'parseLiteral'], |
||
| 406 | ]; |
||
| 407 | } |
||
| 408 | |||
| 409 | $scalarConfiguration = self::getDescriptionConfiguration(static::getMetadatas($reflectionClass)) + $scalarConfiguration; |
||
| 410 | |||
| 411 | return ['type' => 'custom-scalar', 'config' => $scalarConfiguration]; |
||
| 412 | } |
||
| 413 | |||
| 414 | /** |
||
| 415 | * Get a GraphQL Enum configuration from given enum metadata. |
||
| 416 | */ |
||
| 417 | private static function enumMetadataToGQLConfiguration(ReflectionClass $reflectionClass, Metadata\Enum $enumMetadata): array |
||
| 418 | { |
||
| 419 | $metadatas = static::getMetadatas($reflectionClass); |
||
| 420 | $enumValues = array_merge(self::getMetadataMatching($metadatas, Metadata\EnumValue::class), $enumMetadata->values); |
||
| 421 | |||
| 422 | $values = []; |
||
| 423 | |||
| 424 | foreach ($reflectionClass->getConstants() as $name => $value) { |
||
| 425 | $valueAnnotation = current(array_filter($enumValues, fn ($enumValueAnnotation) => $enumValueAnnotation->name === $name)); |
||
| 426 | $valueConfig = []; |
||
| 427 | $valueConfig['value'] = $value; |
||
| 428 | |||
| 429 | if ($valueAnnotation && isset($valueAnnotation->description)) { |
||
| 430 | $valueConfig['description'] = $valueAnnotation->description; |
||
| 431 | } |
||
| 432 | |||
| 433 | if ($valueAnnotation && isset($valueAnnotation->deprecationReason)) { |
||
| 434 | $valueConfig['deprecationReason'] = $valueAnnotation->deprecationReason; |
||
| 435 | } |
||
| 436 | |||
| 437 | $values[$name] = $valueConfig; |
||
| 438 | } |
||
| 439 | |||
| 440 | $enumConfiguration = ['values' => $values]; |
||
| 441 | $enumConfiguration = self::getDescriptionConfiguration(static::getMetadatas($reflectionClass)) + $enumConfiguration; |
||
| 442 | |||
| 443 | return ['type' => 'enum', 'config' => $enumConfiguration]; |
||
| 444 | } |
||
| 445 | |||
| 446 | /** |
||
| 447 | * Get a GraphQL Union configuration from given union metadata. |
||
| 448 | */ |
||
| 449 | private static function unionMetadataToGQLConfiguration(ReflectionClass $reflectionClass, Metadata\Union $unionMetadata): array |
||
| 487 | } |
||
| 488 | |||
| 489 | /** |
||
| 490 | * @phpstan-param ReflectionMethod|ReflectionProperty $reflector |
||
| 491 | * @phpstan-param class-string<Metadata\Field> $fieldMetadataName |
||
| 492 | * |
||
| 493 | * @throws AnnotationException |
||
| 494 | */ |
||
| 495 | private static function getTypeFieldConfigurationFromReflector(ReflectionClass $reflectionClass, Reflector $reflector, string $fieldMetadataName, string $currentValue = 'value'): array |
||
| 496 | { |
||
| 497 | /** @var ReflectionProperty|ReflectionMethod $reflector */ |
||
| 498 | $metadatas = static::getMetadatas($reflector); |
||
| 499 | |||
| 616 | } |
||
| 617 | |||
| 618 | /** |
||
| 619 | * Create GraphQL input fields configuration based on metadatas. |
||
| 620 | * |
||
| 621 | * @param ReflectionProperty[] $reflectors |
||
| 622 | * |
||
| 623 | * @throws AnnotationException |
||
| 624 | */ |
||
| 625 | private static function getGraphQLInputFieldsFromMetadatas(ReflectionClass $reflectionClass, array $reflectors): array |
||
| 626 | { |
||
| 627 | $fields = []; |
||
| 628 | |||
| 629 | foreach ($reflectors as $reflector) { |
||
| 630 | $metadatas = static::getMetadatas($reflector); |
||
| 631 | |||
| 632 | /** @var Metadata\Field|null $fieldMetadata */ |
||
| 633 | $fieldMetadata = self::getFirstMetadataMatching($metadatas, Metadata\Field::class); |
||
| 634 | |||
| 635 | // No field metadata found |
||
| 636 | if (null === $fieldMetadata) { |
||
| 637 | continue; |
||
| 638 | } |
||
| 639 | |||
| 640 | // Ignore field with resolver when the type is an Input |
||
| 641 | if (isset($fieldMetadata->resolve)) { |
||
| 642 | continue; |
||
| 643 | } |
||
| 644 | |||
| 645 | $fieldName = $reflector->getName(); |
||
| 646 | if (isset($fieldMetadata->type)) { |
||
| 647 | $fieldType = $fieldMetadata->type; |
||
| 648 | } else { |
||
| 649 | try { |
||
| 650 | $fieldType = self::guessType($reflectionClass, $reflector, self::VALID_INPUT_TYPES); |
||
| 651 | } catch (TypeGuessingException $e) { |
||
| 652 | throw new InvalidArgumentException(sprintf('The attribute "type" on %s is missing on property "%s" and cannot be auto-guessed from the following type guessers:'."\n%s\n", self::formatMetadata(Metadata\Field::class), $reflector->getName(), $e->getMessage())); |
||
| 653 | } |
||
| 654 | } |
||
| 655 | $fieldConfiguration = []; |
||
| 656 | if ($fieldType) { |
||
| 657 | // Resolve a PHP class from a GraphQL type |
||
| 658 | $resolvedType = self::$map->getType($fieldType); |
||
| 659 | // We found a type but it is not allowed |
||
| 660 | if (null !== $resolvedType && !in_array($resolvedType['type'], self::VALID_INPUT_TYPES)) { |
||
| 661 | throw new InvalidArgumentException(sprintf('The type "%s" on "%s" is a "%s" not valid on an Input %s. Only Input, Scalar and Enum are allowed.', $fieldType, $reflector->getName(), $resolvedType['type'], self::formatMetadata('Field'))); |
||
| 662 | } |
||
| 663 | |||
| 664 | $fieldConfiguration['type'] = $fieldType; |
||
| 665 | } |
||
| 666 | |||
| 667 | $fieldConfiguration = array_merge(self::getDescriptionConfiguration($metadatas, true), $fieldConfiguration); |
||
| 668 | $fields[$fieldName] = $fieldConfiguration; |
||
| 669 | } |
||
| 670 | |||
| 671 | return $fields; |
||
| 672 | } |
||
| 673 | |||
| 674 | /** |
||
| 675 | * Create GraphQL type fields configuration based on metadatas. |
||
| 676 | * |
||
| 677 | * @phpstan-param class-string<Metadata\Field> $fieldMetadataName |
||
| 678 | * |
||
| 679 | * @param ReflectionProperty[]|ReflectionMethod[] $reflectors |
||
| 680 | * |
||
| 681 | * @throws AnnotationException |
||
| 682 | */ |
||
| 683 | private static function getGraphQLTypeFieldsFromAnnotations(ReflectionClass $reflectionClass, array $reflectors, string $fieldMetadataName = Metadata\Field::class, string $currentValue = 'value'): array |
||
| 684 | { |
||
| 685 | $fields = []; |
||
| 686 | |||
| 687 | foreach ($reflectors as $reflector) { |
||
| 688 | $fields = array_merge($fields, self::getTypeFieldConfigurationFromReflector($reflectionClass, $reflector, $fieldMetadataName, $currentValue)); |
||
| 689 | } |
||
| 690 | |||
| 691 | return $fields; |
||
| 692 | } |
||
| 693 | |||
| 694 | /** |
||
| 695 | * @phpstan-param class-string<Metadata\Query|Metadata\Mutation> $expectedMetadata |
||
| 696 | * |
||
| 697 | * Return fields config from Provider methods. |
||
| 698 | * Loop through configured provider and extract fields targeting the targetType. |
||
| 699 | */ |
||
| 700 | private static function getGraphQLFieldsFromProviders(ReflectionClass $reflectionClass, string $expectedMetadata, string $targetType, bool $isDefaultTarget = false): array |
||
| 701 | { |
||
| 702 | $fields = []; |
||
| 703 | foreach (self::$providers as ['reflectionClass' => $providerReflection, 'metadata' => $providerMetadata]) { |
||
| 704 | $defaultAccessAnnotation = self::getFirstMetadataMatching(static::getMetadatas($providerReflection), Metadata\Access::class); |
||
| 705 | $defaultIsPublicAnnotation = self::getFirstMetadataMatching(static::getMetadatas($providerReflection), Metadata\IsPublic::class); |
||
| 706 | |||
| 707 | $defaultAccess = $defaultAccessAnnotation ? self::formatExpression($defaultAccessAnnotation->value) : false; |
||
| 708 | $defaultIsPublic = $defaultIsPublicAnnotation ? self::formatExpression($defaultIsPublicAnnotation->value) : false; |
||
| 709 | |||
| 710 | $methods = []; |
||
| 711 | // First found the methods matching the targeted type |
||
| 712 | foreach ($providerReflection->getMethods() as $method) { |
||
| 713 | $metadatas = static::getMetadatas($method); |
||
| 714 | |||
| 715 | $metadata = self::getFirstMetadataMatching($metadatas, [Metadata\Mutation::class, Metadata\Query::class]); |
||
| 716 | if (null === $metadata) { |
||
| 717 | continue; |
||
| 718 | } |
||
| 719 | |||
| 720 | // TODO: Remove old property check in 1.1 |
||
| 721 | $metadataTargets = $metadata->targetTypes ?? $metadata->targetType ?? null; |
||
| 722 | |||
| 723 | if (null === $metadataTargets) { |
||
| 724 | if ($metadata instanceof Metadata\Mutation && isset($providerMetadata->targetMutationTypes)) { |
||
| 725 | $metadataTargets = $providerMetadata->targetMutationTypes; |
||
| 726 | } elseif ($metadata instanceof Metadata\Query && isset($providerMetadata->targetQueryTypes)) { |
||
| 727 | $metadataTargets = $providerMetadata->targetQueryTypes; |
||
| 728 | } |
||
| 729 | } |
||
| 730 | |||
| 731 | if (null === $metadataTargets) { |
||
| 732 | if ($isDefaultTarget) { |
||
| 733 | $metadataTargets = [$targetType]; |
||
| 734 | if (!$metadata instanceof $expectedMetadata) { |
||
| 735 | continue; |
||
| 736 | } |
||
| 737 | } else { |
||
| 738 | continue; |
||
| 739 | } |
||
| 740 | } |
||
| 741 | |||
| 742 | if (!in_array($targetType, $metadataTargets)) { |
||
| 743 | continue; |
||
| 744 | } |
||
| 745 | |||
| 746 | if (!$metadata instanceof $expectedMetadata) { |
||
| 747 | if (Metadata\Mutation::class === $expectedMetadata) { |
||
| 748 | $message = sprintf('The provider "%s" try to add a query field on type "%s" (through %s on method "%s") but "%s" is a mutation.', $providerReflection->getName(), $targetType, self::formatMetadata('Query'), $method->getName(), $targetType); |
||
| 749 | } else { |
||
| 750 | $message = sprintf('The provider "%s" try to add a mutation on type "%s" (through %s on method "%s") but "%s" is not a mutation.', $providerReflection->getName(), $targetType, self::formatMetadata('Mutation'), $method->getName(), $targetType); |
||
| 751 | } |
||
| 752 | |||
| 753 | throw new InvalidArgumentException($message); |
||
| 754 | } |
||
| 755 | $methods[$method->getName()] = $method; |
||
| 756 | } |
||
| 757 | |||
| 758 | $currentValue = sprintf("service('%s')", self::formatNamespaceForExpression($providerReflection->getName())); |
||
| 759 | $providerFields = self::getGraphQLTypeFieldsFromAnnotations($reflectionClass, $methods, $expectedMetadata, $currentValue); |
||
| 760 | foreach ($providerFields as $fieldName => $fieldConfig) { |
||
| 761 | if (isset($providerMetadata->prefix)) { |
||
| 762 | $fieldName = sprintf('%s%s', $providerMetadata->prefix, $fieldName); |
||
| 763 | } |
||
| 764 | |||
| 765 | if ($defaultAccess && !isset($fieldConfig['access'])) { |
||
| 766 | $fieldConfig['access'] = $defaultAccess; |
||
| 767 | } |
||
| 768 | |||
| 769 | if ($defaultIsPublic && !isset($fieldConfig['public'])) { |
||
| 770 | $fieldConfig['public'] = $defaultIsPublic; |
||
| 771 | } |
||
| 772 | |||
| 773 | $fields[$fieldName] = $fieldConfig; |
||
| 774 | } |
||
| 775 | } |
||
| 776 | |||
| 777 | return $fields; |
||
| 778 | } |
||
| 779 | |||
| 780 | /** |
||
| 781 | * Get the config for description & deprecation reason. |
||
| 782 | */ |
||
| 783 | private static function getDescriptionConfiguration(array $metadatas, bool $withDeprecation = false): array |
||
| 784 | { |
||
| 785 | $config = []; |
||
| 786 | $descriptionAnnotation = self::getFirstMetadataMatching($metadatas, Metadata\Description::class); |
||
| 787 | if (null !== $descriptionAnnotation) { |
||
| 788 | $config['description'] = $descriptionAnnotation->value; |
||
| 789 | } |
||
| 790 | |||
| 791 | if ($withDeprecation) { |
||
| 792 | $deprecatedAnnotation = self::getFirstMetadataMatching($metadatas, Metadata\Deprecated::class); |
||
| 793 | if (null !== $deprecatedAnnotation) { |
||
| 794 | $config['deprecationReason'] = $deprecatedAnnotation->value; |
||
| 795 | } |
||
| 796 | } |
||
| 797 | |||
| 798 | return $config; |
||
| 799 | } |
||
| 800 | |||
| 801 | /** |
||
| 802 | * Format an array of args to a list of arguments in an expression. |
||
| 803 | */ |
||
| 804 | private static function formatArgsForExpression(array $args): string |
||
| 812 | } |
||
| 813 | |||
| 814 | /** |
||
| 815 | * Format a namespace to be used in an expression (double escape). |
||
| 816 | */ |
||
| 817 | private static function formatNamespaceForExpression(string $namespace): string |
||
| 818 | { |
||
| 819 | return str_replace('\\', '\\\\', $namespace); |
||
| 820 | } |
||
| 821 | |||
| 822 | /** |
||
| 823 | * Get the first metadata matching given class. |
||
| 824 | * |
||
| 825 | * @phpstan-template T of object |
||
| 826 | * @phpstan-param class-string<T>|class-string<T>[] $metadataClasses |
||
| 827 | * @phpstan-return T|null |
||
| 828 | * |
||
| 829 | * @return object|null |
||
| 830 | */ |
||
| 831 | private static function getFirstMetadataMatching(array $metadatas, $metadataClasses) |
||
| 832 | { |
||
| 833 | $metas = self::getMetadataMatching($metadatas, $metadataClasses); |
||
| 834 | |||
| 835 | return array_shift($metas); |
||
| 836 | } |
||
| 837 | |||
| 838 | /** |
||
| 839 | * Return the metadata matching given class |
||
| 840 | * |
||
| 841 | * @phpstan-template T of object |
||
| 842 | * @phpstan-param class-string<T>|class-string<T>[] $metadataClasses |
||
| 843 | * |
||
| 844 | * @return array |
||
| 845 | */ |
||
| 846 | private static function getMetadataMatching(array $metadatas, $metadataClasses) |
||
| 847 | { |
||
| 848 | if (is_string($metadataClasses)) { |
||
| 849 | $metadataClasses = [$metadataClasses]; |
||
| 850 | } |
||
| 851 | |||
| 852 | return array_filter($metadatas, function ($metadata) use ($metadataClasses) { |
||
| 853 | foreach ($metadataClasses as $metadataClass) { |
||
| 854 | if ($metadata instanceof $metadataClass) { |
||
| 855 | return true; |
||
| 856 | } |
||
| 857 | } |
||
| 858 | |||
| 859 | return false; |
||
| 860 | }); |
||
| 861 | } |
||
| 862 | |||
| 863 | /** |
||
| 864 | * Format an expression (ie. add "@=" if not set). |
||
| 865 | */ |
||
| 866 | private static function formatExpression(string $expression): string |
||
| 867 | { |
||
| 868 | return '@=' === substr($expression, 0, 2) ? $expression : sprintf('@=%s', $expression); |
||
| 869 | } |
||
| 870 | |||
| 871 | /** |
||
| 872 | * Suffix a name if it is not already. |
||
| 873 | */ |
||
| 874 | private static function suffixName(string $name, string $suffix): string |
||
| 875 | { |
||
| 876 | return substr($name, -strlen($suffix)) === $suffix ? $name : sprintf('%s%s', $name, $suffix); |
||
| 877 | } |
||
| 878 | |||
| 879 | /** |
||
| 880 | * Try to guess a GraphQL type using configured type guessers |
||
| 881 | * |
||
| 882 | * @throws RuntimeException |
||
| 883 | */ |
||
| 884 | private static function guessType(ReflectionClass $reflectionClass, Reflector $reflector, array $filterGraphQLTypes = []): string |
||
| 885 | { |
||
| 886 | $errors = []; |
||
| 887 | foreach (self::$typeGuessers as $typeGuesser) { |
||
| 888 | if (!$typeGuesser->supports($reflector)) { |
||
| 889 | continue; |
||
| 890 | } |
||
| 891 | try { |
||
| 892 | $type = $typeGuesser->guessType($reflectionClass, $reflector, $filterGraphQLTypes); |
||
| 893 | |||
| 894 | return $type; |
||
| 895 | } catch (TypeGuessingException $exception) { |
||
| 896 | $errors[] = sprintf('[%s] %s', $typeGuesser->getName(), $exception->getMessage()); |
||
| 897 | } |
||
| 898 | } |
||
| 899 | |||
| 900 | throw new TypeGuessingException(join("\n", $errors)); |
||
| 901 | } |
||
| 902 | |||
| 903 | /** |
||
| 904 | * Transform a method arguments from reflection to a list of GraphQL argument. |
||
| 905 | */ |
||
| 906 | private static function guessArgs(ReflectionClass $reflectionClass, ReflectionMethod $method): array |
||
| 907 | { |
||
| 908 | $arguments = []; |
||
| 909 | foreach ($method->getParameters() as $index => $parameter) { |
||
| 910 | try { |
||
| 911 | $gqlType = self::guessType($reflectionClass, $parameter, self::VALID_INPUT_TYPES); |
||
| 912 | } catch (TypeGuessingException $exception) { |
||
| 913 | throw new InvalidArgumentException(sprintf('Argument n°%s "$%s" on method "%s" cannot be auto-guessed from the following type guessers:'."\n%s\n", $index + 1, $parameter->getName(), $method->getName(), $exception->getMessage())); |
||
| 914 | } |
||
| 915 | |||
| 916 | $argumentConfig = []; |
||
| 917 | if ($parameter->isDefaultValueAvailable()) { |
||
| 918 | $argumentConfig['defaultValue'] = $parameter->getDefaultValue(); |
||
| 919 | } |
||
| 920 | |||
| 921 | $argumentConfig['type'] = $gqlType; |
||
| 922 | |||
| 923 | $arguments[$parameter->getName()] = $argumentConfig; |
||
| 924 | } |
||
| 925 | |||
| 926 | return $arguments; |
||
| 927 | } |
||
| 928 | |||
| 929 | private static function getClassProperties(ReflectionClass $reflectionClass) |
||
| 930 | { |
||
| 931 | $properties = []; |
||
| 932 | do { |
||
| 933 | foreach ($reflectionClass->getProperties() as $property) { |
||
| 934 | if (isset($properties[$property->getName()])) { |
||
| 935 | continue; |
||
| 936 | } |
||
| 937 | $properties[$property->getName()] = $property; |
||
| 938 | } |
||
| 939 | } while ($reflectionClass = $reflectionClass->getParentClass()); |
||
| 940 | |||
| 941 | return $properties; |
||
| 942 | } |
||
| 943 | |||
| 944 | protected static function formatMetadata(string $className): string |
||
| 947 | } |
||
| 948 | |||
| 949 | abstract protected static function getMetadatas(Reflector $reflector): array; |
||
| 950 | } |
||
| 951 |