diff --git a/README.md b/README.md index 9163473..2773846 100644 --- a/README.md +++ b/README.md @@ -822,7 +822,7 @@ Each error goes to stderr as `file:line message`, with the file relative to the | Attribute | Goes on | Arguments | | ---------------------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | -| `#[BidirektSchema]` | a class, an enum with string values, or a handler ([without a class](#schemas-without-a-class)) | `name`, `fields` | +| `#[BidirektSchema]` | a class, an enum with string values, or a handler ([without a class](#schemas-without-a-class)) | `name`, `fields`, `graphqlType` | | `#[BidirektField]` | a property or a promoted constructor parameter, or `new BidirektField(...)` in `fields:` | `name`, `type`, `items`, `values`, `optional`, `nullable`, `description`, `union` | | `#[BidirektRestProvider]` | a method, a function, a closure or an arrow function | `method`, `path`, `responses`, `request` | | `#[BidirektRestConsumer]` | a method, a function, a closure or an arrow function | `provider`, `method`, `path`, `responses`, `request` | @@ -849,7 +849,7 @@ An argument is read from the code, never run: a literal, an array, `X::class`, a A promoted constructor parameter is a field like a property. An annotation on a parameter that is not promoted, or on a `static` property, is not read, and `generate` warns. -In a GraphQL contract, `#[BidirektGraphqlField]` takes the place of `#[BidirektField]` on a field that needs GraphQL's own options, and `@bidirekt graphql field` that of `@bidirekt field`. They take the options above, plus `scalar: 'DateTime'`, a custom scalar that replaces the field's type at the bottom of its lists and is written as `type: scalar, name: DateTime`, and `arguments: ReviewsArgs::class`, the schema of the arguments the call passes to the field, as `first` in `reviews(first: 10)`. In a tag, `scalar=DateTime` and `arguments=ReviewsArgs`. A field takes one of the two attributes, never both. +In a GraphQL contract, `#[BidirektGraphqlField]` takes the place of `#[BidirektField]` on a field that needs GraphQL's own options, and `@bidirekt graphql field` that of `@bidirekt field`. They take the options above, plus `scalar: 'DateTime'`, a custom scalar or a built-in one (`ID`, `String`, `Int`, `Float`, `Boolean`) that replaces the field's type at the bottom of its lists and is written as `type: scalar, name: DateTime`, and `arguments: ReviewsArgs::class`, the schema of the arguments the call passes to the field, as `first` in `reviews(first: 10)`. In a tag, `scalar=DateTime` and `arguments=ReviewsArgs`. A field takes one of the two attributes, never both. ### Handlers @@ -882,7 +882,17 @@ Without a request (no `request` argument, no `@bidirekt request`), the resource | an enum | `['enum' => ['AVAILABLE', 'SOLD'], 'name' => 'Status']` | `enum:AVAILABLE\|SOLD as Status` | `Status` | | a union | `['union' => ['Pet' => Pet::class, 'Owner' => Owner::class], 'name' => 'SearchResult']` | `union={Pet: Pet, Owner: Owner} as SearchResult` | `SearchResult` | -A primitive, a scalar, an enum or a union also takes the place of the schema in a nullable or a list (`['nullable' => 'integer']`, `'string[]'`, `scalar:DateTime?[]`). Each key of a union is the name of one of its types in the provider's GraphQL schema, and its value the schema the call reads from that type. Each form but a schema returned as it is becomes a schema of the contract, with the name above, and `name` in the attribute or `as ` in the tag gives it another one. They name only a schema `generate` creates: `@bidirekt returns Pet as MyPet` stops `generate`; to call it `MyPet`, name the schema itself. An enum or a union in a nullable or a list is a schema of its own, under the name it declares, and the nullable or the list references it under the name above: `['nullable' => ['enum' => ['AVAILABLE', 'SOLD'], 'name' => 'Status']]` and `enum:AVAILABLE|SOLD? as Status` both write `Status` and `StatusOrNull`. A scalar in a nullable or a list takes no name of its own: the name goes on the nullable or the list. GraphQL's own names of the built-in scalars, as `Int` or `Boolean`, are not schemas: write `integer` or `boolean`. +A primitive, a scalar, an enum or a union also takes the place of the schema in a nullable or a list (`['nullable' => 'integer']`, `'string[]'`, `scalar:DateTime?[]`). Each key of a union is the name of one of its types in the provider's GraphQL schema, and its value the schema the call reads from that type. Each form but a schema returned as it is becomes a schema of the contract, with the name above, and `name` in the attribute or `as ` in the tag gives it another one. They name only a schema `generate` creates: `@bidirekt returns Pet as MyPet` stops `generate`; to call it `MyPet`, name the schema itself. An enum or a union in a nullable or a list is a schema of its own, under the name it declares, and the nullable or the list references it under the name above: `['nullable' => ['enum' => ['AVAILABLE', 'SOLD'], 'name' => 'Status']]` and `enum:AVAILABLE|SOLD? as Status` both write `Status` and `StatusOrNull`. A scalar in a nullable or a list takes no name of its own: the name goes on the nullable or the list. GraphQL's own names of the built-in scalars, as `Int` or `Boolean`, are not schemas: write `integer` or `boolean`, which accept any GraphQL type of that shape, or `['scalar' => 'ID']` and `scalar:ID` to send that exact GraphQL type, written as `type: scalar, name: ID`. + +`graphqlType` on `#[BidirektSchema]`, or `graphqlType=PetInput` on `@bidirekt schema`, declares the GraphQL type a class or an enum is sent or read as, written as `name: PetInput` on its schema: the check then breaks when the provider's type has another name. Without it, a type the provider renames with the same shape doesn't break. The broker takes it on an object or an enum that only GraphQL reaches, and never on the schema of `arguments` itself, which is no GraphQL type: put it on the input objects inside. + +The same field called by several handlers is written once. A handler that declares other `arguments` or `returns` adds them: one schema is written as its name, several as a list in alphabetical order, with `~` first for a handler that sends no arguments, and the broker checks each one as if each handler were alone: + +```yaml +pet: + arguments: [~, PetArgs] + returns: [PetWithName, PetWithStatus] +``` ### Tags @@ -890,7 +900,7 @@ A tag is `@bidirekt ` at the start of a line of a `/** */` docblock, wi | Tag | Goes | | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `@bidirekt schema` or `@bidirekt schema name=PetResponse` | above a class or an enum with string values | +| `@bidirekt schema [name=PetResponse] [graphqlType=Pet]` | above a class or an enum with string values | | `@bidirekt field [key=value ...]` | above a property, or a promoted constructor parameter | | `@bidirekt schema ` and `@bidirekt field type=...` | in a handler's docblock ([without a class](#schemas-without-a-class)) | | `@bidirekt rest provides ` | above a method, a function, a closure, or a route call like `$app->get(...)` or `Route::get(...)` | diff --git a/src/BidirektSchema.php b/src/BidirektSchema.php index 727d06a..3d1003d 100644 --- a/src/BidirektSchema.php +++ b/src/BidirektSchema.php @@ -15,5 +15,6 @@ final class BidirektSchema public function __construct( public ?string $name = null, public array $fields = [], + public ?string $graphqlType = null, ) {} } diff --git a/src/Model/Protocols/Graphql/BlocksToMerged.php b/src/Model/Protocols/Graphql/BlocksToMerged.php index acdb21b..69d9838 100644 --- a/src/Model/Protocols/Graphql/BlocksToMerged.php +++ b/src/Model/Protocols/Graphql/BlocksToMerged.php @@ -45,7 +45,7 @@ public static function sideBlocksToMerged(array $sideBlocks): MergedBlock foreach ($blocks as $own) { array_push($operations, ...$own->operations); } - $block->operations = $merger->operationsToMerged($operations, $provider); + $block->operations = self::operationsToMerged($operations); } return new MergedBlock($block, array_values($merger->errors)); @@ -75,10 +75,13 @@ private function graphsToMerged(array $graphs): ?Graph } /** + * Joins the operations of every handler that calls the same field: each distinct schema of its `arguments` and + * its `returns` once, in byte order, with a handler that sends no arguments first. + * * @param list $operations * @return list */ - private function operationsToMerged(array $operations, string $provider): array + private static function operationsToMerged(array $operations): array { $groups = []; foreach ($operations as $operation) { @@ -86,37 +89,39 @@ private function operationsToMerged(array $operations, string $provider): array } $merged = []; foreach ($groups as $group) { - $first = array_shift($group); - $described = sprintf('%s %s consumed from "%s"', $first->kind, $first->name, $provider); - foreach ($group as $other) { - $this->usesToConflict('arguments', $first->arguments, $other->arguments, $first, $other, $described); - $this->usesToConflict('returns', $first->returns, $other->returns, $first, $other, $described); + $arguments = []; + $returns = []; + foreach ($group as $operation) { + array_push($arguments, ...$operation->arguments); + array_push($returns, ...$operation->returns); } - $merged[] = $first; + $withoutArguments = in_array(null, $arguments, true) ? [null] : []; + $first = $group[0]; + $merged[] = new Operation( + $first->kind, + $first->name, + [...$withoutArguments, ...self::usesToDistinct(array_filter($arguments))], + self::usesToDistinct($returns), + $first->location, + ); } return $merged; } - private function usesToConflict(string $use, ?SchemaUse $firstUse, ?SchemaUse $otherUse, Operation $first, Operation $other, string $described): void + /** + * @param array $uses + * @return list + */ + private static function usesToDistinct(array $uses): array { - if ($firstUse?->schema === $otherUse?->schema) { - return; + $bySchema = []; + foreach ($uses as $use) { + $bySchema[$use->schema] ??= $use; } - if ($firstUse === null || $otherUse === null) { - $this->addConflict( - sprintf('%s of %s is declared in one handler and not in another: declare the same %s in every handler', $use, $described, $use), - $firstUse->location ?? $first->location, - $otherUse->location ?? $other->location, - ); + ksort($bySchema, SORT_STRING); - return; - } - $this->addConflict( - sprintf('%s of %s is declared as %s and %s: declare the same %s in every handler', $use, $described, $firstUse->schema, $otherUse->schema, $use), - $firstUse->location, - $otherUse->location, - ); + return array_values($bySchema); } private function addConflict(string $message, SourceLocation $first, SourceLocation $other): void diff --git a/src/Model/Protocols/Graphql/GraphqlExtra.php b/src/Model/Protocols/Graphql/GraphqlExtra.php index 980cd01..f0ebbf0 100644 --- a/src/Model/Protocols/Graphql/GraphqlExtra.php +++ b/src/Model/Protocols/Graphql/GraphqlExtra.php @@ -9,7 +9,8 @@ use Bidirekt\PhpSdk\Model\SchemaNode; /** - * GraphQL's own options of a field: a custom scalar in place of its type, and the arguments the call passes to it. + * GraphQL's own options of a field: a custom scalar in place of its type, and the arguments the call passes to it; + * and of a schema, the GraphQL type it is sent as. */ final class GraphqlExtra implements NodeExtra { @@ -21,8 +22,18 @@ final class GraphqlExtra implements NodeExtra public function __construct( public ?string $scalar = null, public ?string $arguments = null, + public ?string $graphqlType = null, ) {} + public static function nodeToTyped(SchemaNode $node, ?string $graphqlType): SchemaNode + { + if ($graphqlType !== null) { + $node->extra = new self(graphqlType: $graphqlType); + } + + return $node; + } + public static function scalarToNode(string $scalar): SchemaNode { $node = new PrimitiveNode('string'); diff --git a/src/Model/Protocols/Graphql/Operation.php b/src/Model/Protocols/Graphql/Operation.php index db7fcca..450c703 100644 --- a/src/Model/Protocols/Graphql/Operation.php +++ b/src/Model/Protocols/Graphql/Operation.php @@ -7,18 +7,21 @@ use Bidirekt\PhpSdk\Model\SourceLocation; /** - * A field of the query or the mutation root that the service calls. + * A field of the query or the mutation root that the service calls, from one handler or joined from every handler + * that calls it. */ final class Operation { /** * @param 'query'|'mutation' $kind + * @param list $arguments null for a handler that sends no arguments + * @param list $returns */ public function __construct( public string $kind, public string $name, - public ?SchemaUse $arguments, - public SchemaUse $returns, + public array $arguments, + public array $returns, public SourceLocation $location, ) {} } diff --git a/src/Protocols/GraphqlProtocol.php b/src/Protocols/GraphqlProtocol.php index cd0a48e..576f4ea 100644 --- a/src/Protocols/GraphqlProtocol.php +++ b/src/Protocols/GraphqlProtocol.php @@ -36,7 +36,7 @@ public function references(ProtocolBlock $block): array } $references = []; foreach ($block->operations as $operation) { - foreach ([$operation->arguments, $operation->returns] as $use) { + foreach ([...$operation->arguments, ...$operation->returns] as $use) { if ($use !== null) { $references[] = new Reference($use->schema, $use->location, self::NAME); } @@ -69,6 +69,6 @@ public function missingSchemaToMessage(string $schema): ?string return null; } - return sprintf('%s is GraphQL\'s name: write %s', $schema, $primitive); + return sprintf('%s is GraphQL\'s name: write %s, or [\'scalar\' => \'%s\'] (scalar:%s in a tag) to declare that GraphQL type', $schema, $primitive, $schema, $schema); } } diff --git a/src/Reader/ClassesToSchemas.php b/src/Reader/ClassesToSchemas.php index c37a4c7..d5845cc 100644 --- a/src/Reader/ClassesToSchemas.php +++ b/src/Reader/ClassesToSchemas.php @@ -10,6 +10,7 @@ use Bidirekt\PhpSdk\Model\NamedSchema; use Bidirekt\PhpSdk\Model\ObjectNode; use Bidirekt\PhpSdk\Model\Property; +use Bidirekt\PhpSdk\Model\Protocols\Graphql\GraphqlExtra; use Bidirekt\PhpSdk\Protocols\GraphqlProtocol; use Bidirekt\PhpSdk\Reader\Protocols\Graphql\FieldArgumentsToExtra; @@ -63,8 +64,8 @@ public static function filesToSchemas( array_push($schemaClasses, ...$reader->fileToSchemaClasses($file)); } $schemas = $reader->unreadSchemas; - foreach ($schemaClasses as [$declaration, $name, $fields, $form]) { - $schemas[] = $reader->classToSchema($declaration, $name, $fields, $form); + foreach ($schemaClasses as [$declaration, $name, $annotation]) { + $schemas[] = $reader->classToSchema($declaration, $name, $annotation); } foreach ($files as $file) { $reader->fileToFieldWarnings($file); @@ -80,10 +81,9 @@ public static function filesToSchemas( /** * Registers the schema names of the file's class-likes, so every reference resolves before a field is read. * - * @return list the class, its schema - * name, its `fields:` and its - * annotation, for each class - * whose fields are to be read + * @return list the class, its schema name and its + * annotation, for each class whose fields + * are to be read */ private function fileToSchemaClasses(FileSummary $file): array { @@ -101,9 +101,8 @@ private function fileToSchemaClasses(FileSummary $file): array /** * Registers the schema name of a class-like with `#[BidirektSchema]` or `@bidirekt schema`. * - * @return array{ClassDeclaration, string, ConstantValue|null, AnnotationForm}|null the class, its schema name, - * its `fields:` and its annotation, - * when its fields are to be read + * @return array{ClassDeclaration, string, SchemaAnnotation}|null the class, its schema name and its + * annotation, when its fields are to be read */ private function classToSchemaClass(ClassSummary $class, FileSummary $file): ?array { @@ -128,23 +127,24 @@ private function classToSchemaClass(ClassSummary $class, FileSummary $file): ?ar return null; } - return $this->namedToSchemaClass($class, $file, $annotation->declaredName, $annotation->form, $annotation->fields); + return $this->namedToSchemaClass($class, $file, $annotation); } /** * Registers the schema name of an annotated class-like: an enum's schema is read at once. * - * @return array{ClassDeclaration, string, ConstantValue|null, AnnotationForm}|null + * @return array{ClassDeclaration, string, SchemaAnnotation}|null */ - private function namedToSchemaClass(ClassSummary $class, FileSummary $file, ?string $declared, AnnotationForm $form, ?ConstantValue $fields): ?array + private function namedToSchemaClass(ClassSummary $class, FileSummary $file, SchemaAnnotation $annotation): ?array { - $declaration = $this->classToDeclaration($class, $file, $declared, $form); + $declared = $annotation->declaredName; + $declaration = $this->classToDeclaration($class, $file, $declared, $annotation->form); if ($declaration === null) { return null; } $name = SchemaNaming::schemaToName($declared, $declaration->name); if ($class->kind === 'enum') { - $this->schemas->addEnum($class, $name); + $this->schemas->addEnum($class, $name, $annotation->graphqlType); $schema = $this->schemas->enumToSchema($declaration); if (is_array($schema)) { $this->addErrors($schema); @@ -155,7 +155,7 @@ private function namedToSchemaClass(ClassSummary $class, FileSummary $file, ?str } $this->schemas->addClass($class, $name); - return [$declaration, $name, $fields, $form]; + return [$declaration, $name, $annotation]; } /** @@ -215,12 +215,12 @@ private function classToDeclaration(ClassSummary $class, FileSummary $file, ?str } /** - * A schema with no field is still declared, so the references to it add no error of their own. - * - * @param ConstantValue|null $declaredFields the `fields:` of its #[BidirektSchema], which come after the annotated ones + * A schema with no field is still declared, so the references to it add no error of their own. The `fields:` + * of its #[BidirektSchema] come after the annotated ones. */ - private function classToSchema(ClassDeclaration $declaration, string $name, ?ConstantValue $declaredFields, AnnotationForm $form): NamedSchema + private function classToSchema(ClassDeclaration $declaration, string $name, SchemaAnnotation $annotation): NamedSchema { + $declaredFields = $annotation->fields; [$members, $complete] = $this->classToMembers($declaration, new ClassScope($declaration, $declaration), []); $properties = []; foreach ($members as $member) { @@ -232,7 +232,7 @@ private function classToSchema(ClassDeclaration $declaration, string $name, ?Con } $properties[] = $property; } - $fix = sprintf('annotate at least one field with %s', $form->fieldAnnotation); + $fix = sprintf('annotate at least one field with %s', $annotation->form->fieldAnnotation); if ($declaredFields !== null) { [$declared, $errors] = $this->declaredFields->fieldsToProperties($declaredFields); $this->addErrors($errors); @@ -245,7 +245,7 @@ private function classToSchema(ClassDeclaration $declaration, string $name, ?Con $this->addErrors([new Diagnostic(sprintf('schema "%s" has no field: %s', $name, $fix), $location)]); } - return new NamedSchema($name, new ObjectNode($properties), $location); + return new NamedSchema($name, GraphqlExtra::nodeToTyped(new ObjectNode($properties), $annotation->graphqlType), $location); } /** diff --git a/src/Reader/FieldOptions.php b/src/Reader/FieldOptions.php index 580c3df..6381df6 100644 --- a/src/Reader/FieldOptions.php +++ b/src/Reader/FieldOptions.php @@ -18,6 +18,7 @@ final class FieldOptions * @param SchemaNode|null $declared the type a tag's `type=`, `items=`, `values=` or `union=` declare, null when none does * @param string|null $protocol the protocol whose field annotation declares the field, null for the core's * @param NodeExtra|null $extra the options of that protocol + * @param string|null $graphqlType the GraphQL type a schema tag declares */ public function __construct( public ?string $name = null, @@ -27,6 +28,7 @@ public function __construct( public ?SchemaNode $declared = null, public ?string $protocol = null, public ?NodeExtra $extra = null, + public ?string $graphqlType = null, ) {} /** diff --git a/src/Reader/FunctionsToSchemas.php b/src/Reader/FunctionsToSchemas.php index 112cf9c..069f9dd 100644 --- a/src/Reader/FunctionsToSchemas.php +++ b/src/Reader/FunctionsToSchemas.php @@ -8,6 +8,7 @@ use Bidirekt\PhpSdk\Model\Diagnostic; use Bidirekt\PhpSdk\Model\NamedSchema; use Bidirekt\PhpSdk\Model\ObjectNode; +use Bidirekt\PhpSdk\Model\Protocols\Graphql\GraphqlExtra; use PhpParser\Node\FunctionLike; /** @@ -77,6 +78,11 @@ private function attributeToSchema(SdkAttribute $attribute): array if ($name instanceof Diagnostic) { return [null, [...$errors, $name]]; } + $graphqlType = $arguments->nameArgument('graphqlType'); + if ($graphqlType instanceof Diagnostic) { + $errors[] = $graphqlType; + $graphqlType = null; + } $properties = []; if (isset($arguments->values['fields'])) { [$properties, $fieldErrors] = $this->declaredFields->fieldsToProperties($arguments->values['fields']); @@ -86,6 +92,6 @@ private function attributeToSchema(SdkAttribute $attribute): array $errors[] = new Diagnostic(sprintf('schema "%s" has no field: declare at least one field in "fields"', $name), $attribute->location); } - return [new NamedSchema($name, new ObjectNode($properties), $attribute->location), $errors]; + return [new NamedSchema($name, GraphqlExtra::nodeToTyped(new ObjectNode($properties), $graphqlType), $attribute->location), $errors]; } } diff --git a/src/Reader/Protocols/Graphql/ConsumedOperation.php b/src/Reader/Protocols/Graphql/ConsumedOperation.php index 506dd68..bc430ad 100644 --- a/src/Reader/Protocols/Graphql/ConsumedOperation.php +++ b/src/Reader/Protocols/Graphql/ConsumedOperation.php @@ -35,7 +35,7 @@ public function addToRead(ProtocolRead $read): void { [$schema, $derived] = ReturnsToSchema::returnsToSchema($this->returns, $this->returnsLocation); array_push($read->derived, ...$derived); - $operation = new Operation($this->kind, $this->name, $this->arguments, new SchemaUse($schema, $this->returnsLocation), $this->location); + $operation = new Operation($this->kind, $this->name, [$this->arguments], [new SchemaUse($schema, $this->returnsLocation)], $this->location); $read->blocks[] = new SideBlock($this->provider, new GraphqlBlock([$operation])); } } diff --git a/src/Reader/SchemaAnnotation.php b/src/Reader/SchemaAnnotation.php index d68fee6..fc18ed7 100644 --- a/src/Reader/SchemaAnnotation.php +++ b/src/Reader/SchemaAnnotation.php @@ -12,11 +12,13 @@ final class SchemaAnnotation /** * @param ConstantValue|null $fields the `fields:` of its #[BidirektSchema] * @param bool $readable false when one of its arguments cannot be read, so it declares its name alone + * @param string|null $graphqlType the GraphQL type its schema is sent as */ public function __construct( public ?string $declaredName, public AnnotationForm $form, public ?ConstantValue $fields, public bool $readable = true, + public ?string $graphqlType = null, ) {} } diff --git a/src/Reader/SchemaClasses.php b/src/Reader/SchemaClasses.php index 3064caa..38afcd6 100644 --- a/src/Reader/SchemaClasses.php +++ b/src/Reader/SchemaClasses.php @@ -8,6 +8,7 @@ use Bidirekt\PhpSdk\Model\Diagnostic; use Bidirekt\PhpSdk\Model\EnumNode; use Bidirekt\PhpSdk\Model\NamedSchema; +use Bidirekt\PhpSdk\Model\Protocols\Graphql\GraphqlExtra; use Bidirekt\PhpSdk\Model\SourceLocation; use PhpParser\Node\Stmt\ClassLike; use PhpParser\Node\Stmt\Enum_; @@ -23,7 +24,7 @@ final class SchemaClasses /** @var array class summary id => schema name */ private array $classNames = []; - /** @var array enum summary id => name declared by its #[BidirektSchema] */ + /** @var array enum summary id => schema name and GraphQL type its annotation declares */ private array $enumNames = []; /** @var array|null> enum summary id => schema, why it cannot be one, or null for an enum without string values */ @@ -44,9 +45,9 @@ public function classToName(ClassDeclaration $class): ?string return $this->classNames[spl_object_id($class->summary)] ?? null; } - public function addEnum(ClassSummary $enum, string $name): void + public function addEnum(ClassSummary $enum, string $name, ?string $graphqlType): void { - $this->enumNames[spl_object_id($enum)] = $name; + $this->enumNames[spl_object_id($enum)] = [$name, $graphqlType]; } public static function isStringEnum(ClassSummary $class): bool @@ -90,7 +91,7 @@ public function enumToSchema(ClassDeclaration $enum): NamedSchema|array|null { $id = spl_object_id($enum->summary); if (!array_key_exists($id, $this->enumSchemas)) { - $this->enumSchemas[$id] = $this->enumToReadSchema($enum, $this->enumNames[$id] ?? null); + $this->enumSchemas[$id] = $this->enumToReadSchema($enum, ...$this->enumNames[$id] ?? [null, null]); } return $this->enumSchemas[$id]; @@ -101,7 +102,7 @@ public function enumToSchema(ClassDeclaration $enum): NamedSchema|array|null * like one in vendor/, whose annotation is read here * @return NamedSchema|list|null */ - private function enumToReadSchema(ClassDeclaration $enum, ?string $name): NamedSchema|array|null + private function enumToReadSchema(ClassDeclaration $enum, ?string $name, ?string $graphqlType): NamedSchema|array|null { if ($name === null) { $read = $this->classToAnnotation($enum->summary, $enum->file); @@ -111,13 +112,14 @@ private function enumToReadSchema(ClassDeclaration $enum, ?string $name): NamedS return $errors; } $name = $annotation?->declaredName; + $graphqlType = $annotation?->graphqlType; } } if (!self::isStringEnum($enum->summary)) { return null; } - return $this->enumToNewSchema($enum, $name ?? SchemaNaming::classToShortName($enum->name)); + return $this->enumToNewSchema($enum, $name ?? SchemaNaming::classToShortName($enum->name), $graphqlType); } /** @@ -178,8 +180,12 @@ public function classToAnnotation(ClassSummary $class, FileSummary $file): ?arra if ($declared instanceof Diagnostic) { return [null, [...$errors, $declared]]; } + $graphqlType = $arguments->nameArgument('graphqlType'); + if ($graphqlType instanceof Diagnostic) { + return [null, [...$errors, $graphqlType]]; + } - return [new SchemaAnnotation($declared, AnnotationForm::attribute(), $arguments->values['fields'] ?? null, $errors === []), $errors]; + return [new SchemaAnnotation($declared, AnnotationForm::attribute(), $arguments->values['fields'] ?? null, $errors === [], $graphqlType), $errors]; } /** @@ -193,7 +199,7 @@ private function tagToAnnotation(ClassSummary $class, CommentTag $tag): array $tag->location, )]]; } - $options = TagArgumentsToOptions::argumentsToOptions($tag, $tag->arguments, ['name']); + $options = TagArgumentsToOptions::argumentsToOptions($tag, $tag->arguments, ['name', 'graphqlType']); if ($options instanceof Diagnostic) { return [null, [$options]]; } @@ -204,7 +210,7 @@ private function tagToAnnotation(ClassSummary $class, CommentTag $tag): array } } - return [new SchemaAnnotation($options->name, AnnotationForm::tag(), null), []]; + return [new SchemaAnnotation($options->name, AnnotationForm::tag(), null, graphqlType: $options->graphqlType), []]; } /** @@ -245,7 +251,7 @@ public function enumSchemas(): array /** * @return NamedSchema|list */ - private function enumToNewSchema(ClassDeclaration $enum, string $name): NamedSchema|array + private function enumToNewSchema(ClassDeclaration $enum, string $name, ?string $graphqlType): NamedSchema|array { if ($enum->summary->cases === []) { return [new Diagnostic(sprintf('%s has no cases: add a case with a string value', $enum->summary->description), $enum->summary->location)]; @@ -278,6 +284,6 @@ private function enumToNewSchema(ClassDeclaration $enum, string $name): NamedSch return $errors; } - return new NamedSchema($name, new EnumNode($members), $enum->summary->location); + return new NamedSchema($name, GraphqlExtra::nodeToTyped(new EnumNode($members), $graphqlType), $enum->summary->location); } } diff --git a/src/Reader/TagArgumentsToOptions.php b/src/Reader/TagArgumentsToOptions.php index 74fea1b..1077674 100644 --- a/src/Reader/TagArgumentsToOptions.php +++ b/src/Reader/TagArgumentsToOptions.php @@ -34,6 +34,7 @@ final class TagArgumentsToOptions 'union' => '"union={: , ...}"', 'scalar' => '"scalar="', 'arguments' => '"arguments="', + 'graphqlType' => '"graphqlType="', ]; public const SCHEMA_NAME_PATTERN = '/^[^\s<>[\],:={}]+$/'; @@ -86,6 +87,7 @@ public static function argumentsToOptions(CommentTag $tag, array $arguments, arr } $options->name = $values['name'] ?? null; $options->description = $values['description'] ?? null; + $options->graphqlType = $values['graphqlType'] ?? null; if (isset($values['optional'])) { $options->optional = $values['optional'] === 'true'; } @@ -121,7 +123,7 @@ private static function optionToError(string $key, string $value, string $argume return self::unreadable($argument, $tag, $usage); } - if (($key === 'scalar' || $key === 'arguments') && preg_match(self::SCHEMA_NAME_PATTERN, $value) !== 1) { + if (in_array($key, ['scalar', 'arguments', 'graphqlType'], true) && preg_match(self::SCHEMA_NAME_PATTERN, $value) !== 1) { return self::unreadable($argument, $tag, $usage); } if ($key === 'union' && self::valueToUnion($value) === null) { diff --git a/src/Writer/ContractToYaml.php b/src/Writer/ContractToYaml.php index 3d09215..4d7dfef 100644 --- a/src/Writer/ContractToYaml.php +++ b/src/Writer/ContractToYaml.php @@ -188,7 +188,7 @@ private function mapToText(YamlMap $map, string $indent): string /** * @param Value $value */ - private function pairToText(int|string $key, YamlMap|array|string|bool|null $value, string $indent): string + private function pairToText(int|string $key, YamlMap|YamlSequence|array|string|bool|null $value, string $indent): string { $childIndent = $indent . self::INDENT_STEP; $keyText = (string) $key; @@ -218,7 +218,7 @@ private function pairToText(int|string $key, YamlMap|array|string|bool|null $val * * @param Value $value */ - private function valueToText(YamlMap|array|string|bool|null $value, string $indent): string + private function valueToText(YamlMap|YamlSequence|array|string|bool|null $value, string $indent): string { if ($value instanceof YamlMap) { return $this->mapToText($value, $indent); @@ -226,6 +226,9 @@ private function valueToText(YamlMap|array|string|bool|null $value, string $inde if (is_array($value)) { return $this->flowSequenceToText($value, $indent); } + if ($value instanceof YamlSequence) { + return self::sequenceToText($value, $indent); + } if (is_string($value)) { return $this->scalarToYaml($value, $indent, false); } @@ -241,6 +244,13 @@ private function scalarToYaml(string $value, string $indent, bool $implicitKey): return $this->scalars[sprintf('%d%s|%s', $implicitKey, $indent, $value)] ??= StringToYaml::stringToYaml($value, $indent, $implicitKey); } + private static function sequenceToText(YamlSequence $sequence, string $indent): string + { + $items = array_map(static fn(?string $item): string => $item === null ? '~' : StringToYaml::stringToFlowScalar($item, $indent), $sequence->items); + + return '[' . implode(', ', $items) . ']'; + } + /** * @param list $members */ diff --git a/src/Writer/Protocols/Graphql/BlockToYaml.php b/src/Writer/Protocols/Graphql/BlockToYaml.php index 43852f7..00e7f35 100644 --- a/src/Writer/Protocols/Graphql/BlockToYaml.php +++ b/src/Writer/Protocols/Graphql/BlockToYaml.php @@ -6,7 +6,9 @@ use Bidirekt\PhpSdk\Model\Protocols\Graphql\GraphqlBlock; use Bidirekt\PhpSdk\Model\Protocols\Graphql\Operation; +use Bidirekt\PhpSdk\Model\Protocols\Graphql\SchemaUse; use Bidirekt\PhpSdk\Writer\YamlMap; +use Bidirekt\PhpSdk\Writer\YamlSequence; final class BlockToYaml { @@ -37,11 +39,26 @@ public static function blockToYaml(GraphqlBlock $block): YamlMap private static function operationToYaml(Operation $operation): YamlMap { $field = new YamlMap(); - if ($operation->arguments !== null) { - $field->add('arguments', $operation->arguments->schema); + if ($operation->arguments !== [null]) { + $field->add('arguments', self::usesToYaml($operation->arguments)); } - $field->add('returns', $operation->returns->schema); + $field->add('returns', self::usesToYaml($operation->returns)); return $field; } + + /** + * One schema as its name, several as a list of names, with `~` for a handler that sends no arguments. + * + * @param list $uses + */ + private static function usesToYaml(array $uses): string|YamlSequence + { + $names = array_map(static fn(?SchemaUse $use): ?string => $use?->schema, $uses); + if (count($names) === 1 && $names[0] !== null) { + return $names[0]; + } + + return new YamlSequence($names); + } } diff --git a/src/Writer/Protocols/Graphql/FieldExtraToYaml.php b/src/Writer/Protocols/Graphql/FieldExtraToYaml.php index 53b7a79..992027b 100644 --- a/src/Writer/Protocols/Graphql/FieldExtraToYaml.php +++ b/src/Writer/Protocols/Graphql/FieldExtraToYaml.php @@ -10,7 +10,7 @@ final class FieldExtraToYaml { /** - * `type: scalar` with its `name` in place of the node's type, and `arguments` beside it. + * `type: scalar` with its `name` in place of the node's type, `arguments` beside it, and a schema's `name`. */ public static function extraToYaml(GraphqlExtra $extra, YamlMap $fields): void { @@ -21,5 +21,8 @@ public static function extraToYaml(GraphqlExtra $extra, YamlMap $fields): void if ($extra->arguments !== null) { $fields->add('arguments', $extra->arguments); } + if ($extra->graphqlType !== null) { + $fields->add('name', $extra->graphqlType); + } } } diff --git a/src/Writer/StringToYaml.php b/src/Writer/StringToYaml.php index 7295dc4..e8c4cb6 100644 --- a/src/Writer/StringToYaml.php +++ b/src/Writer/StringToYaml.php @@ -39,6 +39,18 @@ public static function stringToYaml(string $value, string $indent, bool $implici return self::stringToPlain($value, $indent, $implicitKey); } + /** + * A scalar inside a flow collection, where a line break or a flow indicator is never plain. + */ + public static function stringToFlowScalar(string $value, string $indent): string + { + if (preg_match('/[\n[\]{},]/', $value) === 1) { + return self::stringToQuoted($value, $indent, false); + } + + return self::stringToYaml($value, $indent, false); + } + public static function stringToDoubleQuoted(string $value, string $indent, bool $implicitKey): string { $json = self::stringToJson($value); diff --git a/src/Writer/YamlMap.php b/src/Writer/YamlMap.php index 0b6d077..080a33b 100644 --- a/src/Writer/YamlMap.php +++ b/src/Writer/YamlMap.php @@ -7,7 +7,7 @@ /** * A list of strings is a flow sequence of double-quoted scalars. * - * @phpstan-type Value YamlMap|list|string|bool|null + * @phpstan-type Value YamlMap|YamlSequence|list|string|bool|null */ final class YamlMap { @@ -19,7 +19,7 @@ final class YamlMap /** * @param Value $value */ - public function add(int|string $key, YamlMap|array|string|bool|null $value): void + public function add(int|string $key, YamlMap|YamlSequence|array|string|bool|null $value): void { $this->pairs[] = [$key, $value]; } @@ -29,7 +29,7 @@ public function add(int|string $key, YamlMap|array|string|bool|null $value): voi * * @param Value $value */ - public function set(int|string $key, YamlMap|array|string|bool|null $value): void + public function set(int|string $key, YamlMap|YamlSequence|array|string|bool|null $value): void { foreach ($this->pairs as $index => [$existing]) { if ($existing === $key) { diff --git a/src/Writer/YamlSequence.php b/src/Writer/YamlSequence.php new file mode 100644 index 0000000..d3702aa --- /dev/null +++ b/src/Writer/YamlSequence.php @@ -0,0 +1,18 @@ + $items + */ + public function __construct( + public array $items, + ) {} +} diff --git a/tests/Model/DeclarationsToContractTest.php b/tests/Model/DeclarationsToContractTest.php index 6850d65..7145a50 100644 --- a/tests/Model/DeclarationsToContractTest.php +++ b/tests/Model/DeclarationsToContractTest.php @@ -88,14 +88,14 @@ public function testWritesTheSameEnumDerivedWithItsMembersInAnotherOrderOnce(): public function testRejectsAGraphqlNameOfABuiltInScalarWithThePrimitiveToWrite(): void { - $returns = new Operation('query', 'petCount', null, new SchemaUse('Int', new SourceLocation('src/A.php', 3)), new SourceLocation('src/A.php', 2)); + $returns = new Operation('query', 'petCount', [null], [new SchemaUse('Int', new SourceLocation('src/A.php', 3))], new SourceLocation('src/A.php', 2)); $result = DeclarationsToContract::declarationsToContract( new Declarations(['graphql' => [new SideBlock('petstore_api', new GraphqlBlock([$returns]))]]), Protocols::all(), ); - self::assertEquals([new Diagnostic('Int is GraphQL\'s name: write integer', new SourceLocation('src/A.php', 3))], $result->errors); + self::assertEquals([new Diagnostic('Int is GraphQL\'s name: write integer, or [\'scalar\' => \'Int\'] (scalar:Int in a tag) to declare that GraphQL type', new SourceLocation('src/A.php', 3))], $result->errors); } public function testRejectsTheArgumentsOfAFieldThatNameNoSchemaAtTheFieldLine(): void diff --git a/tests/Model/Protocols/Graphql/BlocksToMergedTest.php b/tests/Model/Protocols/Graphql/BlocksToMergedTest.php index d3ec7b6..b6209a2 100644 --- a/tests/Model/Protocols/Graphql/BlocksToMergedTest.php +++ b/tests/Model/Protocols/Graphql/BlocksToMergedTest.php @@ -20,35 +20,29 @@ final class BlocksToMergedTest extends TestCase public function testWritesTheSameCallOfSeveralHandlersOnce(): void { - $merged = BlocksToMerged::sideBlocksToMerged([self::consumed(self::pet(1, 'Pet')), self::consumed(self::pet(10, 'Pet'))]); + $merged = BlocksToMerged::sideBlocksToMerged([self::consumed(self::pet(1, null, 'Pet')), self::consumed(self::pet(10, null, 'Pet'))]); self::assertSame([], $merged->errors); - self::assertEquals(new GraphqlBlock([self::pet(1, 'Pet')]), $merged->block); + self::assertEquals(new GraphqlBlock([self::pet(1, null, 'Pet')]), $merged->block); } - public function testRejectsTheSameCallReturningAnotherSchemaAtBothPlaces(): void + public function testJoinsTheDistinctSchemasOfEveryHandlerInByteOrderWithoutArgumentsFirst(): void { - $merged = BlocksToMerged::sideBlocksToMerged([self::consumed(self::pet(1, 'MaybePet')), self::consumed(self::pet(10, 'Pet'))]); - - $message = 'returns of query pet consumed from "petstore_api" is declared as MaybePet and Pet: declare the same returns in every handler'; - self::assertEquals( - [new Diagnostic($message, new SourceLocation(self::CLIENT, 2)), new Diagnostic($message, new SourceLocation(self::CLIENT, 11))], - $merged->errors, - ); - } - - public function testRejectsArgumentsDeclaredInOneHandlerOnlyAtBothPlaces(): void - { - $withArguments = self::pet(10, 'Pet'); - $withArguments->arguments = new SchemaUse('PetArgs', new SourceLocation(self::CLIENT, 12)); - - $merged = BlocksToMerged::sideBlocksToMerged([self::consumed(self::pet(1, 'Pet')), self::consumed($withArguments)]); + $merged = BlocksToMerged::sideBlocksToMerged([ + self::consumed(self::pet(1, 'PetByNameArgs', 'Pet')), + self::consumed(self::pet(4, null, 'MaybePet')), + self::consumed(self::pet(7, 'PetArgs', 'Pet')), + self::consumed(self::pet(10, 'PetArgs', 'MaybePet')), + ]); - $message = 'arguments of query pet consumed from "petstore_api" is declared in one handler and not in another: declare the same arguments in every handler'; - self::assertEquals( - [new Diagnostic($message, new SourceLocation(self::CLIENT, 1)), new Diagnostic($message, new SourceLocation(self::CLIENT, 12))], - $merged->errors, - ); + self::assertSame([], $merged->errors); + self::assertEquals(new GraphqlBlock([new Operation( + 'query', + 'pet', + [null, self::use('PetArgs', 7), self::use('PetByNameArgs', 1)], + [self::use('MaybePet', 5), self::use('Pet', 2)], + new SourceLocation(self::CLIENT, 1), + )]), $merged->block); } public function testKeepsTheGraphWrittenFirstAndRejectsAnotherName(): void @@ -71,8 +65,15 @@ private static function consumed(Operation $operation): SideBlock return new SideBlock('petstore_api', new GraphqlBlock([$operation])); } - private static function pet(int $line, string $returns): Operation + private static function pet(int $line, ?string $arguments, string $returns): Operation + { + $argumentsUse = $arguments === null ? null : self::use($arguments, $line); + + return new Operation('query', 'pet', [$argumentsUse], [self::use($returns, $line + 1)], new SourceLocation(self::CLIENT, $line)); + } + + private static function use(string $schema, int $line): SchemaUse { - return new Operation('query', 'pet', null, new SchemaUse($returns, new SourceLocation(self::CLIENT, $line + 1)), new SourceLocation(self::CLIENT, $line)); + return new SchemaUse($schema, new SourceLocation(self::CLIENT, $line)); } } diff --git a/tests/Reader/SdkAttributesTest.php b/tests/Reader/SdkAttributesTest.php index 04df4ac..47435ca 100644 --- a/tests/Reader/SdkAttributesTest.php +++ b/tests/Reader/SdkAttributesTest.php @@ -152,7 +152,7 @@ public function testReadsPositionalArgumentsInTheOrderTheAttributeBindsThem(): v { $field = new BidirektField('petId'); $attributes = [ - [new BidirektSchema('Pet', [$field]), ['Pet', [$field]]], + [new BidirektSchema('Pet', [$field], 'PetInput'), ['Pet', [$field], 'PetInput']], [ new BidirektField('pet_name', 'string', 'Item', 'Value', true, false, 'The name', ['card' => 'Card']), ['pet_name', 'string', 'Item', 'Value', true, false, 'The name', ['card' => 'Card']], diff --git a/tests/Writer/ContractToYamlTest.php b/tests/Writer/ContractToYamlTest.php index 5254a28..36948e7 100644 --- a/tests/Writer/ContractToYamlTest.php +++ b/tests/Writer/ContractToYamlTest.php @@ -449,7 +449,7 @@ public function testQuotesFreeTextOnlyWhereYamlWouldReadItAsSomethingElse(): voi self::assertSame(self::HEADER . self::FREE_TEXT_YAML, self::toYaml($contract)); } - public function testWritesTheGraphqlBlocksWithTheirScalarsAndArguments(): void + public function testWritesTheGraphqlBlocksWithTheirScalarsArgumentsAndTypeNames(): void { $at = new SourceLocation('src/Client.php', 1); $bornAt = new PrimitiveNode('string'); @@ -459,14 +459,14 @@ public function testWritesTheGraphqlBlocksWithTheirScalarsAndArguments(): void $contract = new Contract( ['graphql' => new GraphqlBlock([], new Graph('petstore_graph', $at))], ['petstore_api' => ['graphql' => new GraphqlBlock([ - new Operation('mutation', 'adoptPet', new SchemaUse('AdoptArgs', $at), new SchemaUse('Pet', $at), $at), - new Operation('query', 'pets', null, new SchemaUse('PetList', $at), $at), - new Operation('query', 'pet', new SchemaUse('PetArgs', $at), new SchemaUse('Pet', $at), $at), + new Operation('mutation', 'adoptPet', [new SchemaUse('AdoptArgs', $at)], [new SchemaUse('Pet', $at)], $at), + new Operation('query', 'pets', [null], [new SchemaUse('PetList', $at)], $at), + new Operation('query', 'pet', [null, new SchemaUse('PetArgs', $at)], [new SchemaUse('Pet', $at), new SchemaUse('PetName', $at)], $at), ])]], [new NamedSchema('Pet', new ObjectNode([ new Property('bornAt', self::flagged($bornAt, false, true), $at), new Property('reviews', $reviews, $at), - ]), $at)], + ]), $at), new NamedSchema('Status', GraphqlExtra::nodeToTyped(new EnumNode(['AVAILABLE']), 'PetStatus'), $at)], ); self::assertSame( @@ -479,8 +479,8 @@ public function testWritesTheGraphqlBlocksWithTheirScalarsAndArguments(): void graphql: query: pet: - arguments: PetArgs - returns: Pet + arguments: [~, PetArgs] + returns: [Pet, PetName] pets: returns: PetList mutation: @@ -500,6 +500,10 @@ public function testWritesTheGraphqlBlocksWithTheirScalarsAndArguments(): void items: ref: Review arguments: ReviewsArgs + Status: + type: enum + members: ["AVAILABLE"] + name: PetStatus YAML, self::toYaml($contract), diff --git a/tests/Writer/StringToYamlTest.php b/tests/Writer/StringToYamlTest.php index cd4ac68..dcf5bd0 100644 --- a/tests/Writer/StringToYamlTest.php +++ b/tests/Writer/StringToYamlTest.php @@ -119,6 +119,30 @@ public function testWritesAKeyAsTheYamlLibraryDoes(string $key, string $expected self::assertSame($expected, StringToYaml::stringToYaml($key, self::INDENT, true)); } + /** + * @return array + */ + public function flowScalarProvider(): array + { + return [ + 'name' => ['PetArgs', 'PetArgs'], + 'space' => ['a b', 'a b'], + 'comma' => ['a,b', '"a,b"'], + 'closing bracket' => ['x]', '"x]"'], + 'opening brace' => ['{x', '"{x"'], + 'core null word' => ['null', '"null"'], + 'quote inside' => ['a"b', 'a"b'], + ]; + } + + /** + * @dataProvider flowScalarProvider + */ + public function testWritesAFlowSequenceItemAsTheYamlLibraryDoes(string $value, string $expected): void + { + self::assertSame($expected, StringToYaml::stringToFlowScalar($value, self::INDENT)); + } + public function testCountsLengthInUtf16CodeUnits(): void { self::assertSame(4, StringToYaml::stringToUtf16Length("a\u{e9}\u{1f600}")); diff --git a/tests/e2e/run.sh b/tests/e2e/run.sh index b03a3ba..137b9b2 100755 --- a/tests/e2e/run.sh +++ b/tests/e2e/run.sh @@ -148,6 +148,17 @@ petstore_api (1, deployed): · query status returns at \"\$\"" expect_break "$enum_participant" production "$enum_consumer" "$provider" "$expected_enum_break" +joined_consumer=graphql-consumer-joins-reads-of-one-field +joined_participant=e2e_$(printf '%s' "$joined_consumer" | tr - _) +expected_joined_break="$joined_participant 1 cannot be deployed to production + +petstore_api (1, deployed): + PetWithNickname.nickname — $joined_participant reads it, but petstore_api doesn't provide it + → $joined_participant: stop reading it + → petstore_api: provide it + · query pet returns at \"\$.nickname\"" +expect_break "$joined_participant" production "$joined_consumer" "$provider" "$expected_joined_break" + renamed_provider=graphql-graph-renamed-type deploy "$renamed_provider" 2 staging diff --git a/tests/fixtures/rejects-graphql-conflicting-handlers/clients.php b/tests/fixtures/graphql-consumer-joins-handlers/clients.php similarity index 100% rename from tests/fixtures/rejects-graphql-conflicting-handlers/clients.php rename to tests/fixtures/graphql-consumer-joins-handlers/clients.php diff --git a/tests/fixtures/graphql-consumer-joins-handlers/expected.yaml b/tests/fixtures/graphql-consumer-joins-handlers/expected.yaml new file mode 100644 index 0000000..50ca6bf --- /dev/null +++ b/tests/fixtures/graphql-consumer-joins-handlers/expected.yaml @@ -0,0 +1,38 @@ +# Generated by bidirekt/php-sdk. Do not edit. +consumes: + petstore_api: + graphql: + query: + pet: + arguments: [PetArgs, PetByNameArgs] + returns: [MaybePet, Pet] + mutation: + adoptPet: + arguments: [~, PetArgs] + returns: Pet + deletePet: + returns: [Boolean, BooleanOrNull] +schemas: + Boolean: + type: boolean + BooleanOrNull: + type: boolean + nullable: true + MaybePet: + ref: Pet + nullable: true + Pet: + type: object + properties: + name: + type: string + PetArgs: + type: object + properties: + id: + type: string + PetByNameArgs: + type: object + properties: + name: + type: string diff --git a/tests/fixtures/rejects-graphql-conflicting-handlers/tagged.php b/tests/fixtures/graphql-consumer-joins-handlers/tagged.php similarity index 100% rename from tests/fixtures/rejects-graphql-conflicting-handlers/tagged.php rename to tests/fixtures/graphql-consumer-joins-handlers/tagged.php diff --git a/tests/fixtures/graphql-consumer-joins-reads-of-one-field/clients.php b/tests/fixtures/graphql-consumer-joins-reads-of-one-field/clients.php new file mode 100644 index 0000000..4b0c7b0 --- /dev/null +++ b/tests/fixtures/graphql-consumer-joins-reads-of-one-field/clients.php @@ -0,0 +1,46 @@ + PetWithStatus::class])] + public function pet(): void {} +} + +final class NicknameClient +{ + #[BidirektGraphqlConsumer(provider: 'petstore_api', query: 'pet', arguments: PetArgs::class, returns: ['nullable' => PetWithNickname::class])] + public function pet(): void {} +} diff --git a/tests/fixtures/graphql-consumer-joins-reads-of-one-field/expected.yaml b/tests/fixtures/graphql-consumer-joins-reads-of-one-field/expected.yaml new file mode 100644 index 0000000..bbe3246 --- /dev/null +++ b/tests/fixtures/graphql-consumer-joins-reads-of-one-field/expected.yaml @@ -0,0 +1,38 @@ +# Generated by bidirekt/php-sdk. Do not edit. +consumes: + petstore_api: + graphql: + query: + pet: + arguments: PetArgs + returns: [PetWithNicknameOrNull, PetWithStatusOrNull] +schemas: + PetArgs: + type: object + properties: + id: + type: scalar + name: ID + PetWithNickname: + type: object + properties: + nickname: + type: string + nullable: true + name: Pet + PetWithNicknameOrNull: + ref: PetWithNickname + nullable: true + PetWithStatus: + type: object + properties: + status: + ref: Status + name: Pet + PetWithStatusOrNull: + ref: PetWithStatus + nullable: true + Status: + type: enum + members: ["AVAILABLE", "SOLD"] + name: Status diff --git a/tests/fixtures/graphql-type-names-tags/clients.php b/tests/fixtures/graphql-type-names-tags/clients.php new file mode 100644 index 0000000..170ad12 --- /dev/null +++ b/tests/fixtures/graphql-type-names-tags/clients.php @@ -0,0 +1,49 @@ + 'Int'])] + public function petCount(): void {} + + #[BidirektGraphqlConsumer(provider: 'petstore_api', query: 'petId', returns: ['nullable' => ['scalar' => 'ID'], 'name' => 'PetIdOrNull'])] + public function petId(): void {} + + #[BidirektSchema(name: 'Adoption', graphqlType: 'Adoption', fields: [new BidirektField('petId', type: 'string')])] + #[BidirektGraphqlConsumer(provider: 'petstore_api', mutation: 'adoptPet', returns: 'Adoption')] + public function adopt(): void {} +} diff --git a/tests/fixtures/graphql-type-names/expected.yaml b/tests/fixtures/graphql-type-names/expected.yaml new file mode 100644 index 0000000..6716fa5 --- /dev/null +++ b/tests/fixtures/graphql-type-names/expected.yaml @@ -0,0 +1,54 @@ +# Generated by bidirekt/php-sdk. Do not edit. +consumes: + petstore_api: + graphql: + query: + pet: + arguments: PetArgs + returns: Pet + petCount: + returns: Int + petId: + returns: PetIdOrNull + mutation: + adoptPet: + returns: Adoption +schemas: + Adoption: + type: object + properties: + petId: + type: string + name: Adoption + Filter: + type: object + properties: + id: + type: scalar + name: ID + status: + ref: Status + name: PetFilter + Int: + type: scalar + name: Int + Pet: + type: object + properties: + name: + type: scalar + name: String + name: Pet + PetArgs: + type: object + properties: + filter: + ref: Filter + PetIdOrNull: + type: scalar + name: ID + nullable: true + Status: + type: enum + members: ["AVAILABLE", "SOLD"] + name: PetStatus diff --git a/tests/fixtures/rejects-braces-outside-union/expected-error.txt b/tests/fixtures/rejects-braces-outside-union/expected-error.txt index b5e108c..f34edfa 100644 --- a/tests/fixtures/rejects-braces-outside-union/expected-error.txt +++ b/tests/fixtures/rejects-braces-outside-union/expected-error.txt @@ -1,3 +1,3 @@ owners.php:4 cannot read "@bidirekt rest provides GET /owners/{ id }": write "@bidirekt rest provides " owners.php:12 cannot read "@bidirekt rest consumes {payments api} POST /charges": write "@bidirekt rest consumes " -owners.php:19 cannot read "Status}" in "@bidirekt schema": write "name=" +owners.php:19 cannot read "Status}" in "@bidirekt schema": write "=" with key name or graphqlType diff --git a/tests/fixtures/rejects-graphql-conflicting-handlers/expected-error.txt b/tests/fixtures/rejects-graphql-conflicting-handlers/expected-error.txt deleted file mode 100644 index ee2ed45..0000000 --- a/tests/fixtures/rejects-graphql-conflicting-handlers/expected-error.txt +++ /dev/null @@ -1,8 +0,0 @@ -clients.php:30 arguments of query pet consumed from "petstore_api" is declared as PetArgs and PetByNameArgs: declare the same arguments in every handler -clients.php:30 returns of query pet consumed from "petstore_api" is declared as MaybePet and Pet: declare the same returns in every handler -clients.php:33 arguments of mutation adoptPet consumed from "petstore_api" is declared in one handler and not in another: declare the same arguments in every handler -clients.php:39 arguments of query pet consumed from "petstore_api" is declared as PetArgs and PetByNameArgs: declare the same arguments in every handler -clients.php:39 returns of query pet consumed from "petstore_api" is declared as MaybePet and Pet: declare the same returns in every handler -clients.php:42 arguments of mutation adoptPet consumed from "petstore_api" is declared in one handler and not in another: declare the same arguments in every handler -tagged.php:5 returns of mutation deletePet consumed from "petstore_api" is declared as Boolean and BooleanOrNull: declare the same returns in every handler -tagged.php:13 returns of mutation deletePet consumed from "petstore_api" is declared as Boolean and BooleanOrNull: declare the same returns in every handler diff --git a/tests/fixtures/rejects-graphql-type-names-for-primitives/expected-error.txt b/tests/fixtures/rejects-graphql-type-names-for-primitives/expected-error.txt index 1c41b37..b7fe05d 100644 --- a/tests/fixtures/rejects-graphql-type-names-for-primitives/expected-error.txt +++ b/tests/fixtures/rejects-graphql-type-names-for-primitives/expected-error.txt @@ -1,5 +1,5 @@ -clients.php:5 Int is GraphQL's name: write integer -clients.php:13 Float is GraphQL's name: write float -clients.php:21 Boolean is GraphQL's name: write boolean -clients.php:29 String is GraphQL's name: write string -clients.php:37 ID is GraphQL's name: write string +clients.php:5 Int is GraphQL's name: write integer, or ['scalar' => 'Int'] (scalar:Int in a tag) to declare that GraphQL type +clients.php:13 Float is GraphQL's name: write float, or ['scalar' => 'Float'] (scalar:Float in a tag) to declare that GraphQL type +clients.php:21 Boolean is GraphQL's name: write boolean, or ['scalar' => 'Boolean'] (scalar:Boolean in a tag) to declare that GraphQL type +clients.php:29 String is GraphQL's name: write string, or ['scalar' => 'String'] (scalar:String in a tag) to declare that GraphQL type +clients.php:37 ID is GraphQL's name: write string, or ['scalar' => 'ID'] (scalar:ID in a tag) to declare that GraphQL type diff --git a/tests/fixtures/rejects-malformed-field-tags/expected-error.txt b/tests/fixtures/rejects-malformed-field-tags/expected-error.txt index 35e3818..cd0cb9b 100644 --- a/tests/fixtures/rejects-malformed-field-tags/expected-error.txt +++ b/tests/fixtures/rejects-malformed-field-tags/expected-error.txt @@ -1,4 +1,4 @@ -pets.php:3 cannot read "Pet" in "@bidirekt schema": write "name=" +pets.php:3 cannot read "Pet" in "@bidirekt schema": write "=" with key name or graphqlType pets.php:8 cannot name an anonymous class: declare it with "@bidirekt schema name=" pets.php:16 cannot read "kind=integer" in "@bidirekt field": write "=" with key type, items, values, name, optional, nullable, description or union pets.php:19 cannot read "integer" in "@bidirekt field": write "=" with key type, items, values, name, optional, nullable, description or union diff --git a/tests/fixtures/rejects-malformed-graphql-type/clients.php b/tests/fixtures/rejects-malformed-graphql-type/clients.php new file mode 100644 index 0000000..ff2ebab --- /dev/null +++ b/tests/fixtures/rejects-malformed-graphql-type/clients.php @@ -0,0 +1,18 @@ +" diff --git a/tests/fixtures/rejects-malformed-tags/expected-error.txt b/tests/fixtures/rejects-malformed-tags/expected-error.txt index 3d8404a..fdcc75f 100644 --- a/tests/fixtures/rejects-malformed-tags/expected-error.txt +++ b/tests/fixtures/rejects-malformed-tags/expected-error.txt @@ -10,5 +10,5 @@ pets.php:54 cannot read "Pet[] as" as a body: write "", "[]" or pets.php:61 "@bidirekt response" needs a "@bidirekt rest provides" or "@bidirekt rest consumes" tag in the same comment pets.php:68 "@bidirekt" needs a keyword: use rest, request, response, graphql, arguments, returns, graph, schema or field pets.php:69 unknown tag "@bidirekt handles": use rest, request, response, graphql, arguments, returns, graph, schema or field -pets.php:76 cannot read "Status" in "@bidirekt schema": write "name=" +pets.php:76 cannot read "Status" in "@bidirekt schema": write "=" with key name or graphqlType pets.php:85 response status "0200" must be written as 200 diff --git a/tests/fixtures/rejects-schema-arguments-without-follow-on-errors/expected-error.txt b/tests/fixtures/rejects-schema-arguments-without-follow-on-errors/expected-error.txt index eb53b7b..af460fb 100644 --- a/tests/fixtures/rejects-schema-arguments-without-follow-on-errors/expected-error.txt +++ b/tests/fixtures/rejects-schema-arguments-without-follow-on-errors/expected-error.txt @@ -1,3 +1,3 @@ -pet.php:7 unknown argument "nmae" in #[BidirektSchema]: write name or fields +pet.php:7 unknown argument "nmae" in #[BidirektSchema]: write name, fields or graphqlType pet.php:14 "name" is empty: write a name or leave "name" out -pet.php:22 cannot read "nmae=Breeder" in "@bidirekt schema": write "name=" +pet.php:22 cannot read "nmae=Breeder" in "@bidirekt schema": write "=" with key name or graphqlType diff --git a/tests/fixtures/rejects-unknown-option/expected-error.txt b/tests/fixtures/rejects-unknown-option/expected-error.txt index d767ab0..7fd1480 100644 --- a/tests/fixtures/rejects-unknown-option/expected-error.txt +++ b/tests/fixtures/rejects-unknown-option/expected-error.txt @@ -1,3 +1,3 @@ -pet.php:7 unknown argument "nmae" in #[BidirektSchema]: write name or fields +pet.php:7 unknown argument "nmae" in #[BidirektSchema]: write name, fields or graphqlType pet.php:15 unknown argument "nulable" in #[BidirektField]: write name, type, items, values, optional, nullable, description or union pet.php:25 unknown argument "requst" in #[BidirektRestConsumer]: write provider, method, path, responses or request diff --git a/tests/fixtures/rejects-unreadable-enum-schema/expected-error.txt b/tests/fixtures/rejects-unreadable-enum-schema/expected-error.txt index 57b0dce..199334e 100644 --- a/tests/fixtures/rejects-unreadable-enum-schema/expected-error.txt +++ b/tests/fixtures/rejects-unreadable-enum-schema/expected-error.txt @@ -1,2 +1,2 @@ pets.php:12 "self::PREFIX . 'sold'" cannot be read without running the code: write a literal, an array, X::class, a class constant or Enum::Case->value -pets.php:17 unknown argument "label" in #[BidirektSchema]: write name or fields +pets.php:17 unknown argument "label" in #[BidirektSchema]: write name, fields or graphqlType