|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace GraphQL\Validator\Rules; |
| 6 | + |
| 7 | +use GraphQL\Error\Error; |
| 8 | +use GraphQL\Language\AST\EnumTypeDefinitionNode; |
| 9 | +use GraphQL\Language\AST\EnumTypeExtensionNode; |
| 10 | +use GraphQL\Language\AST\EnumValueNode; |
| 11 | +use GraphQL\Language\AST\NodeKind; |
| 12 | +use GraphQL\Language\Visitor; |
| 13 | +use GraphQL\Language\VisitorOperation; |
| 14 | +use GraphQL\Type\Definition\EnumType; |
| 15 | +use GraphQL\Validator\SDLValidationContext; |
| 16 | + |
| 17 | +class UniqueEnumValueNames extends ValidationRule |
| 18 | +{ |
| 19 | + public function getSDLVisitor(SDLValidationContext $context): array |
| 20 | + { |
| 21 | + /** @var array<string, array<string, EnumValueNode>> $knownValueNames */ |
| 22 | + $knownValueNames = []; |
| 23 | + |
| 24 | + /** |
| 25 | + * @param EnumTypeDefinitionNode|EnumTypeExtensionNode $enum |
| 26 | + */ |
| 27 | + $checkValueUniqueness = static function ($enum) use ($context, &$knownValueNames): VisitorOperation { |
| 28 | + $typeName = $enum->name->value; |
| 29 | + |
| 30 | + $schema = $context->getSchema(); |
| 31 | + $existingType = $schema !== null |
| 32 | + ? $schema->getType($typeName) |
| 33 | + : null; |
| 34 | + |
| 35 | + $valueNodes = $enum->values; |
| 36 | + |
| 37 | + if (! isset($knownValueNames[$typeName])) { |
| 38 | + $knownValueNames[$typeName] = []; |
| 39 | + } |
| 40 | + |
| 41 | + $valueNames = &$knownValueNames[$typeName]; |
| 42 | + |
| 43 | + foreach ($valueNodes as $valueDef) { |
| 44 | + $valueNameNode = $valueDef->name; |
| 45 | + $valueName = $valueNameNode->value; |
| 46 | + |
| 47 | + if ($existingType instanceof EnumType && $existingType->getValue($valueName) !== null) { |
| 48 | + $context->reportError(new Error( |
| 49 | + "Enum value \"${typeName}.${valueName}\" already exists in the schema. It cannot also be defined in this type extension.", |
| 50 | + $valueNameNode |
| 51 | + )); |
| 52 | + } elseif (isset($valueNames[$valueName])) { |
| 53 | + $context->reportError(new Error( |
| 54 | + "Enum value \"${typeName}.${valueName}\" can only be defined once.", |
| 55 | + [$valueNames[$valueName], $valueNameNode] |
| 56 | + )); |
| 57 | + } else { |
| 58 | + $valueNames[$valueName] = $valueNameNode; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return Visitor::skipNode(); |
| 63 | + }; |
| 64 | + |
| 65 | + return [ |
| 66 | + NodeKind::ENUM_TYPE_DEFINITION => $checkValueUniqueness, |
| 67 | + NodeKind::ENUM_TYPE_EXTENSION => $checkValueUniqueness, |
| 68 | + ]; |
| 69 | + } |
| 70 | +} |
0 commit comments