diff --git a/src/Console/Service/YieldsClassDefinitions.php b/src/Console/Service/YieldsClassDefinitions.php index b46dfe1c..11d626f7 100644 --- a/src/Console/Service/YieldsClassDefinitions.php +++ b/src/Console/Service/YieldsClassDefinitions.php @@ -4,24 +4,19 @@ namespace Membrane\Console\Service; -use Membrane\Filter; use Membrane\Console\Template; -use Membrane\OpenAPI\Builder\OpenAPIRequestBuilder; -use Membrane\OpenAPI\Builder\OpenAPIResponseBuilder; +use Membrane\Filter; +use Membrane\OpenAPI\Builder\Internal\Request; +use Membrane\OpenAPI\Builder\Internal\Response; use Membrane\OpenAPI\ExtractPathParameters\PathParameterExtractor; -use Membrane\OpenAPI\Specification\OpenAPIRequest; -use Membrane\OpenAPI\Specification\OpenAPIResponse; -use Membrane\OpenAPIReader\Exception\CannotRead; -use Membrane\OpenAPIReader\Exception\CannotSupport; -use Membrane\OpenAPIReader\Exception\InvalidOpenAPI; use Membrane\OpenAPIReader\MembraneReader; use Membrane\OpenAPIReader\OpenAPIVersion; use Membrane\OpenAPIReader\ValueObject\Valid\{Enum\Method, V30, V31}; final class YieldsClassDefinitions { - private OpenAPIRequestBuilder $requestBuilder; - private OpenAPIResponseBuilder $responseBuilder; + private Request $requestBuilder; + private Response $responseBuilder; public function __construct( private readonly \Psr\Log\LoggerInterface $logger, @@ -61,11 +56,9 @@ public function __invoke( namespace: "$cacheNamespace\\Request", name: $className, processor: $this->getRequestBuilder()->build( - new OpenAPIRequest( - new PathParameterExtractor($pathUrl), - $path, - $methodObject, - ) + new PathParameterExtractor($pathUrl), + $path, + $methodObject, ) ); } @@ -80,13 +73,7 @@ public function __invoke( yield new Template\Processor( namespace: "$cacheNamespace\\Response\\$prefixedCode", name: $className, - processor: $this->getResponseBuilder()->build( - new OpenAPIResponse( - $operation->operationId, - (string)$code, - $response, - ) - ) + processor: $this->getResponseBuilder()->build($response), ); } } @@ -113,10 +100,10 @@ public function __invoke( private function readOpenAPIFile(string $filepath): V30\OpenAPI | V31\OpenAPI { $this->logger->info("Reading OpenAPI from $filepath"); - return (new MembraneReader([ + return new MembraneReader([ OpenAPIVersion::Version_3_0, OpenAPIVersion::Version_3_1 - ]))->readFromAbsoluteFilePath($filepath); + ])->readFromAbsoluteFilePath($filepath); } /** @param array $existingClassNames */ @@ -143,20 +130,20 @@ private function createSuitableClassName(string $nameToConvert, array $existingC } - private function getRequestBuilder(): OpenAPIRequestBuilder + private function getRequestBuilder(): Request { if (!isset($this->requestBuilder)) { - $this->requestBuilder = new OpenAPIRequestBuilder(); + $this->requestBuilder = new Request(); return $this->requestBuilder; } return $this->requestBuilder; } - private function getResponseBuilder(): OpenAPIResponseBuilder + private function getResponseBuilder(): Response { if (!isset($this->responseBuilder)) { - $this->responseBuilder = new OpenAPIResponseBuilder(); + $this->responseBuilder = new Response(); return $this->responseBuilder; } return $this->responseBuilder; diff --git a/src/OpenAPI/Builder/Arrays.php b/src/OpenAPI/Builder/Internal/Arrays.php similarity index 50% rename from src/OpenAPI/Builder/Arrays.php rename to src/OpenAPI/Builder/Internal/Arrays.php index 6ab1fcf8..2c717de6 100644 --- a/src/OpenAPI/Builder/Arrays.php +++ b/src/OpenAPI/Builder/Internal/Arrays.php @@ -2,15 +2,18 @@ declare(strict_types=1); -namespace Membrane\OpenAPI\Builder; +namespace Membrane\OpenAPI\Builder\Internal; -use Membrane\Builder\Specification; use Membrane\Filter; +use Membrane\OpenAPI\Exception\CannotProcessSpecification; use Membrane\OpenAPI\Filter\FormatStyle\Form; use Membrane\OpenAPI\Filter\FormatStyle\Matrix; use Membrane\OpenAPI\Filter\FormatStyle\PipeDelimited; use Membrane\OpenAPI\Filter\FormatStyle\SpaceDelimited; +use Membrane\OpenAPIReader\ValueObject\Valid\{V30, V31}; use Membrane\OpenAPIReader\ValueObject\Valid\Enum\Style; +use Membrane\OpenAPIReader\ValueObject\Valid\Enum\Type; +use Membrane\OpenAPIReader\ValueObject\Value; use Membrane\Processor; use Membrane\Processor\BeforeSet; use Membrane\Processor\Collection; @@ -19,38 +22,47 @@ use Membrane\Validator\Collection\Unique; use Membrane\Validator\Type\IsList; -class Arrays extends APIBuilder +/** + * @internal see README.md + */ +class Arrays extends Schema { - public function supports(Specification $specification): bool - { - return $specification instanceof \Membrane\OpenAPI\Specification\Arrays; - } - - public function build(Specification $specification): Processor - { - assert($specification instanceof \Membrane\OpenAPI\Specification\Arrays); + public function build( + string $fieldName, + V30\Keywords | V31\Keywords $keywords, + bool $convertFromString, + bool $convertFromArray, + ?string $style, + ?bool $explode, + ): Processor { + if (!in_array(Type::Array, $keywords->types)) { + throw CannotProcessSpecification::mismatchedType( + ['array'], + array_map(fn($t) => $t->value, $keywords->types), + ); + } - $beforeChain = $specification->convertFromArray ? + $beforeChain = $convertFromArray ? [new Filter\String\Implode(',')] : []; - if (isset($specification->style)) { + if (isset($style)) { $beforeChain = array_merge( $beforeChain, - match (Style::from($specification->style)) { + match (Style::from($style)) { Style::Matrix => [ - new Matrix('array', $specification->explode ?? false), + new Matrix('array', $explode ?? false), ], Style::Label => [ new Filter\String\LeftTrim('.'), new Filter\String\Explode( - $specification->explode ?? false ? + $explode ?? false ? '.' : ',' ), ], Style::Form => [ - new Form('array', $specification->explode ?? true), + new Form('array', $explode ?? true), ], Style::Simple => [ new Filter\String\Explode(',') @@ -64,30 +76,39 @@ public function build(Specification $specification): Processor $beforeChain[] = new IsList(); - if ($specification->enum !== null) { - $beforeChain[] = new Contained($specification->enum); + if ( + $keywords->enum !== null + ) { + $beforeChain[] = new Contained(array_map( + fn(Value $v) => $v->value, + $keywords->enum, + )); } - if ($specification->minItems > 0 || $specification->maxItems !== null) { - $beforeChain[] = new Count($specification->minItems, $specification->maxItems); + if ( + $keywords->minItems > 0 + || $keywords->maxItems !== null + ) { + $beforeChain[] = new Count( + $keywords->minItems, + $keywords->maxItems, + ); } - if ($specification->uniqueItems === true) { + if ($keywords->uniqueItems === true) { $beforeChain[] = new Unique(); } $beforeSet = new BeforeSet(...$beforeChain); - $collection = new Collection( - $specification->fieldName, + return new Collection( + $fieldName, $beforeSet, $this->fromSchema( - $specification->items, + $keywords->items, '', - $specification->convertFromString, + $convertFromString, ) ); - - return $collection; } } diff --git a/src/OpenAPI/Builder/Internal/Numeric.php b/src/OpenAPI/Builder/Internal/Numeric.php new file mode 100644 index 00000000..fbe3517b --- /dev/null +++ b/src/OpenAPI/Builder/Internal/Numeric.php @@ -0,0 +1,144 @@ +types; + if (in_array(Type::Integer, $types)) { + $type = Type::Integer->value; + } elseif (in_array(Type::Number, $types)) { + $type = Type::Number->value; + } else { + throw CannotProcessSpecification::mismatchedType( + ['number', 'integer'], + array_map(fn($t) => $t->value, $keywords->types), + ); + } + + $chain = $convertFromArray ? + [new Filter\String\Implode(',')] : + []; + + if (isset($style)) { + switch (Style::tryFrom($style)) { + case Style::Matrix: + $chain[] = new Matrix($type, false); + break; + case Style::Label: + $chain[] = new LeftTrim('.'); + break; + case Style::Form: + case Style::SpaceDelimited: + case Style::PipeDelimited: + $chain[] = new Form($type, false); + break; + } + } + + $chain = array_merge($chain, $type === 'number' + ? $this->handleNumber($keywords, $convertFromString) + : $this->handleInteger($keywords, $convertFromString)); + + if ( + $keywords->enum !== null + ) { + $chain[] = new Contained(array_map( + fn(Value $v) => $v->value, + $keywords->enum, + )); + } + + $chain = array_merge( + $chain, + $this->handleNumericConstraints($keywords), + ); + + return new Field($fieldName, ...$chain); + } + + /** @return Filter[]|Validator[] */ + private function handleNumber( + V30\Keywords | V31\Keywords $keywords, + bool $convertFromString, + ): array { + if (in_array($keywords->format, ['float', 'double'], true)) { + return $convertFromString ? [new NumericString(), new ToFloat()] : [new IsFloat()]; + } else { + return $convertFromString ? [new NumericString(), new ToNumber()] : [new IsNumber()]; + } + } + + /** @return Filter[]|Validator[] */ + private function handleInteger( + V30\Keywords | V31\Keywords $keywords, + bool $convertFromString, + ): array { + return $convertFromString ? [new IntString(), new ToInt()] : [new IsInt()]; + } + + /** @return Validator[] */ + private function handleNumericConstraints( + V30\Keywords | V31\Keywords $keywords, + ): array { + $chain = []; + // if keywords->maximum !== null + // keywords->maximum->limit + if ($keywords->maximum !== null) { + $chain[] = new Maximum( + $keywords->maximum->limit, + $keywords->maximum->exclusive, + ); + } + + if ($keywords->minimum !== null) { + $chain[] = new Minimum( + $keywords->minimum->limit, + $keywords->minimum->exclusive, + ); + } + + if ($keywords->multipleOf !== null) { + $chain[] = new MultipleOf($keywords->multipleOf); + } + + return $chain; + } +} diff --git a/src/OpenAPI/Builder/Internal/Objects.php b/src/OpenAPI/Builder/Internal/Objects.php new file mode 100644 index 00000000..73172857 --- /dev/null +++ b/src/OpenAPI/Builder/Internal/Objects.php @@ -0,0 +1,141 @@ +types)) { + throw CannotProcessSpecification::mismatchedType( + ['object'], + array_map(fn($t) => $t->value, $keywords->types), + ); + } + + $beforeChain = []; + + if ($convertFromArray) { + array_unshift($beforeChain, new Filter\String\Implode(',')); + } + + if (isset($style)) { + $beforeChain = array_merge( + $beforeChain, + match (Style::tryFrom($style)) { + Style::Matrix => [ + new Matrix('object', $explode ?? false), + ], + Style::Label => [ + new Filter\String\LeftTrim('.'), + $explode ?? false ? + new Filter\String\Tokenize('.=') : + new Filter\String\Explode(','), + ], + Style::Simple => [ + $explode === true ? + new Filter\String\Tokenize(',=') : + new Filter\String\Explode(','), + ], + Style::Form => [ + new Form('object', $explode ?? true), + ], + Style::SpaceDelimited => [new SpaceDelimited()], + Style::PipeDelimited => [new PipeDelimited()], + Style::DeepObject => [new DeepObject()], + default => [], + }, + [new Filter\Shape\KeyValueSplit()] + ); + } + + $beforeChain[] = new IsArray(); + + if ( + $keywords->enum !== null + ) { + $beforeChain[] = new Contained(array_map( + fn(Value $v) => $v->value, + $keywords->enum, + )); + } + + if (!empty($keywords->required)) { + $beforeChain[] = new RequiredFields( + ...$keywords->required + ); + } + + if ($keywords->additionalProperties->value === false) { + $beforeChain[] = new FixedFields( + ...array_keys($keywords->properties) + ); + } + + if ( + $keywords->minProperties > 0 + || $keywords->maxProperties !== null + ) { + $beforeChain[] = new Count( + $keywords->minProperties, + $keywords->maxProperties, + ); + } + + $beforeSet = new BeforeSet(...$beforeChain); + + $fields = []; + + foreach ($keywords->properties as $key => $schema) { + $fields [] = $this->fromSchema( + $schema, + $key, + $convertFromString, + ); + } + + if (!is_bool($keywords->additionalProperties->value)) { + $fields [] = new DefaultProcessor( + $this->fromSchema( + $keywords->additionalProperties, + '', + $convertFromString, + ) + ); + } + + return new FieldSet($fieldName, $beforeSet, ...$fields); + } +} diff --git a/src/OpenAPI/Builder/Internal/README.md b/src/OpenAPI/Builder/Internal/README.md new file mode 100644 index 00000000..6b456147 --- /dev/null +++ b/src/OpenAPI/Builder/Internal/README.md @@ -0,0 +1,5 @@ +# Internal Classes Only + +Warning, classes in this directory are **not** intended for use outside of this library. + +They will not be protected by any backwards compatibility guarantee, or subject to semver. diff --git a/src/OpenAPI/Builder/Internal/Request.php b/src/OpenAPI/Builder/Internal/Request.php new file mode 100644 index 00000000..77d91e2b --- /dev/null +++ b/src/OpenAPI/Builder/Internal/Request.php @@ -0,0 +1,156 @@ +getOperations()[$method->value] + ?? throw CannotProcessSpecification::methodNotFound($method->value); + + return new RequestProcessor( + '', + $operation->operationId, + $method, + [ + 'body' => $this->fromRequestBody($operation->requestBody), + ...$this->fromParameters( + $pathParameterExtractor, + $operation->parameters, + ), + ], + ); + } + + private function fromRequestBody( + null | V30\RequestBody | V31\RequestBody $requestBody, + ): Processor { + if ($requestBody === null || $requestBody->content === []) { + return new Field('requestBody', new Passes()); + } + + foreach ($requestBody->content as $contentType => $mediaType) { + if ( + ContentType::fromContentTypeHeader($contentType) !== ContentType::Unmatched + && $mediaType->schema !== null + ) { + return $this->getSchemaBuilder()->fromSchema( + $mediaType->schema, + 'requestBody', + ); + } + } + + throw CannotProcessOpenAPI::unsupportedMediaTypes( + ...array_keys($requestBody->content), + ); + } + + /** + * @param V30\Parameter[] | V31\Parameter[] $parameters + * + * @return Processor[] + */ + private function fromParameters( + ExtractsPathParameters $extractsPathParameters, + array $parameters, + ): array { + $queryParameters = array_filter( + $parameters, + fn($p) => $p->in === In::Query, + ); + + $location = fn(array $chain) => [ + 'required' => [], + 'fields' => [], + 'beforeSet' => $chain, + ]; + $locations = [ + 'path' => $location([new Filter\PathMatcher($extractsPathParameters)]), + 'query' => $location([new Filter\QueryStringToArray(array_combine( + array_map(fn($p) => $p->name, $queryParameters), + array_map( + fn($p) => [ + 'style' => $p->style->value, + 'explode' => $p->explode, + ], + $queryParameters, + ) + ))]), + 'header' => $location([]), + 'cookie' => $location([]), + ]; + + foreach ($parameters as $parameter) { + if ($parameter->hasMediaType() && $parameter->getMediaType() !== 'application/json') { + assert($parameter->getMediaType() !== null); + throw CannotProcessOpenAPI::unsupportedMediaTypes($parameter->getMediaType()); + } + + $locations[$parameter->in->value]['fields'][] = $this + ->getSchemaBuilder() + ->fromSchema( + $parameter->getSchema(), + $parameter->name, + true, + $parameter->in === In::Header, + $parameter->style->value, + $parameter->explode, + ); + + if ($parameter->required) { + $locations[$parameter->in->value]['required'][] = $parameter->name; + } + } + + $fieldSets = []; + foreach ($locations as $in => $location) { + $fields = $location['fields']; + $required = $location['required']; + $beforeSet = $location['beforeSet']; + + if (!empty($required)) { + $beforeSet[] = new RequiredFields(...$required); + } + + if (!empty($beforeSet)) { + $fields[] = new BeforeSet(...$beforeSet); + } + + $fieldSets[$in] = new FieldSet($in, ...$fields); + } + + return $fieldSets; + } + + private function getSchemaBuilder(): Schema + { + return $this->schemaBuilder ??= new Schema(); + } +} diff --git a/src/OpenAPI/Builder/Internal/Response.php b/src/OpenAPI/Builder/Internal/Response.php new file mode 100644 index 00000000..d537e540 --- /dev/null +++ b/src/OpenAPI/Builder/Internal/Response.php @@ -0,0 +1,42 @@ +fromContent($response); + } + + private function fromContent(V30\Response | V31\Response $response): Processor + { + if ($response->content === []) { + return new Field('', new Passes()); + } + + if (! isset($response->content['application/json'])) { + throw CannotProcessOpenAPI::unsupportedMediaTypes( + ...array_keys($response->content), + ); + } + + if ($response->content['application/json']->schema === null) { + return new Field('', new Passes()); + } + + return $this->fromSchema($response->content['application/json']->schema); + } +} diff --git a/src/OpenAPI/Builder/APIBuilder.php b/src/OpenAPI/Builder/Internal/Schema.php similarity index 75% rename from src/OpenAPI/Builder/APIBuilder.php rename to src/OpenAPI/Builder/Internal/Schema.php index 1ca245d7..707ff4be 100644 --- a/src/OpenAPI/Builder/APIBuilder.php +++ b/src/OpenAPI/Builder/Internal/Schema.php @@ -2,9 +2,8 @@ declare(strict_types=1); -namespace Membrane\OpenAPI\Builder; +namespace Membrane\OpenAPI\Builder\Internal; -use Membrane\Builder\Builder; use Membrane\OpenAPI; use Membrane\OpenAPIReader\ValueObject\Valid\{Enum\Type, V30, V31}; use Membrane\Processor; @@ -15,7 +14,10 @@ use Membrane\Validator\Type\IsNull; use Membrane\Validator\Utility; -abstract class APIBuilder implements Builder +/** + * @internal see README.md + */ +class Schema { private Arrays $arrayBuilder; private TrueFalse $trueFalseBuilder; @@ -83,51 +85,56 @@ public function fromSchema( $typeSpecificProcessors = array_map( fn ($t) => match ($t) { - Type::Array => $this->getArrayBuilder() - ->build(new OpenAPI\Specification\Arrays( + Type::Array => $this + ->getArrayBuilder() + ->build( $fieldName, $schema->value, $convertFromString, $convertFromArray, $style, $explode, - )), + ), - Type::Boolean => $this->getTrueFalseBuilder() - ->build(new OpenAPI\Specification\TrueFalse( + Type::Boolean => $this + ->getTrueFalseBuilder() + ->build( $fieldName, $schema->value, $convertFromString, $convertFromArray, $style, - )), + ), - Type::Integer, Type::Number => $this->getNumericBuilder() - ->build(new OpenAPI\Specification\Numeric( + Type::Integer, Type::Number => $this + ->getNumericBuilder() + ->build( $fieldName, $schema->value, $convertFromString, $convertFromArray, - $style - )), + $style, + ), - Type::String => ($this->getStringBuilder()) - ->build(new OpenAPI\Specification\Strings( + Type::String => $this + ->getStringBuilder() + ->build( $fieldName, $schema->value, $convertFromArray, - $style - )), + $style, + ), - Type::Object => $this->getObjectBuilder() - ->build(new OpenAPI\Specification\Objects( + Type::Object => $this + ->getObjectBuilder() + ->build( $fieldName, $schema->value, $convertFromString, $convertFromArray, $style, $explode, - )), + ), Type::Null => new Field($fieldName, new IsNull()), }, @@ -151,7 +158,7 @@ public function fromSchema( /** * @param class-string $complexSchemaClass - * @param non-empty-list $subSchemas + * @param non-empty-list | non-empty-list $subSchemas */ private function fromComplexSchema( string $complexSchemaClass, @@ -193,45 +200,26 @@ private function fromComplexSchema( private function getArrayBuilder(): Arrays { - if (!isset($this->arrayBuilder)) { - $this->arrayBuilder = new Arrays(); - } - - return $this->arrayBuilder; + return $this->arrayBuilder ??= new Arrays(); } private function getTrueFalseBuilder(): TrueFalse { - if (!isset($this->trueFalseBuilder)) { - $this->trueFalseBuilder = new TrueFalse(); - } - - return $this->trueFalseBuilder; + return $this->trueFalseBuilder ??= new TrueFalse(); } private function getObjectBuilder(): Objects { - if (!isset($this->objectBuilder)) { - $this->objectBuilder = new Objects(); - } - - return $this->objectBuilder; + return $this->objectBuilder ??= new Objects(); } private function getNumericBuilder(): Numeric { - if (!isset($this->numericBuilder)) { - $this->numericBuilder = new OpenAPI\Builder\Numeric(); - } - - return $this->numericBuilder; + return $this->numericBuilder ??= new Numeric(); } private function getStringBuilder(): Strings { - if (!isset($this->stringBuilder)) { - $this->stringBuilder = new OpenAPI\Builder\Strings(); - } - return $this->stringBuilder; + return $this->stringBuilder ??= new Strings(); } } diff --git a/src/OpenAPI/Builder/Internal/Strings.php b/src/OpenAPI/Builder/Internal/Strings.php new file mode 100644 index 00000000..2c1b02d3 --- /dev/null +++ b/src/OpenAPI/Builder/Internal/Strings.php @@ -0,0 +1,107 @@ +types)) { + throw CannotProcessSpecification::mismatchedType( + ['string'], + array_map(fn($t) => $t->value, $keywords->types), + ); + } + + + $chain = $convertFromArray ? + [new Implode(',')] : + []; + + if (isset($style)) { + switch (Style::tryFrom($style)) { + case Style::Matrix: + $chain[] = new Matrix('string', false); + break; + case Style::Label: + $chain[] = new LeftTrim('.'); + break; + case Style::Form: + case Style::SpaceDelimited: + case Style::PipeDelimited: + $chain[] = new Form('string', false); + break; + } + } + + $chain[] = new IsString(); + + if ( + $keywords->enum !== null + ) { + $chain[] = new Contained(array_map( + fn(Value $v) => $v->value, + $keywords->enum, + )); + } + + if ($keywords->format === 'date') { + $chain[] = new DateString('Y-m-d', true); + } + + if ($keywords->format === 'date-time') { + $chain[] = new ToUpperCase(); + $chain[] = new AnyOf( + new DateString('Y-m-d\TH:i:sP', true), + new DateString('Y-m-d\TH:i:sp', true), + ); + } + + if ( + $keywords->maxLength !== null + || $keywords->minLength > 0 + ) { + $chain[] = new Length( + $keywords->minLength, + $keywords->maxLength, + ); + } + + if ($keywords->pattern !== null) { + $chain[] = new Regex(sprintf( + '#%s#u', + str_replace('#', '\#', $keywords->pattern), + )); + } + + return new Field($fieldName, ...$chain); + } +} diff --git a/src/OpenAPI/Builder/Internal/TrueFalse.php b/src/OpenAPI/Builder/Internal/TrueFalse.php new file mode 100644 index 00000000..36f233fe --- /dev/null +++ b/src/OpenAPI/Builder/Internal/TrueFalse.php @@ -0,0 +1,77 @@ +types)) { + throw CannotProcessSpecification::mismatchedType( + ['boolean'], + array_map(fn($t) => $t->value, $keywords->types), + ); + } + + $chain = $convertFromArray ? + [new Implode(',')] : + []; + + if (isset($style)) { + switch (Style::tryFrom($style)) { + case Style::Matrix: + $chain[] = new Matrix('boolean', false); + break; + case Style::Label: + $chain[] = new LeftTrim('.'); + break; + case Style::Form: + case Style::SpaceDelimited: + case Style::PipeDelimited: + $chain[] = new Form('boolean', false); + break; + } + } + + $chain = array_merge($chain, $convertFromString ? + [new BoolString(), new ToBool()] : + [new IsBool()]); + + if ( + $keywords->enum !== null + ) { + $chain[] = new Contained(array_map( + fn(Value $v) => $v->value, + $keywords->enum, + )); + } + + return new Field($fieldName, ...$chain); + } +} diff --git a/src/OpenAPI/Builder/Numeric.php b/src/OpenAPI/Builder/Numeric.php deleted file mode 100644 index 287eb364..00000000 --- a/src/OpenAPI/Builder/Numeric.php +++ /dev/null @@ -1,109 +0,0 @@ -convertFromArray ? - [new Filter\String\Implode(',')] : - []; - - if (isset($specification->style)) { - switch (Style::tryFrom($specification->style)) { - case Style::Matrix: - $chain[] = new Matrix($specification->type, false); - break; - case Style::Label: - $chain[] = new LeftTrim('.'); - break; - case Style::Form: - case Style::SpaceDelimited: - case Style::PipeDelimited: - $chain[] = new Form($specification->type, false); - break; - } - } - - $chain = array_merge($chain, $specification->type === 'number' ? - $this->handleNumber($specification) : - $this->handleInteger($specification)); - - if ($specification->enum !== null) { - $chain[] = new Contained($specification->enum); - } - - $chain = array_merge($chain, $this->handleNumericConstraints($specification)); - - return new Field($specification->fieldName, ...$chain); - } - - /** @return Filter[]|Validator[] */ - private function handleNumber(OpenAPI\Specification\Numeric $specification): array - { - if (in_array($specification->format, ['float', 'double'], true)) { - return $specification->convertFromString ? [new NumericString(), new ToFloat()] : [new IsFloat()]; - } else { - return $specification->convertFromString ? [new NumericString(), new ToNumber()] : [new IsNumber()]; - } - } - - /** @return Filter[]|Validator[] */ - private function handleInteger(OpenAPI\Specification\Numeric $specification): array - { - return $specification->convertFromString ? [new IntString(), new ToInt()] : [new IsInt()]; - } - - /** @return Validator[] */ - private function handleNumericConstraints(OpenAPI\Specification\Numeric $specification): array - { - $chain = []; - - if ($specification->maximum !== null) { - $chain[] = new Maximum($specification->maximum, $specification->exclusiveMaximum); - } - - if ($specification->minimum !== null) { - $chain[] = new Minimum($specification->minimum, $specification->exclusiveMinimum); - } - - if ($specification->multipleOf !== null) { - $chain[] = new MultipleOf($specification->multipleOf); - } - - return $chain; - } -} diff --git a/src/OpenAPI/Builder/Objects.php b/src/OpenAPI/Builder/Objects.php deleted file mode 100644 index db834685..00000000 --- a/src/OpenAPI/Builder/Objects.php +++ /dev/null @@ -1,116 +0,0 @@ -convertFromArray) { - array_unshift($beforeChain, new Filter\String\Implode(',')); - } - - if (isset($specification->style)) { - $beforeChain = array_merge( - $beforeChain, - match (Style::tryFrom($specification->style)) { - Style::Matrix => [ - new Matrix('object', $specification->explode ?? false), - ], - Style::Label => [ - new Filter\String\LeftTrim('.'), - $specification->explode ?? false ? - new Filter\String\Tokenize('.=') : - new Filter\String\Explode(','), - ], - Style::Simple => [ - $specification->explode === true ? - new Filter\String\Tokenize(',=') : - new Filter\String\Explode(','), - ], - Style::Form => [ - new Form('object', $specification->explode ?? true), - ], - Style::SpaceDelimited => [new SpaceDelimited()], - Style::PipeDelimited => [new PipeDelimited()], - Style::DeepObject => [new DeepObject()], - default => [], - }, - [new Filter\Shape\KeyValueSplit()] - ); - } - - $beforeChain[] = new IsArray(); - - if ($specification->enum !== null) { - $beforeChain[] = new Contained($specification->enum); - } - - if (!empty($specification->required)) { - $beforeChain[] = new RequiredFields(...$specification->required); - } - - if ($specification->additionalProperties->value === false) { - $beforeChain[] = new FixedFields(...array_keys($specification->properties)); - } - - if ($specification->minProperties > 0 || isset($specification->maxProperties)) { - $beforeChain[] = new Count($specification->minProperties, $specification->maxProperties); - } - - $beforeSet = new BeforeSet(...$beforeChain); - - $fields = []; - - foreach ($specification->properties as $key => $schema) { - $fields [] = $this->fromSchema( - $schema, - $key, - $specification->convertFromString - ); - } - - if (!is_bool($specification->additionalProperties->value)) { - $fields [] = new DefaultProcessor( - $this->fromSchema( - $specification->additionalProperties, - '', - $specification->convertFromString - ) - ); - } - - $processor = new FieldSet($specification->fieldName, $beforeSet, ...$fields); - - return $processor; - } -} diff --git a/src/OpenAPI/Builder/OpenAPIRequestBuilder.php b/src/OpenAPI/Builder/OpenAPIRequestBuilder.php deleted file mode 100644 index 41cba9ad..00000000 --- a/src/OpenAPI/Builder/OpenAPIRequestBuilder.php +++ /dev/null @@ -1,122 +0,0 @@ -fromParameters($specification); - $processors['body'] = $this->fromRequestBody($specification); - - return new RequestProcessor( - '', - $specification->operationId, - $specification->method, - $processors - ); - } - - private function fromRequestBody(OpenAPIRequest $specification): Processor - { - if ($specification->requestBodySchema === null) { - return new Field('requestBody', new Passes()); - } - - return $this->getParameterBuilder()->fromSchema( - $specification->requestBodySchema, - 'requestBody', - ); - } - - /** @return Processor[] */ - private function fromParameters(OpenAPIRequest $specification): array - { - $parameters = array_map( - fn($p) => new Parameter($p), - $specification->parameters, - ); - - $queryParameters = array_filter($parameters, fn($p) => $p->in === 'query'); - - $location = fn(array $chain) => ['required' => [], 'fields' => [], 'beforeSet' => $chain]; - $locations = [ - 'path' => $location([new Filter\PathMatcher($specification->pathParameterExtractor)]), - 'query' => $location([new Filter\QueryStringToArray(array_combine( - array_map(fn($p) => $p->name, $queryParameters), - array_map( - fn($p) => ['style' => $p->style, 'explode' => $p->explode], - $queryParameters, - ) - ))]), - 'header' => $location([]), - 'cookie' => $location([]), - ]; - - foreach ($parameters as $parameter) { - $locations[$parameter->in]['fields'][] = $this - ->getParameterBuilder() - ->fromParameter( - $parameter, - true, - $parameter->in === In::Header->value, - ); - - if ($parameter->required) { - $locations[$parameter->in]['required'][] = $parameter->name; - } - } - - $fieldSets = []; - foreach ($locations as $in => $location) { - $fields = $location['fields']; - $required = $location['required'] ?? []; - $beforeSet = $location['beforeSet'] ?? []; - - if (!empty($required)) { - $beforeSet[] = new RequiredFields(...$required); - } - - if (!empty($beforeSet)) { - $fields[] = new BeforeSet(...$beforeSet); - } - - $fieldSets[$in] = new FieldSet($in, ...$fields); - } - - return $fieldSets; - } - - private function getParameterBuilder(): ParameterBuilder - { - if (!isset($this->parameterBuilder)) { - $this->parameterBuilder = new ParameterBuilder(); - } - return $this->parameterBuilder; - } -} diff --git a/src/OpenAPI/Builder/OpenAPIResponseBuilder.php b/src/OpenAPI/Builder/OpenAPIResponseBuilder.php deleted file mode 100644 index dbd12e8a..00000000 --- a/src/OpenAPI/Builder/OpenAPIResponseBuilder.php +++ /dev/null @@ -1,35 +0,0 @@ -fromContent($specification); - } - - private function fromContent(OpenAPIResponse $response): Processor - { - if ($response->schema === null) { - return new Field('', new Passes()); - } - - return $this->fromSchema($response->schema); - } -} diff --git a/src/OpenAPI/Builder/ParameterBuilder.php b/src/OpenAPI/Builder/ParameterBuilder.php deleted file mode 100644 index b615b34d..00000000 --- a/src/OpenAPI/Builder/ParameterBuilder.php +++ /dev/null @@ -1,41 +0,0 @@ -fromParameter($specification); - } - - public function fromParameter( - Parameter $specification, - bool $convertFromString = false, - bool $convertFromArray = false, - ): Processor { - $schemaProcessor = $this->fromSchema( - $specification->schema, - $specification->name, - $convertFromString, - $convertFromArray, - $specification->style, - $specification->explode, - ); - - return $schemaProcessor; - } -} diff --git a/src/OpenAPI/Builder/RequestBuilder.php b/src/OpenAPI/Builder/RequestBuilder.php index 2164a460..b7662cb3 100644 --- a/src/OpenAPI/Builder/RequestBuilder.php +++ b/src/OpenAPI/Builder/RequestBuilder.php @@ -7,7 +7,6 @@ use Membrane\Builder\{Builder, Specification}; use Membrane\OpenAPI\Exception\CannotProcessSpecification; use Membrane\OpenAPI\ExtractPathParameters\PathMatcher; -use Membrane\OpenAPI\Specification\OpenAPIRequest; use Membrane\OpenAPI\Specification\Request; use Membrane\OpenAPIReader\MembraneReader; use Membrane\OpenAPIReader\OpenAPIVersion; @@ -16,7 +15,7 @@ class RequestBuilder implements Builder { - private OpenAPIRequestBuilder $requestBuilder; + private Internal\Request $requestBuilder; public function supports(Specification $specification): bool { @@ -27,10 +26,10 @@ public function build(Specification $specification): Processor { assert($specification instanceof Request); - $openAPI = (new MembraneReader([ + $openAPI = new MembraneReader([ OpenAPIVersion::Version_3_0, OpenAPIVersion::Version_3_1, - ]))->readFromAbsoluteFilePath($specification->absoluteFilePath); + ])->readFromAbsoluteFilePath($specification->absoluteFilePath); $serverUrl = $this->matchServer($openAPI, $specification->url); foreach ($openAPI->paths as $path => $pathItem) { @@ -39,13 +38,11 @@ public function build(Specification $specification): Processor continue; } - $newSpecification = new OpenAPIRequest( + return $this->getOpenAPIRequestBuilder()->build( $pathMatcher, $pathItem, - $specification->method + $specification->method, ); - - return $this->getOpenAPIRequestBuilder()->build($newSpecification); } throw CannotProcessSpecification::pathNotFound( @@ -54,13 +51,9 @@ public function build(Specification $specification): Processor ); } - private function getOpenAPIRequestBuilder(): OpenAPIRequestBuilder + private function getOpenAPIRequestBuilder(): Internal\Request { - if (!isset($this->requestBuilder)) { - $this->requestBuilder = new OpenAPIRequestBuilder(); - } - - return $this->requestBuilder; + return $this->requestBuilder ??= new Internal\Request(); } private function matchServer( diff --git a/src/OpenAPI/Builder/ResponseBuilder.php b/src/OpenAPI/Builder/ResponseBuilder.php index 6f00b907..89aace67 100644 --- a/src/OpenAPI/Builder/ResponseBuilder.php +++ b/src/OpenAPI/Builder/ResponseBuilder.php @@ -6,10 +6,10 @@ use Membrane\Builder\Builder; use Membrane\Builder\Specification; +use Membrane\OpenAPI\Builder\Internal\Schema; use Membrane\OpenAPI\Exception\CannotProcessResponse; use Membrane\OpenAPI\Exception\CannotProcessSpecification; use Membrane\OpenAPI\ExtractPathParameters\PathMatcher; -use Membrane\OpenAPI\Specification\OpenAPIResponse; use Membrane\OpenAPI\Specification\Response; use Membrane\OpenAPIReader\MembraneReader; use Membrane\OpenAPIReader\OpenAPIVersion; @@ -19,7 +19,7 @@ class ResponseBuilder implements Builder { - private OpenAPIResponseBuilder $responseBuilder; + private Internal\Response $responseBuilder; public function supports(Specification $specification): bool { @@ -30,10 +30,10 @@ public function build(Specification $specification): Processor { assert($specification instanceof Response); - $openAPI = (new MembraneReader([ + $openAPI = new MembraneReader([ OpenAPIVersion::Version_3_0, - OpenAPIVersion::Version_3_1 - ]))->readFromAbsoluteFilePath($specification->absoluteFilePath); + OpenAPIVersion::Version_3_1, + ])->readFromAbsoluteFilePath($specification->absoluteFilePath); $serverUrl = $this->matchServer($openAPI, $specification->url); foreach ($openAPI->paths as $path => $pathItem) { @@ -46,13 +46,7 @@ public function build(Specification $specification): Processor $response = $this->getResponse($operation, $specification->statusCode); - $newSpecification = new OpenAPIResponse( - $operation->operationId, - $specification->statusCode, - $response - ); - - return $this->getOpenAPIResponseBuilder()->build($newSpecification); + return $this->getResponseBuilder()->build($response); } throw CannotProcessSpecification::pathNotFound( @@ -61,16 +55,6 @@ public function build(Specification $specification): Processor ); } - private function getOpenAPIResponseBuilder(): OpenAPIResponseBuilder - { - if (!isset($this->responseBuilder)) { - $this->responseBuilder = new OpenAPIResponseBuilder(); - } - - return $this->responseBuilder; - } - - private function getOperation( V30\PathItem | V31\PathItem $pathItem, Method $method @@ -104,4 +88,9 @@ private function matchServer( return ''; } + + private function getResponseBuilder(): Internal\Response + { + return $this->responseBuilder ??= new Internal\Response(); + } } diff --git a/src/OpenAPI/Builder/Strings.php b/src/OpenAPI/Builder/Strings.php deleted file mode 100644 index 357e3d1b..00000000 --- a/src/OpenAPI/Builder/Strings.php +++ /dev/null @@ -1,85 +0,0 @@ -convertFromArray ? - [new Implode(',')] : - []; - - if (isset($specification->style)) { - switch (Style::tryFrom($specification->style)) { - case Style::Matrix: - $chain[] = new Matrix('string', false); - break; - case Style::Label: - $chain[] = new LeftTrim('.'); - break; - case Style::Form: - case Style::SpaceDelimited: - case Style::PipeDelimited: - $chain[] = new Form('string', false); - break; - } - } - - $chain[] = new IsString(); - - if ($specification->enum !== null) { - $chain[] = new Contained($specification->enum); - } - - if ($specification->format === 'date') { - $chain[] = new DateString('Y-m-d', true); - } - - if ($specification->format === 'date-time') { - $chain[] = new ToUpperCase(); - $chain[] = new AnyOf( - new DateString('Y-m-d\TH:i:sP', true), - new DateString('Y-m-d\TH:i:sp', true), - ); - } - - if ($specification->minLength > 0 || $specification->maxLength !== null) { - $chain[] = new Length($specification->minLength, $specification->maxLength); - } - - if ($specification->pattern !== null) { - $chain[] = new Regex( - sprintf('#%s#u', str_replace('#', '\#', $specification->pattern)) - ); - } - - return new Field($specification->fieldName, ...$chain); - } -} diff --git a/src/OpenAPI/Builder/TrueFalse.php b/src/OpenAPI/Builder/TrueFalse.php deleted file mode 100644 index cb95442c..00000000 --- a/src/OpenAPI/Builder/TrueFalse.php +++ /dev/null @@ -1,61 +0,0 @@ -convertFromArray ? - [new Implode(',')] : - []; - - if (isset($specification->style)) { - switch (Style::tryFrom($specification->style)) { - case Style::Matrix: - $chain[] = new Matrix('boolean', false); - break; - case Style::Label: - $chain[] = new LeftTrim('.'); - break; - case Style::Form: - case Style::SpaceDelimited: - case Style::PipeDelimited: - $chain[] = new Form('boolean', false); - break; - } - } - - $chain = array_merge($chain, $specification->convertFromString ? - [new BoolString(), new ToBool()] : - [new IsBool()]); - - if ($specification->enum !== null) { - $chain[] = new Contained($specification->enum); - } - - return new Field($specification->fieldName, ...$chain); - } -} diff --git a/src/OpenAPI/Specification/APISchema.php b/src/OpenAPI/Specification/APISchema.php deleted file mode 100644 index 4d72c1c3..00000000 --- a/src/OpenAPI/Specification/APISchema.php +++ /dev/null @@ -1,25 +0,0 @@ -enum = isset($keywords->enum) ? - array_map(fn($e) => $e->value, $keywords->enum) : - null; - $this->format = $keywords->format; - } -} diff --git a/src/OpenAPI/Specification/Arrays.php b/src/OpenAPI/Specification/Arrays.php deleted file mode 100644 index 1b4ee97e..00000000 --- a/src/OpenAPI/Specification/Arrays.php +++ /dev/null @@ -1,40 +0,0 @@ -types)) { - throw CannotProcessSpecification::mismatchedType( - ['array'], - array_map(fn($t) => $t->value, $keywords->types), - ); - } - - $this->items = $keywords->items; - $this->maxItems = $keywords->maxItems; - $this->minItems = $keywords->minItems; - $this->uniqueItems = $keywords->uniqueItems; - - parent::__construct($fieldName, $keywords); - } -} diff --git a/src/OpenAPI/Specification/Numeric.php b/src/OpenAPI/Specification/Numeric.php deleted file mode 100644 index ad227985..00000000 --- a/src/OpenAPI/Specification/Numeric.php +++ /dev/null @@ -1,47 +0,0 @@ -types; - if (in_array(Type::Integer, $types)) { - $this->type = Type::Integer->value; - } elseif (in_array(Type::Number, $types)) { - $this->type = Type::Number->value; - } else { - throw CannotProcessSpecification::mismatchedType( - ['integer', 'number'], - array_map(fn($t) => $t->value, $types), - ); - } - - $this->exclusiveMaximum = $keywords->maximum->exclusive ?? false; - $this->exclusiveMinimum = $keywords->minimum->exclusive ?? false; - $this->maximum = $keywords->maximum?->limit; - $this->minimum = $keywords->minimum?->limit; - $this->multipleOf = $keywords->multipleOf; - - parent::__construct($fieldName, $keywords); - } -} diff --git a/src/OpenAPI/Specification/Objects.php b/src/OpenAPI/Specification/Objects.php deleted file mode 100644 index 0bfff5d5..00000000 --- a/src/OpenAPI/Specification/Objects.php +++ /dev/null @@ -1,46 +0,0 @@ -types)) { - throw CannotProcessSpecification::mismatchedType( - ['object'], - array_map(fn($t) => $t->value, $keywords->types), - ); - } - - $this->additionalProperties = $keywords->additionalProperties; - $this->properties = $keywords->properties; - $this->required = $keywords->required; - $this->maxProperties = $keywords->maxProperties; - $this->minProperties = $keywords->minProperties; - - parent::__construct($fieldName, $keywords); - } -} diff --git a/src/OpenAPI/Specification/OpenAPIRequest.php b/src/OpenAPI/Specification/OpenAPIRequest.php deleted file mode 100644 index 2849657d..00000000 --- a/src/OpenAPI/Specification/OpenAPIRequest.php +++ /dev/null @@ -1,65 +0,0 @@ -getOperation($this->path, $this->method); - - $this->parameters = $operation->parameters; - - assert(isset($operation->operationId)); - $this->operationId = $operation->operationId; - - $this->requestBodySchema = isset($operation->requestBody) ? - $this->getRequestBodySchema($operation->requestBody->content) : - null; - } - - /** @param array $content */ - private function getRequestBodySchema(array $content): V30\Schema | V31\Schema | null - { - if ($content === []) { - return null; - } - - foreach ($content as $contentType => $mediaType) { - if ( - ContentType::fromContentTypeHeader($contentType) !== ContentType::Unmatched - && isset($mediaType->schema) - ) { - return $mediaType->schema; - } - } - - throw CannotProcessOpenAPI::unsupportedMediaTypes(...array_keys($content)); - } - - private function getOperation( - V30\PathItem | V31\PathItem $pathItem, - Method $method - ): V30\Operation | V31\Operation { - return $pathItem->getOperations()[$method->value] - ?? throw CannotProcessSpecification::methodNotFound($method->value); - } -} diff --git a/src/OpenAPI/Specification/OpenAPIResponse.php b/src/OpenAPI/Specification/OpenAPIResponse.php deleted file mode 100644 index 7a8c8ef6..00000000 --- a/src/OpenAPI/Specification/OpenAPIResponse.php +++ /dev/null @@ -1,35 +0,0 @@ -schema = $this->getSchema($response->content); - } - - /** @param array $content */ - private function getSchema(array $content): V30\Schema | V31\Schema | null - { - if ($content === []) { - return null; - } - - $schema = $content['application/json']->schema - ?? throw CannotProcessOpenAPI::unsupportedMediaTypes(...array_keys($content)); - - return $schema; - } -} diff --git a/src/OpenAPI/Specification/Parameter.php b/src/OpenAPI/Specification/Parameter.php deleted file mode 100644 index 3d990c97..00000000 --- a/src/OpenAPI/Specification/Parameter.php +++ /dev/null @@ -1,36 +0,0 @@ -name = $parameter->name; - $this->in = $parameter->in->value; - $this->style = $parameter->style->value; - $this->explode = $parameter->explode; - - if ($parameter->hasMediaType() && $parameter->getMediaType() !== 'application/json') { - assert($parameter->getMediaType() !== null); - throw CannotProcessOpenAPI::unsupportedMediaTypes($parameter->getMediaType()); - } - - $this->schema = $parameter->getSchema(); - - $this->required = $parameter->required; - } -} diff --git a/src/OpenAPI/Specification/Strings.php b/src/OpenAPI/Specification/Strings.php deleted file mode 100644 index dbeed3c2..00000000 --- a/src/OpenAPI/Specification/Strings.php +++ /dev/null @@ -1,36 +0,0 @@ -types)) { - throw CannotProcessSpecification::mismatchedType( - ['string'], - array_map(fn($t) => $t->value, $keywords->types), - ); - } - - $this->maxLength = $keywords->maxLength; - $this->minLength = $keywords->minLength; - $this->pattern = $keywords->pattern; - - parent::__construct($fieldName, $keywords); - } -} diff --git a/src/OpenAPI/Specification/TrueFalse.php b/src/OpenAPI/Specification/TrueFalse.php deleted file mode 100644 index 0d8d7671..00000000 --- a/src/OpenAPI/Specification/TrueFalse.php +++ /dev/null @@ -1,29 +0,0 @@ -types)) { - throw CannotProcessSpecification::mismatchedType( - ['boolean'], - array_map(fn($t) => $t->value, $keywords->types), - ); - } - - parent::__construct($fieldName, $keywords); - } -} diff --git a/tests/Console/Command/CacheOpenAPIProcessorsTest.php b/tests/Console/Command/CacheOpenAPIProcessorsTest.php index 8fc2f368..107a3512 100644 --- a/tests/Console/Command/CacheOpenAPIProcessorsTest.php +++ b/tests/Console/Command/CacheOpenAPIProcessorsTest.php @@ -11,12 +11,12 @@ use Membrane\Filter\String\Explode; use Membrane\Filter\String\ToPascalCase; use Membrane\Filter\Type as TypeFilter; +use Membrane\OpenAPI; use Membrane\OpenAPI\Builder as Builder; -use Membrane\OpenAPI\Builder\OpenAPIRequestBuilder; +use Membrane\OpenAPI\Builder\Internal\Request; use Membrane\OpenAPI\ContentType; use Membrane\OpenAPI\ExtractPathParameters\PathParameterExtractor; use Membrane\OpenAPI\Filter\PathMatcher; -use Membrane\OpenAPI\Processor\Request; use Membrane\OpenAPI\Specification as Specification; use Membrane\OpenAPIReader\MembraneReader; use Membrane\OpenAPIReader\OpenAPIVersion; @@ -37,34 +37,25 @@ #[UsesClass(Template\Processor::class)] #[UsesClass(Template\ResponseBuilder::class)] #[UsesClass(Template\RequestBuilder::class)] -#[UsesClass(Builder\APIBuilder::class)] -#[UsesClass(Builder\ParameterBuilder::class)] -#[UsesClass(Builder\Arrays::class)] -#[UsesClass(Builder\Numeric::class)] -#[UsesClass(Builder\Strings::class)] -#[UsesClass(Builder\Objects::class)] -#[UsesClass(Builder\OpenAPIRequestBuilder::class)] -#[UsesClass(Builder\OpenAPIResponseBuilder::class)] +#[UsesClass(Builder\Internal\Schema::class)] +#[UsesClass(Builder\Internal\Arrays::class)] +#[UsesClass(Builder\Internal\Numeric::class)] +#[UsesClass(Builder\Internal\Strings::class)] +#[UsesClass(Builder\Internal\Objects::class)] +#[UsesClass(Builder\Internal\Request::class)] +#[UsesClass(Builder\Internal\Response::class)] #[UsesClass(PathMatcher::class)] #[UsesClass(PathParameterExtractor::class)] #[UsesClass(Processor\AllOf::class)] #[UsesClass(Membrane\OpenAPI\Filter\QueryStringToArray::class)] #[UsesClass(Membrane\OpenAPI\Filter\FormatStyle\Form::class)] -#[UsesClass(Request::class)] -#[UsesClass(Specification\Objects::class)] -#[UsesClass(Specification\OpenAPIRequest::class)] -#[UsesClass(Specification\OpenAPIResponse::class)] +#[UsesClass(OpenAPI\Processor\Request::class)] #[UsesClass(Membrane\Result\Result::class)] #[UsesClass(AlphaNumeric::class)] #[UsesClass(ToPascalCase::class)] #[UsesClass(Explode::class)] #[UsesClass(IntString::class)] #[UsesClass(TypeFilter\ToInt::class)] -#[UsesClass(Specification\APISchema::class)] -#[UsesClass(Specification\Parameter::class)] -#[UsesClass(Specification\Arrays::class)] -#[UsesClass(Specification\Numeric::class)] -#[UsesClass(Specification\Strings::class)] #[UsesClass(Processor\BeforeSet::class)] #[UsesClass(Processor\Collection::class)] #[UsesClass(Processor\Field::class)] @@ -127,11 +118,11 @@ public function failsOnUnreadableOpenAPI(string $openAPI, string $destination, i public static function provideCasesToCache(): array { - $requestBuilder = new OpenAPIRequestBuilder(); - $responseBuilder = new Builder\OpenAPIResponseBuilder(); + $requestBuilder = new Request(); + $responseBuilder = new Builder\Internal\Response(); $petstoreExpandedFilePath = __DIR__ . '/../../fixtures/OpenAPI/docs/petstore-expanded.json'; - $petstoreExpandedOpenApi = (new MembraneReader([OpenAPIVersion::Version_3_0])) + $petstoreExpandedOpenApi = new MembraneReader([OpenAPIVersion::Version_3_0]) ->readFromAbsoluteFilePath($petstoreExpandedFilePath); return [ @@ -141,11 +132,9 @@ public static function provideCasesToCache(): array 'CommandTest\\PetstoreA', 'Request\\FindPets', $requestBuilder->build( - new Specification\OpenAPIRequest( new PathParameterExtractor('/pets'), $petstoreExpandedOpenApi->paths['/pets'], Membrane\OpenAPIReader\ValueObject\Valid\Enum\Method::GET - ) ), ], 'findPets : 200 Response' => [ @@ -154,11 +143,7 @@ public static function provideCasesToCache(): array 'CommandTest\\PetstoreB', 'Response\\Code200\\FindPets', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'findPets', - '200', - $petstoreExpandedOpenApi->paths['/pets']->get->responses['200'] - ) + $petstoreExpandedOpenApi->paths['/pets']->get->responses['200'], ), ], 'findPets : default Response' => [ @@ -167,11 +152,7 @@ public static function provideCasesToCache(): array 'CommandTest\\PetstoreC', 'Response\\CodeDefault\\FindPets', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'findPets', - 'default', $petstoreExpandedOpenApi->paths['/pets']->get->responses['default'] - ) ), ], 'addPet : Request' => [ @@ -180,11 +161,9 @@ public static function provideCasesToCache(): array 'CommandTest\\PetstoreD', 'Request\\AddPet', $requestBuilder->build( - new Specification\OpenAPIRequest( - new PathParameterExtractor('/pets'), - $petstoreExpandedOpenApi->paths['/pets'], - Membrane\OpenAPIReader\ValueObject\Valid\Enum\Method::POST - ) + new PathParameterExtractor('/pets'), + $petstoreExpandedOpenApi->paths['/pets'], + Membrane\OpenAPIReader\ValueObject\Valid\Enum\Method::POST, ), ], 'addPet : 200 Response' => [ @@ -193,11 +172,7 @@ public static function provideCasesToCache(): array 'CommandTest\\PetstoreE', 'Response\\Code200\\AddPet', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'addPet', - '200', - $petstoreExpandedOpenApi->paths['/pets']->post->responses['200'] - ) + $petstoreExpandedOpenApi->paths['/pets']->post->responses['200'], ), ], 'addPet : default Response' => [ @@ -206,11 +181,7 @@ public static function provideCasesToCache(): array 'CommandTest\\PetstoreF', 'Response\\CodeDefault\\AddPet', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'addPet', - 'default', - $petstoreExpandedOpenApi->paths['/pets']->post->responses['default'] - ) + $petstoreExpandedOpenApi->paths['/pets']->post->responses['default'], ), ], 'find pet by id : Request' => [ @@ -219,11 +190,9 @@ public static function provideCasesToCache(): array 'CommandTest\\PetstoreG', 'Request\\FindPetById', $requestBuilder->build( - new Specification\OpenAPIRequest( - new PathParameterExtractor('/pets/{id}'), - $petstoreExpandedOpenApi->paths['/pets/{id}'], - Membrane\OpenAPIReader\ValueObject\Valid\Enum\Method::GET - ) + new PathParameterExtractor('/pets/{id}'), + $petstoreExpandedOpenApi->paths['/pets/{id}'], + Membrane\OpenAPIReader\ValueObject\Valid\Enum\Method::GET, ), ], 'find pet by id : 200 Response' => [ @@ -232,11 +201,7 @@ public static function provideCasesToCache(): array 'CommandTest\\PetstoreH', 'Response\\Code200\\FindPetById', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'find pet by id', - '200', - $petstoreExpandedOpenApi->paths['/pets/{id}']->get->responses['200'] - ) + $petstoreExpandedOpenApi->paths['/pets/{id}']->get->responses['200'] ), ], 'find pet by id : default Response' => [ @@ -245,11 +210,7 @@ public static function provideCasesToCache(): array 'CommandTest\\PetstoreI', 'Response\\CodeDefault\\FindPetById', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'find pet by id', - 'default', - $petstoreExpandedOpenApi->paths['/pets/{id}']->get->responses['default'] - ) + $petstoreExpandedOpenApi->paths['/pets/{id}']->get->responses['default'] ), ], 'deletePet : Request' => [ @@ -258,11 +219,9 @@ public static function provideCasesToCache(): array 'CommandTest\\PetstoreJ', 'Request\\DeletePet', $requestBuilder->build( - new Specification\OpenAPIRequest( - new PathParameterExtractor('/pets/{id}'), - $petstoreExpandedOpenApi->paths['/pets/{id}'], - Membrane\OpenAPIReader\ValueObject\Valid\Enum\Method::DELETE - ) + new PathParameterExtractor('/pets/{id}'), + $petstoreExpandedOpenApi->paths['/pets/{id}'], + Membrane\OpenAPIReader\ValueObject\Valid\Enum\Method::DELETE ), ], 'deletePet : 204 Response' => [ @@ -271,11 +230,7 @@ public static function provideCasesToCache(): array 'CommandTest\\PetstoreK', 'Response\\Code204\\DeletePet', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'deletePet', - '204', - $petstoreExpandedOpenApi->paths['/pets/{id}']->delete->responses['204'] - ) + $petstoreExpandedOpenApi->paths['/pets/{id}']->delete->responses['204'] ), ], ]; @@ -309,23 +264,19 @@ public function cachesProcessorsWithSuitableNamesToAvoidDuplicates(): void { $hatstoreFilePath = __DIR__ . '/../../fixtures/OpenAPI/hatstore.json'; - $hatstoreAPI = (new MembraneReader([OpenAPIVersion::Version_3_0])) + $hatstoreAPI = new MembraneReader([OpenAPIVersion::Version_3_0]) ->readFromAbsoluteFilePath($hatstoreFilePath); - $requestBuilder = new Builder\OpenAPIRequestBuilder(); + $requestBuilder = new Builder\Internal\Request(); $expectedFindHats = $requestBuilder->build( - new Specification\OpenAPIRequest( - new PathParameterExtractor('/hats'), - $hatstoreAPI->paths['/hats'], - Method::GET - ) + new PathParameterExtractor('/hats'), + $hatstoreAPI->paths['/hats'], + Method::GET, ); $expectedFindHats1 = $requestBuilder->build( - new Specification\OpenAPIRequest( - new PathParameterExtractor('/hats/{id}'), - $hatstoreAPI->paths['/hats/{id}'], - Method::GET - ) + new PathParameterExtractor('/hats/{id}'), + $hatstoreAPI->paths['/hats/{id}'], + Method::GET, ); $this->sut->execute( diff --git a/tests/Console/Service/CacheOpenAPIProcessorsTest.php b/tests/Console/Service/CacheOpenAPIProcessorsTest.php index 7525f37a..9c5b46ec 100644 --- a/tests/Console/Service/CacheOpenAPIProcessorsTest.php +++ b/tests/Console/Service/CacheOpenAPIProcessorsTest.php @@ -8,13 +8,12 @@ use Membrane\Console\Service\CacheOpenAPIProcessors; use Membrane\Console\Template; use Membrane\Filter\{String\AlphaNumeric, String\Explode, String\ToPascalCase, Type as TypeFilter}; +use Membrane\OpenAPI; use Membrane\OpenAPI\Builder as Builder; -use Membrane\OpenAPI\Builder\OpenAPIRequestBuilder; +use Membrane\OpenAPI\Builder\Internal\Request; use Membrane\OpenAPI\ContentType; -use Membrane\OpenAPI\Exception\CannotReadOpenAPI; use Membrane\OpenAPI\ExtractPathParameters\PathParameterExtractor; use Membrane\OpenAPI\Filter\PathMatcher; -use Membrane\OpenAPI\Processor\Request; use Membrane\OpenAPI\Specification; use Membrane\OpenAPIReader\MembraneReader; use Membrane\OpenAPIReader\OpenAPIVersion; @@ -33,34 +32,25 @@ #[UsesClass(Template\Processor::class)] #[UsesClass(Template\ResponseBuilder::class)] #[UsesClass(Template\RequestBuilder::class)] -#[UsesClass(Builder\APIBuilder::class)] -#[UsesClass(Builder\Arrays::class)] -#[UsesClass(Builder\Numeric::class)] -#[UsesClass(Builder\Strings::class)] -#[UsesClass(Builder\Objects::class)] -#[UsesClass(Builder\ParameterBuilder::class)] -#[UsesClass(Builder\OpenAPIRequestBuilder::class)] -#[UsesClass(Builder\OpenAPIResponseBuilder::class)] +#[UsesClass(Builder\Internal\Schema::class)] +#[UsesClass(Builder\Internal\Arrays::class)] +#[UsesClass(Builder\Internal\Numeric::class)] +#[UsesClass(Builder\Internal\Strings::class)] +#[UsesClass(Builder\Internal\Objects::class)] +#[UsesClass(Builder\Internal\Request::class)] +#[UsesClass(Builder\Internal\Response::class)] #[UsesClass(PathMatcher::class)] #[UsesClass(PathParameterExtractor::class)] #[UsesClass(Processor\AllOf::class)] -#[UsesClass(Membrane\OpenAPI\Filter\QueryStringToArray::class)] -#[UsesClass(Membrane\OpenAPI\Filter\FormatStyle\Form::class)] -#[UsesClass(Request::class)] -#[UsesClass(Specification\Objects::class)] -#[UsesClass(Specification\OpenAPIRequest::class)] -#[UsesClass(Specification\OpenAPIResponse::class)] +#[UsesClass(OpenAPI\Filter\QueryStringToArray::class)] +#[UsesClass(OpenAPI\Filter\FormatStyle\Form::class)] +#[UsesClass(OpenAPI\Processor\Request::class)] #[UsesClass(Membrane\Result\Result::class)] #[UsesClass(IntString::class)] #[UsesClass(AlphaNumeric::class)] #[UsesClass(ToPascalCase::class)] #[UsesClass(Explode::class)] #[UsesClass(TypeFilter\ToInt::class)] -#[UsesClass(Specification\APISchema::class)] -#[UsesClass(Specification\Parameter::class)] -#[UsesClass(Specification\Arrays::class)] -#[UsesClass(Specification\Numeric::class)] -#[UsesClass(Specification\Strings::class)] #[UsesClass(Processor\BeforeSet::class)] #[UsesClass(Processor\Collection::class)] #[UsesClass(Processor\Field::class)] @@ -122,23 +112,19 @@ public function failsOnUnreadableOpenAPI(string $openAPI, string $destination): public function cachesProcessorsWithSuitableNamesToAvoidDuplicates(): void { $hatstoreFilePath = __DIR__ . '/../../fixtures/OpenAPI/hatstore.json'; - $hatstoreApi = (new MembraneReader([OpenAPIVersion::Version_3_0])) + $hatstoreApi = new MembraneReader([OpenAPIVersion::Version_3_0]) ->readFromAbsoluteFilePath($hatstoreFilePath); - $requestBuilder = new Builder\OpenAPIRequestBuilder(); + $requestBuilder = new Builder\Internal\Request(); $expectedFindHats = $requestBuilder->build( - new Specification\OpenAPIRequest( - new PathParameterExtractor('/hats'), - $hatstoreApi->paths['/hats'], - Method::GET - ) + new PathParameterExtractor('/hats'), + $hatstoreApi->paths['/hats'], + Method::GET, ); $expectedFindHats1 = $requestBuilder->build( - new Specification\OpenAPIRequest( - new PathParameterExtractor('/hats/{id}'), - $hatstoreApi->paths['/hats/{id}'], - Method::GET - ) + new PathParameterExtractor('/hats/{id}'), + $hatstoreApi->paths['/hats/{id}'], + Method::GET, ); $this->sut->cache($hatstoreFilePath, $this->root->url() . '/cache/', 'ServiceTest\\Hatstore'); @@ -216,9 +202,9 @@ public function cacheOnlyResponseProcessors(): void public static function provideCasesOfCachedRequestsFromPetstoreExpanded(): array { - $requestBuilder = new OpenAPIRequestBuilder(); + $requestBuilder = new Request(); $petstoreExpandedFilePath = __DIR__ . '/../../fixtures/OpenAPI/docs/petstore-expanded.json'; - $petstoreExpandedOpenApi = (new MembraneReader([OpenAPIVersion::Version_3_0])) + $petstoreExpandedOpenApi = new MembraneReader([OpenAPIVersion::Version_3_0]) ->readFromAbsoluteFilePath($petstoreExpandedFilePath); return [ @@ -228,11 +214,9 @@ public static function provideCasesOfCachedRequestsFromPetstoreExpanded(): array 'ServiceTest\\PetstoreA', 'Request\\FindPets', $requestBuilder->build( - new Specification\OpenAPIRequest( - new PathParameterExtractor('/pets'), - $petstoreExpandedOpenApi->paths['/pets'], - Method::GET - ) + new PathParameterExtractor('/pets'), + $petstoreExpandedOpenApi->paths['/pets'], + Method::GET, ), ], 'addPet : Request' => [ @@ -241,11 +225,9 @@ public static function provideCasesOfCachedRequestsFromPetstoreExpanded(): array 'ServiceTest\\PetstoreD', 'Request\\AddPet', $requestBuilder->build( - new Specification\OpenAPIRequest( - new PathParameterExtractor('/pets'), - $petstoreExpandedOpenApi->paths['/pets'], - Method::POST - ) + new PathParameterExtractor('/pets'), + $petstoreExpandedOpenApi->paths['/pets'], + Method::POST, ), ], 'find pet by id : Request' => [ @@ -254,11 +236,9 @@ public static function provideCasesOfCachedRequestsFromPetstoreExpanded(): array 'ServiceTest\\PetstoreE', 'Request\\FindPetById', $requestBuilder->build( - new Specification\OpenAPIRequest( - new PathParameterExtractor('/pets/{id}'), - $petstoreExpandedOpenApi->paths['/pets/{id}'], - Method::GET - ) + new PathParameterExtractor('/pets/{id}'), + $petstoreExpandedOpenApi->paths['/pets/{id}'], + Method::GET, ), ], 'deletePet : Request' => [ @@ -267,11 +247,9 @@ public static function provideCasesOfCachedRequestsFromPetstoreExpanded(): array 'ServiceTest\\PetstoreH', 'Request\\DeletePet', $requestBuilder->build( - new Specification\OpenAPIRequest( - new PathParameterExtractor('/pets/{id}'), - $petstoreExpandedOpenApi->paths['/pets/{id}'], - Method::DELETE - ) + new PathParameterExtractor('/pets/{id}'), + $petstoreExpandedOpenApi->paths['/pets/{id}'], + Method::DELETE, ), ], ]; @@ -279,9 +257,9 @@ public static function provideCasesOfCachedRequestsFromPetstoreExpanded(): array public static function provideCasesOfCachedResponsesFromPetstoreExpanded(): array { - $responseBuilder = new Builder\OpenAPIResponseBuilder(); + $responseBuilder = new Builder\Internal\Response(); $petstoreExpandedFilePath = __DIR__ . '/../../fixtures/OpenAPI/docs/petstore-expanded.json'; - $petstoreExpandedOpenApi = (new MembraneReader([OpenAPIVersion::Version_3_0])) + $petstoreExpandedOpenApi = new MembraneReader([OpenAPIVersion::Version_3_0]) ->readFromAbsoluteFilePath($petstoreExpandedFilePath); return [ @@ -291,11 +269,7 @@ public static function provideCasesOfCachedResponsesFromPetstoreExpanded(): arra 'ServiceTest\\PetstoreB', 'Response\\Code200\\FindPets', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'findPets', - '200', - $petstoreExpandedOpenApi->paths['/pets']->get->responses['200'] - ) + $petstoreExpandedOpenApi->paths['/pets']->get->responses['200'] ), ], 'findPets : default Response' => [ @@ -304,11 +278,7 @@ public static function provideCasesOfCachedResponsesFromPetstoreExpanded(): arra 'ServiceTest\\PetstoreC', 'Response\\CodeDefault\\FindPets', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'findPets', - 'default', - $petstoreExpandedOpenApi->paths['/pets']->get->responses['default'] - ) + $petstoreExpandedOpenApi->paths['/pets']->get->responses['default'] ), ], 'addPet : 200 Response' => [ @@ -317,11 +287,7 @@ public static function provideCasesOfCachedResponsesFromPetstoreExpanded(): arra 'ServiceTest\\PetstoreE', 'Response\\Code200\\AddPet', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'addPet', - '200', - $petstoreExpandedOpenApi->paths['/pets']->post->responses['200'] - ) + $petstoreExpandedOpenApi->paths['/pets']->post->responses['200'] ), ], 'addPet : default Response' => [ @@ -330,11 +296,7 @@ public static function provideCasesOfCachedResponsesFromPetstoreExpanded(): arra 'ServiceTest\\PetstoreF', 'Response\\CodeDefault\\AddPet', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'addPet', - 'default', - $petstoreExpandedOpenApi->paths['/pets']->post->responses['default'] - ) + $petstoreExpandedOpenApi->paths['/pets']->post->responses['default'] ), ], 'find pet by id : 200 Response' => [ @@ -343,11 +305,7 @@ public static function provideCasesOfCachedResponsesFromPetstoreExpanded(): arra 'ServiceTest\\PetstoreF', 'Response\\Code200\\FindPetById', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'find pet by id', - '200', - $petstoreExpandedOpenApi->paths['/pets/{id}']->get->responses['200'] - ) + $petstoreExpandedOpenApi->paths['/pets/{id}']->get->responses['200'] ), ], 'find pet by id : default Response' => [ @@ -356,11 +314,7 @@ public static function provideCasesOfCachedResponsesFromPetstoreExpanded(): arra 'ServiceTest\\PetstoreG', 'Response\\CodeDefault\\FindPetById', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'find pet by id', - 'default', - $petstoreExpandedOpenApi->paths['/pets/{id}']->get->responses['default'] - ) + $petstoreExpandedOpenApi->paths['/pets/{id}']->get->responses['default'] ), ], 'deletePet : 204 Response' => [ @@ -369,11 +323,7 @@ public static function provideCasesOfCachedResponsesFromPetstoreExpanded(): arra 'ServiceTest\\PetstoreI', 'Response\\Code204\\DeletePet', $responseBuilder->build( - new Specification\OpenAPIResponse( - 'deletePet', - '204', - $petstoreExpandedOpenApi->paths['/pets/{id}']->delete->responses['204'] - ) + $petstoreExpandedOpenApi->paths['/pets/{id}']->delete->responses['204'] ), ], ]; diff --git a/tests/MembraneTest.php b/tests/MembraneTest.php index d2ffc5da..387ac66c 100644 --- a/tests/MembraneTest.php +++ b/tests/MembraneTest.php @@ -12,7 +12,6 @@ use Membrane\Membrane; use Membrane\OpenAPI\Builder as Builder; use Membrane\OpenAPI\ExtractPathParameters\PathMatcher; -use Membrane\OpenAPI\Specification as OpenAPISpecification; use Membrane\OpenAPI\Specification\Request; use Membrane\OpenAPI\Specification\Response; use Membrane\OpenAPIReader\ValueObject\Valid\Enum\Method; @@ -32,24 +31,15 @@ #[CoversClass(Membrane::class)] #[UsesClass(AttributeBuilder::class)] -#[UsesClass(Builder\APIBuilder::class)] -#[UsesClass(Builder\Arrays::class)] -#[UsesClass(Builder\Numeric::class)] -#[UsesClass(Builder\Strings::class)] -#[UsesClass(Builder\Objects::class)] -#[UsesClass(Builder\ParameterBuilder::class)] -#[UsesClass(Builder\OpenAPIRequestBuilder::class)] -#[UsesClass(Builder\OpenAPIResponseBuilder::class)] +#[UsesClass(Builder\Internal\Schema::class)] +#[UsesClass(Builder\Internal\Arrays::class)] +#[UsesClass(Builder\Internal\Numeric::class)] +#[UsesClass(Builder\Internal\Strings::class)] +#[UsesClass(Builder\Internal\Objects::class)] +#[UsesClass(Builder\Internal\Request::class)] +#[UsesClass(Builder\Internal\Response::class)] #[UsesClass(Builder\RequestBuilder::class)] #[UsesClass(Builder\ResponseBuilder::class)] -#[UsesClass(OpenAPISpecification\Objects::class)] -#[UsesClass(OpenAPISpecification\Parameter::class)] -#[UsesClass(OpenAPISpecification\OpenAPIRequest::class)] -#[UsesClass(OpenAPISpecification\OpenAPIResponse::class)] -#[UsesClass(OpenAPISpecification\APISchema::class)] -#[UsesClass(OpenAPISpecification\Arrays::class)] -#[UsesClass(OpenAPISpecification\Numeric::class)] -#[UsesClass(OpenAPISpecification\Strings::class)] #[UsesClass(Processor\BeforeSet::class)] #[UsesClass(Processor\Collection::class)] #[UsesClass(Processor\FieldSet::class)] diff --git a/tests/OpenAPI/Builder/ArraysTest.php b/tests/OpenAPI/Builder/ArraysTest.php deleted file mode 100644 index d2bd310d..00000000 --- a/tests/OpenAPI/Builder/ArraysTest.php +++ /dev/null @@ -1,204 +0,0 @@ -supports($specification)); - } - - #[Test] - public function doesNotSupportNonArraysSpecification(): void - { - $specification = self::createStub(\Membrane\Builder\Specification::class); - $sut = new Arrays(); - - self::assertFalse($sut->supports($specification)); - } - - public static function specificationsToBuild(): array - { - return [ - '3.0 minimum input' => [ - new Specification\Arrays( - '', - (new V30\Schema( - new Identifier('test'), new Partial\Schema( - type: 'array', - ) - ))->value, - ), - new Collection('', new BeforeSet(new IsList()), new Field('', new Passes())), - ], - '3.1 minimum input' => [ - new Specification\Arrays( - '', - (new V31\Schema( - new Identifier('test'), new Partial\Schema( - type: 'array', - ) - ))->value, - ), - new Collection('', new BeforeSet(new IsList()), new Field('', new Passes())), - ], - '3.0 array' => [ - new Specification\Arrays( - '', - (new V30\Schema( - new Identifier('test'), new Partial\Schema( - type: 'array', - items: new Partial\Schema( - anyOf: [ - new Partial\Schema(type: 'string'), - new Partial\Schema(type: 'integer'), - ] - ) - ) - ))->value, - ), - new Collection( - '', - new BeforeSet(new IsList()), - new AnyOf('', new Field('Branch-1', new IsString()), new Field('Branch-2', new IsInt())), - ), - ], - '3.1 array' => [ - new Specification\Arrays( - '', - (new V31\Schema( - new Identifier('test'), new Partial\Schema( - type: 'array', - items: new Partial\Schema(type: ['string', 'integer']), - ) - ))->value, - ), - new Collection( - '', - new BeforeSet(new IsList()), - new AnyOf('', new Field('', new IsString()), new Field('', new IsInt())), - ), - ], - '3.1 detailed input' => [ - new Specification\Arrays( - '', - (new V31\Schema( - new Identifier(''), new Partial\Schema( - type: 'array', - enum: [new Value([1, 2, 3]), new Value(null)], - nullable: false, - maxItems: 3, - minItems: 1, - uniqueItems: true, - items: new Partial\Schema(type: 'integer'), - format: 'array of ints', - ) - ))->value, - ), - new Collection( - '', - new BeforeSet(new IsList(), new Contained([[1, 2, 3], null]), new Count(1, 3), new Unique()), - new Field('', new IsInt()), - ), - ], - '3.0 nullable items' => [ - new Specification\Arrays( - '', - (new V30\Schema( - new Identifier(''), new Partial\Schema( - type: 'array', - enum: [new Value([1, 2, 3]), new Value(null)], - maxItems: 3, - minItems: 1, - uniqueItems: true, - items: new Partial\Schema(type: 'integer', nullable: true), - format: 'array of ints', - ) - ))->value, - ), - new Collection( - '', - new BeforeSet(new IsList(), new Contained([[1, 2, 3], null]), new Count(1, 3), new Unique()), - new AnyOf('', new Field('', new IsInt()), new Field('', new IsNull())), - ), - ], - '3.1 nullable items' => [ - new Specification\Arrays( - '', - (new V31\Schema( - new Identifier(''), new Partial\Schema( - type: 'array', - enum: [new Value([1, 2, 3]), new Value(null)], - maxItems: 3, - minItems: 1, - uniqueItems: true, - items: new Partial\Schema(type: ['integer', 'null']), - format: 'array of ints', - ) - ))->value, - ), - new Collection( - '', - new BeforeSet(new IsList(), new Contained([[1, 2, 3], null]), new Count(1, 3), new Unique()), - new AnyOf('', new Field('', new IsInt()), new Field('', new IsNull())), - ), - ], - ]; - } - - #[Test] - #[DataProvider('specificationsToBuild')] - public function buildTest(Specification\Arrays $specification, Processor $expected): void - { - $sut = new Arrays(); - - $actual = $sut->build($specification); - - self::assertEquals($expected, $actual); - } -} diff --git a/tests/OpenAPI/Builder/Internal/ArraysTest.php b/tests/OpenAPI/Builder/Internal/ArraysTest.php new file mode 100644 index 00000000..aa1c66c5 --- /dev/null +++ b/tests/OpenAPI/Builder/Internal/ArraysTest.php @@ -0,0 +1,204 @@ + [ + new Collection( + '3.0-mvp', + new BeforeSet(new IsList()), + new Field('', new Passes()), + ), + '3.0-mvp', + self::keywordsV30(), + ], + '3.1-mvp' => [ + new Collection( + '3.1-mvp', + new BeforeSet(new IsList()), + new Field('', new Passes()), + ), + '3.1-mvp', + self::keywordsV31(), + ], + '3.0 array' => [ + new Collection( + '3.0-items-stringint', + new BeforeSet(new IsList()), + new AnyOf( + '', + new Field('Branch-1', new IsString()), + new Field('Branch-2', new IsInt()), + ), + ), + '3.0-items-stringint', + self::keywordsV30( + items: new Partial\Schema( + anyOf: [ + new Partial\Schema(type: 'string'), + new Partial\Schema(type: 'integer'), + ] + ) + ), + ], + '3.1 array' => [ + new Collection( + '3.1-items-stringint', + new BeforeSet(new IsList()), + new AnyOf( + '', + new Field('', new IsString()), + new Field('', new IsInt()), + ), + ), + '3.1-items-stringint', + self::keywordsV31( + items: new Partial\Schema( + type: ['string', 'integer'], + ), + ), + ], + '3.1 detailed input' => [ + new Collection( + '3.1-maxvp', + new BeforeSet(new IsList(), new Contained([[1, 2, 3], null]), new Count(1, 3), new Unique()), + new Field('', new IsInt()), + ), + '3.1-maxvp', + self::keywordsV31( + enum: [new Value([1, 2, 3]), new Value(null)], + maxItems: 3, + minItems: 1, + uniqueItems: true, + items: new Partial\Schema(type: 'integer'), + ), + ], + '3.0 nullable items' => [ + new Collection( + '3.0-items-nullable', + new BeforeSet(new IsList(), new Contained([[1, 2, 3], null]), new Count(1, 3), new Unique()), + new AnyOf('', new Field('', new IsInt()), new Field('', new IsNull())), + ), + '3.0-items-nullable', + self::keywordsV30( + enum: [new Value([1, 2, 3]), new Value(null)], + maxItems: 3, + minItems: 1, + uniqueItems: true, + items: new Partial\Schema(type: 'integer', nullable: true), + ), + ], + '3.1 nullable items' => [ + new Collection( + '3.1-items-nullable', + new BeforeSet(new IsList(), new Contained([[1, 2, 3], null]), new Count(1, 3), new Unique()), + new AnyOf('', new Field('', new IsInt()), new Field('', new IsNull())), + ), + '3.1-items-nullable', + self::keywordsV31( + enum: [new Value([1, 2, 3]), new Value(null)], + maxItems: 3, + minItems: 1, + uniqueItems: true, + items: new Partial\Schema(type: ['integer', 'null']), + ), + ], + ]; + } + + #[Test] + #[DataProvider('specificationsToBuild')] + public function buildTest( + Processor $expected, + string $fieldName, + V30\Keywords | V31\Keywords $keywords, + bool $convertFromString = false, + bool $convertFromArray = false, + ?string $style = null, + ?bool $explode = null, + ): void { + self::assertEquals($expected, new Arrays()->build( + $fieldName, + $keywords, + $convertFromString, + $convertFromArray, + $style, + $explode, + )); + } + + private static function keywordsV30( + ?array $enum = null, + ?int $maxItems = null, + int $minItems = 0, + bool $uniqueItems = false, + ?Partial\Schema $items = null, + ): V30\Keywords { + return new V30\Schema(new Identifier(''), new Partial\Schema( + type: 'array', + enum: $enum, + maxItems: $maxItems, + minItems: $minItems, + uniqueItems: $uniqueItems, + items: $items, + ))->value; + } + + private static function keywordsV31( + ?array $enum = null, + ?int $maxItems = null, + int $minItems = 0, + bool $uniqueItems = false, + ?Partial\Schema $items = null, + ): V31\Keywords { + return new V31\Schema(new Identifier(''), new Partial\Schema( + type: 'array', + enum: $enum, + maxItems: $maxItems, + minItems: $minItems, + uniqueItems: $uniqueItems, + items: $items, + ))->value; + } +} diff --git a/tests/OpenAPI/Builder/Internal/NumericTest.php b/tests/OpenAPI/Builder/Internal/NumericTest.php new file mode 100644 index 00000000..c2ec7000 --- /dev/null +++ b/tests/OpenAPI/Builder/Internal/NumericTest.php @@ -0,0 +1,147 @@ + [ + new Field('int-from-string', new IntString(), new ToInt()), + 'int-from-string', + new V30\Schema(new Identifier(''), new Partial\Schema(type: 'integer'))->value, + true, + ], + 'strict integer input' => [ + new Field('strict-integer', new IsInt()), + 'strict-integer', + new V30\Schema(new Identifier(''), new Partial\Schema(type: 'integer'))->value, + ], + 'number input to convert from string' => [ + new Field('number-from-string', new NumericString(), new ToNumber()), + 'number-from-string', + new V30\Schema(new Identifier(''), new Partial\Schema(type: 'number'))->value, + true, + ], + 'strict number input' => [ + new Field('strict-number', new IsNumber()), + 'strict-number', + new V30\Schema(new Identifier(''), new Partial\Schema(type: 'number'))->value, + ], + 'float input to convert from string' => [ + new Field('float-from-string', new NumericString(), new ToFloat()), + 'float-from-string', + new V30\Schema(new Identifier(''), new Partial\Schema(type: 'number', format: 'float'))->value, + true, + ], + 'strict float input' => [ + new Field('strict-float', new IsFloat()), + 'strict-float', + new V30\Schema(new Identifier(''), new Partial\Schema(type: 'number', format: 'float'))->value, + ], + 'detailed input to convert from string' => [ + new Field( + 'maximum-detail-from-string', + new IntString(), + new ToInt(), + new Contained([1, 2, 3, null]), + new Maximum(4, true), + new Minimum(0, true), + new MultipleOf(3) + ), + 'maximum-detail-from-string', + new V30\Schema(new Identifier(''), new Partial\Schema( + type: 'integer', + enum: [new Value(1), new Value(2), new Value(3), new Value(null)], + multipleOf: 3, + exclusiveMaximum: true, + exclusiveMinimum: true, + maximum: 4, + minimum: 0, + format: 'int', + ))->value, + true, + ], + 'strict detailed input' => [ + new Field( + 'strict-maximum-detail', + new IsInt(), + new Contained([1, 2, 3, null]), + new Maximum(4, true), + new Minimum(0, true), + new MultipleOf(3) + ), + 'strict-maximum-detail', + new V30\Schema(new Identifier(''), new Partial\Schema( + type: 'integer', + enum: [new Value(1), new Value(2), new Value(3), new Value(null)], + multipleOf: 3, + exclusiveMaximum: true, + exclusiveMinimum: true, + maximum: 4, + minimum: 0, + format: 'int', + ))->value, + ], + ]; + } + + #[DataProvider('specificationsToBuild')] + #[Test] + public function buildTest( + Processor $expected, + string $fieldName, + V30\Keywords | V31\Keywords $keywords, + bool $convertFromString = false, + bool $convertFromArray = false, + ?string $style = null, + ): void { + self::assertEquals( + $expected, + new Numeric()->build( + $fieldName, + $keywords, + $convertFromString, + $convertFromArray, + $style, + ), + ); + } +} diff --git a/tests/OpenAPI/Builder/Internal/ObjectsTest.php b/tests/OpenAPI/Builder/Internal/ObjectsTest.php new file mode 100644 index 00000000..0f6297ae --- /dev/null +++ b/tests/OpenAPI/Builder/Internal/ObjectsTest.php @@ -0,0 +1,263 @@ + [ + new FieldSet('3.0-mvp', new BeforeSet(new IsArray())), + '3.0-mvp', + self::keywordsV30(), + ], + '3.0 minProperties' => [ + new FieldSet( + '3.0-min', + new BeforeSet(new IsArray(), new Count(1)), + ), + '3.0-min', + self::keywordsV30(minProperties: 1), + ], + '3.0 maxProperties' => [ + new FieldSet( + '3.0-max', + new BeforeSet(new IsArray(), new Count(0, 1)), + ), + '3.0-max', + self::keywordsV30(maxProperties: 1), + ], + '3.0 minProperties and maxProperties' => [ + new FieldSet( + '3.0-min-max', + new BeforeSet(new IsArray(), new Count(1, 1)), + ), + '3.0-min-max', + self::keywordsV30(maxProperties: 1, minProperties: 1), + ], + '3.0 integer property' => [ + new FieldSet( + '3.0-prop-int', + new BeforeSet(new IsArray()), + new Field('a', new IsInt()), + ), + '3.0-prop-int', + self::keywordsV30( + properties: ['a' => new Partial\Schema(type: 'integer')], + ), + ], + '3.0 additionalProperties:false' => [ + new FieldSet( + '3.0-additional', + new BeforeSet(new IsArray(), new FixedFields('a')), + new Field('a', new IsInt()), + ), + '3.0-additional', + self::keywordsV30( + properties: ['a' => new Partial\Schema(type: 'integer')], + additionalProperties: false, + ), + ], + '3.0 property of string|integer' => [ + new FieldSet( + '3.0-prop-stringint', + new BeforeSet(new IsArray()), + new AnyOf( + 'a', + new Field('Branch-1', new IsString()), + new Field('Branch-2', new IsInt()), + ), + ), + '3.0-prop-stringint', + self::keywordsV30( + properties: ['a' => new Partial\Schema(anyOf: [ + new Partial\Schema(type: 'string'), + new Partial\Schema(type: 'integer'), + ])], + ), + ], + '3.1 property of string|integer' => [ + new FieldSet( + '3.1-prop-int', + new BeforeSet(new IsArray()), + new AnyOf( + 'a', + new Field('a', new IsString()), + new Field('a', new IsInt()), + ), + ), + '3.1-prop-int', + self::keywordsV31( + properties: ['a' => new Partial\Schema( + type: ['string', 'integer'], + )], + ), + ], + 'complex additional properties' => [ + new FieldSet( + '3.0-additional-schema', + new BeforeSet(new IsArray(), new Count(2, 5)), + new DefaultProcessor( + new OneOf( + '', + new Field('Branch-1', new IsBool()), + new Field('Branch-2', new IsInt()), + ) + ) + ), + '3.0-additional-schema', + self::keywordsV30( + maxProperties: 5, + minProperties: 2, + additionalProperties: new Partial\Schema(oneOf: [ + new Partial\Schema(type: 'boolean'), + new Partial\Schema(type: 'integer'), + ]), + ), + ], + 'detailed input' => [ + new FieldSet( + 'max-v-p', + new BeforeSet( + new IsArray(), + new Contained([['id' => 5, 'name' => 'Blink'], null]), + new RequiredFields('id', 'name') + ), + DefaultProcessor::fromFiltersAndValidators(new IsString()), + new Field('id', new IsInt()), + new Field('name', new IsString()) + ), + 'max-v-p', + self::keywordsV30( + enum: [new Value(['id' => 5, 'name' => 'Blink']), new Value(null)], + required: ['id', 'name'], + properties: [ + 'id' => new Partial\Schema(type: 'integer'), + 'name' => new Partial\Schema(type: 'string'), + ], + additionalProperties: new Partial\Schema(type: 'string'), + ), + ], + ]; + } + + #[Test] + #[DataProvider('specificationsToBuild')] + public function buildTest( + Processor $expected, + string $fieldName, + V30\Keywords | V31\Keywords $keywords, + bool $convertFromString = false, + bool $convertFromArray = false, + ?string $style = null, + bool $explode = false, + ): void { + self::assertEquals( + $expected, + new Objects()->build( + $fieldName, + $keywords, + $convertFromString, + $convertFromArray, + $style, + $explode, + ), + ); + } + + /** + * @param array $enum + * @param array $required + * @param array $properties + */ + private static function keywordsV30( + ?array $enum = null, + ?int $maxProperties = null, + int $minProperties = 0, + array $required = [], + array $properties = [], + bool|Partial\Schema $additionalProperties = true, + ): V30\Keywords { + return new V30\Schema(new Identifier(''), new Partial\Schema( + type: 'object', + enum: $enum, + maxProperties: $maxProperties, + minProperties: $minProperties, + required: $required, + properties: $properties, + additionalProperties: $additionalProperties, + ))->value; + } + + /** + * @param array $enum + * @param array $required + * @param array $properties + */ + private static function keywordsV31( + ?array $enum = null, + ?int $maxProperties = null, + int $minProperties = 0, + array $required = [], + array $properties = [], + bool|Partial\Schema $additionalProperties = true, + ): V31\Keywords { + return new V31\Schema(new Identifier(''), new Partial\Schema( + type: 'object', + enum: $enum, + maxProperties: $maxProperties, + minProperties: $minProperties, + required: $required, + properties: $properties, + additionalProperties: $additionalProperties, + ))->value; + } +} diff --git a/tests/OpenAPI/Builder/OpenAPIRequestBuilderTest.php b/tests/OpenAPI/Builder/Internal/RequestTest.php similarity index 89% rename from tests/OpenAPI/Builder/OpenAPIRequestBuilderTest.php rename to tests/OpenAPI/Builder/Internal/RequestTest.php index c173d357..4caf8d87 100644 --- a/tests/OpenAPI/Builder/OpenAPIRequestBuilderTest.php +++ b/tests/OpenAPI/Builder/Internal/RequestTest.php @@ -2,11 +2,10 @@ declare(strict_types=1); -namespace Membrane\Tests\OpenAPI\Builder; +namespace Membrane\Tests\OpenAPI\Builder\Internal; use Generator; use GuzzleHttp\Psr7\ServerRequest; -use Membrane\Builder\Specification; use Membrane\Filter\Shape\KeyValueSplit; use Membrane\Filter\String\Explode; use Membrane\Filter\String\Implode; @@ -15,17 +14,12 @@ use Membrane\Filter\Type\ToBool; use Membrane\Filter\Type\ToInt; use Membrane\Filter\Type\ToNumber; -use Membrane\OpenAPI\Builder\APIBuilder; -use Membrane\OpenAPI\Builder\Arrays; -use Membrane\OpenAPI\Builder\Numeric; -use Membrane\OpenAPI\Builder\Objects; -use Membrane\OpenAPI\Builder\OpenAPIRequestBuilder; -use Membrane\OpenAPI\Builder\ParameterBuilder; +use Membrane\OpenAPI\Builder\Internal; use Membrane\OpenAPI\Builder\RequestBuilder; -use Membrane\OpenAPI\Builder\Strings; use Membrane\OpenAPI\ContentType; use Membrane\OpenAPI\Exception\CannotProcessOpenAPI; use Membrane\OpenAPI\Exception\CannotProcessSpecification; +use Membrane\OpenAPI\ExtractPathParameters\ExtractsPathParameters; use Membrane\OpenAPI\ExtractPathParameters\PathMatcher as PathMatcherClass; use Membrane\OpenAPI\ExtractPathParameters\PathParameterExtractor; use Membrane\OpenAPI\Filter\FormatStyle\DeepObject; @@ -36,18 +30,14 @@ use Membrane\OpenAPI\Filter\PathMatcher; use Membrane\OpenAPI\Filter\QueryStringToArray; use Membrane\OpenAPI\Processor\Request as RequestProcessor; -use Membrane\OpenAPI\Specification\APISchema; -use Membrane\OpenAPI\Specification\OpenAPIRequest; -use Membrane\OpenAPI\Specification\Parameter; use Membrane\OpenAPI\Specification\Request; -use Membrane\OpenAPI\Specification\TrueFalse; use Membrane\OpenAPIReader\FileFormat; use Membrane\OpenAPIReader\MembraneReader; use Membrane\OpenAPIReader\OpenAPIVersion; use Membrane\OpenAPIReader\ValueObject\Partial; +use Membrane\OpenAPIReader\ValueObject\Valid\{V30, V31}; use Membrane\OpenAPIReader\ValueObject\Valid\Enum\Method; use Membrane\OpenAPIReader\ValueObject\Valid\Identifier; -use Membrane\OpenAPIReader\ValueObject\Valid\V30; use Membrane\Processor; use Membrane\Processor\AllOf; use Membrane\Processor\AnyOf; @@ -62,6 +52,7 @@ use Membrane\Result\Message; use Membrane\Result\MessageSet; use Membrane\Result\Result; +use Membrane\Tests\Fixtures; use Membrane\Tests\MembraneTestCase; use Membrane\Validator\FieldSet\RequiredFields; use Membrane\Validator\Numeric\Maximum; @@ -81,35 +72,26 @@ use PHPUnit\Framework\Attributes\UsesClass; use Psr\Http\Message\ServerRequestInterface; -#[CoversClass(OpenAPIRequestBuilder::class)] -#[CoversClass(ParameterBuilder::class)] -#[CoversClass(APIBuilder::class)] +#[CoversClass(Request::class)] #[CoversClass(CannotProcessSpecification::class)] #[CoversClass(CannotProcessOpenAPI::class)] +#[CoversClass(Internal\Schema::class)] #[UsesClass(HumanReadable::class)] // to render test failure messages #[UsesClass(RequestBuilder::class)] -#[UsesClass(\Membrane\OpenAPI\Builder\TrueFalse::class)] -#[UsesClass(OpenAPIRequest::class)] -#[UsesClass(Request::class)] -#[UsesClass(Arrays::class)] -#[UsesClass(Numeric::class)] -#[UsesClass(Objects::class)] -#[UsesClass(Strings::class)] +#[UsesClass(Internal\TrueFalse::class)] +#[UsesClass(Internal\Request::class)] +#[UsesClass(Internal\Arrays::class)] +#[UsesClass(Internal\Numeric::class)] +#[UsesClass(Internal\Objects::class)] +#[UsesClass(Internal\Strings::class)] #[UsesClass(QueryStringToArray::class)] #[UsesClass(PathMatcher::class)] #[UsesClass(PathParameterExtractor::class)] #[UsesClass(PathMatcherClass::class)] #[UsesClass(RequestProcessor::class)] -#[UsesClass(Parameter::class)] -#[UsesClass(APISchema::class)] #[UsesClass(AllOf::class)] #[UsesClass(AnyOf::class)] #[UsesClass(OneOf::class)] -#[UsesClass(\Membrane\OpenAPI\Specification\Arrays::class)] -#[UsesClass(\Membrane\OpenAPI\Specification\Numeric::class)] -#[UsesClass(\Membrane\OpenAPI\Specification\Objects::class)] -#[UsesClass(\Membrane\OpenAPI\Specification\Strings::class)] -#[UsesClass(TrueFalse::class)] #[UsesClass(Explode::class)] #[UsesClass(Implode::class)] #[UsesClass(Tokenize::class)] @@ -144,59 +126,64 @@ #[UsesClass(ContentType::class)] #[UsesClass(LeftTrim::class)] #[UsesClass(KeyValueSplit::class)] -class OpenAPIRequestBuilderTest extends MembraneTestCase +class RequestTest extends MembraneTestCase { - public const FIXTURES = __DIR__ . '/../../fixtures/OpenAPI/'; + public const string FIXTURES = __DIR__ . '/../../../fixtures/OpenAPI/'; - #[Test, TestDox('It will support the OpenAPIRequest Specification')] - public function supportsRequestSpecification(): void + #[Test, TestDox('Exceptions will be thrown for parameters with unsupported content types')] + public function throwsExceptionForUnsupportedContentTypes(): void { - $specification = self::createStub(OpenAPIRequest::class); - $sut = new OpenAPIRequestBuilder(); - - self::assertTrue($sut->supports($specification)); - } + $path = '/path'; + $method = Method::GET; + $mediaType = 'application/pdf'; + $pathItem = Fixtures\OpenAPI\ProvidesUnsupportedContent::pathItemMediaType( + path: $path, + method: $method, + mediaType: $mediaType, + ); - #[Test, TestDox('It will not support any Specifications other than OpenAPIRequest')] - public function doesNotSupportSpecificationsOtherThanRequest(): void - { - $specification = self::createStub(\Membrane\Builder\Specification::class); - $sut = new OpenAPIRequestBuilder(); + self::expectExceptionObject(CannotProcessOpenAPI::unsupportedMediaTypes($mediaType)); - self::assertFalse($sut->supports($specification)); + new Internal\Request()->build( + new PathParameterExtractor($path), + $pathItem, + $method, + ); } #[Test, TestDox('It currently only supports application/json content')] public function throwsExceptionIfParameterHasContentThatIsNotJson(): void { - $openAPI = (new MembraneReader([OpenAPIVersion::Version_3_0])) + $openAPI = new MembraneReader([OpenAPIVersion::Version_3_0]) ->readFromAbsoluteFilePath((self::FIXTURES . 'noReferences.json')); - $specification = new OpenAPIRequest( - new PathParameterExtractor('/requestpathexceptions'), - $openAPI->paths['/requestpathexceptions'], - Method::POST - ); - - $sut = new OpenAPIRequestBuilder(); + $sut = new Internal\Request(); $mediaTypes = array_keys($openAPI->paths['/requestpathexceptions']->post->parameters[0]->content); self::expectExceptionObject(CannotProcessOpenAPI::unsupportedMediaTypes(...$mediaTypes)); - $sut->build($specification); + $sut->build( + new PathParameterExtractor('/requestpathexceptions'), + $openAPI->paths['/requestpathexceptions'], + Method::POST, + ); } #[Test] #[TestDox('Builds a Processor for the Operation Object (specified by the PathItem and method provided')] #[DataProvider('dataSetsForBuild')] - public function buildTest(Specification $spec, Processor $expected): void - { - $sut = new OpenAPIRequestBuilder(); - - $actual = $sut->build($spec); - - self::assertProcessorEquals($expected, $actual); + public function buildTest( + Processor $expected, + ExtractsPathParameters $extractsPathParameters, + V30\PathItem | V31\PathItem $pathItem, + Method $method, + ): void { + self::assertProcessorEquals($expected, new Internal\Request()->build( + $extractsPathParameters, + $pathItem, + $method, + )); } #[Test] @@ -205,13 +192,19 @@ public function buildTest(Specification $spec, Processor $expected): void #[DataProvider('provideAPIWithQueryParameters')] #[DataProvider('provideAPIWithHeaderParameters')] public function itBuildsProcessorsThatValidateRequests( - OpenAPIRequest $specification, + Result $expected, + ExtractsPathParameters $extractsPathParameters, + V30\PathItem | V31\PathItem $pathItem, + Method $method, array | ServerRequestInterface $serverRequest, - Result $expected ): void { - $sut = new OpenAPIRequestBuilder(); + $sut = new Internal\Request(); - $processor = $sut->build($specification); + $processor = $sut->build( + $extractsPathParameters, + $pathItem, + $method, + ); $actual = $processor->process(new FieldName(''), $serverRequest); @@ -223,14 +216,9 @@ public static function dataSetsForBuild(): Generator { $reader = new MembraneReader([OpenAPIVersion::Version_3_0]); $noRefAPI = $reader - ->readFromAbsoluteFilePath(__DIR__ . '/../../fixtures/OpenAPI/noReferences.json'); + ->readFromAbsoluteFilePath(__DIR__ . '/../../../fixtures/OpenAPI/noReferences.json'); yield 'Request: no path params, no operation params, no requestBody' => [ - new OpenAPIRequest( - new PathParameterExtractor('/path'), - $noRefAPI->paths['/path'], - Method::GET - ), new RequestProcessor( '', 'path-get', @@ -248,13 +236,11 @@ public static function dataSetsForBuild(): Generator 'body' => new Field('requestBody', new Passes()), ] ), + new PathParameterExtractor('/path'), + $noRefAPI->paths['/path'], + Method::GET, ]; yield 'Patch Request: no path params, no operation params, no requestBody' => [ - new OpenAPIRequest( - new PathParameterExtractor('/path'), - $noRefAPI->paths['/path'], - Method::PATCH - ), new RequestProcessor( '', 'path-patch', @@ -272,13 +258,11 @@ public static function dataSetsForBuild(): Generator 'body' => new Field('requestBody', new Passes()), ] ), + new PathParameterExtractor('/path'), + $noRefAPI->paths['/path'], + Method::PATCH, ]; yield 'Request: path param in path, no operation params, no requestBody' => [ - new OpenAPIRequest( - new PathParameterExtractor('/requestpathone/{id}'), - $noRefAPI->paths['/requestpathone/{id}'], - Method::GET - ), new RequestProcessor( '', 'requestpathone-get', @@ -298,13 +282,11 @@ public static function dataSetsForBuild(): Generator 'body' => new Field('requestBody', new Passes()), ] ), + new PathParameterExtractor('/requestpathone/{id}'), + $noRefAPI->paths['/requestpathone/{id}'], + Method::GET, ]; yield 'Request: path param in path, operation param in query not required, no requestBody' => [ - new OpenAPIRequest( - new PathParameterExtractor('/requestpathone/{id}'), - $noRefAPI->paths['/requestpathone/{id}'], - Method::POST - ), new RequestProcessor( '', 'requestpathone-post', @@ -328,13 +310,11 @@ public static function dataSetsForBuild(): Generator 'body' => new Field('requestBody', new Passes()), ] ), + new PathParameterExtractor('/requestpathone/{id}'), + $noRefAPI->paths['/requestpathone/{id}'], + Method::POST, ]; yield 'Request: path param in path, operation param in query required, no requestBody' => [ - new OpenAPIRequest( - new PathParameterExtractor('/requestpathone/{id}'), - $noRefAPI->paths['/requestpathone/{id}'], - Method::PUT, - ), new RequestProcessor( '', 'requestpathone-put', @@ -363,13 +343,11 @@ public static function dataSetsForBuild(): Generator 'body' => new Field('requestBody', new Passes()), ] ), + new PathParameterExtractor('/requestpathone/{id}'), + $noRefAPI->paths['/requestpathone/{id}'], + Method::PUT, ]; yield 'Request: path param in path, operation param in query with json content, required, no requestBody' => [ - new OpenAPIRequest( - new PathParameterExtractor('/requestpathone/{id}'), - $noRefAPI->paths['/requestpathone/{id}'], - Method::DELETE - ), new RequestProcessor( '', 'requestpathone-delete', @@ -398,13 +376,11 @@ public static function dataSetsForBuild(): Generator 'body' => new Field('requestBody', new Passes()), ] ), + new PathParameterExtractor('/requestpathone/{id}'), + $noRefAPI->paths['/requestpathone/{id}'], + Method::DELETE, ]; yield 'Request: path param in header, no requestBody' => [ - new OpenAPIRequest( - new PathParameterExtractor('/requestpathtwo'), - $noRefAPI->paths['/requestpathtwo'], - Method::GET - ), new RequestProcessor( '', 'requestpathtwo-get', @@ -422,13 +398,11 @@ public static function dataSetsForBuild(): Generator 'body' => new Field('requestBody', new Passes()), ] ), + new PathParameterExtractor('/requestpathtwo'), + $noRefAPI->paths['/requestpathtwo'], + Method::GET, ]; yield 'Request: path param in header, operation param in cookie, no requestBody' => [ - new OpenAPIRequest( - new PathParameterExtractor('/requestpathtwo'), - $noRefAPI->paths['/requestpathtwo'], - Method::POST - ), new RequestProcessor( '', 'requestpathtwo-post', @@ -446,14 +420,12 @@ public static function dataSetsForBuild(): Generator 'body' => new Field('requestBody', new Passes()), ] ), + new PathParameterExtractor('/requestpathtwo'), + $noRefAPI->paths['/requestpathtwo'], + Method::POST, ]; yield 'Request: identical param in header and query, no requestBody' => [ - new OpenAPIRequest( - new PathParameterExtractor('/requestpathtwo'), - $noRefAPI->paths['/requestpathtwo'], - Method::PUT - ), new RequestProcessor( '', 'requestpathtwo-put', @@ -475,14 +447,12 @@ public static function dataSetsForBuild(): Generator 'body' => new Field('requestBody', new Passes()), ] ), + new PathParameterExtractor('/requestpathtwo'), + $noRefAPI->paths['/requestpathtwo'], + Method::PUT, ]; yield 'Request: same param in path and operation with different types, no requestBody' => [ - new OpenAPIRequest( - new PathParameterExtractor('/requestpathtwo'), - $noRefAPI->paths['/requestpathtwo'], - Method::DELETE - ), new RequestProcessor( '', 'requestpathtwo-delete', @@ -500,14 +470,12 @@ public static function dataSetsForBuild(): Generator 'body' => new Field('requestBody', new Passes()), ] ), + new PathParameterExtractor('/requestpathtwo'), + $noRefAPI->paths['/requestpathtwo'], + Method::DELETE, ]; yield 'Request: requestBody param' => [ - new OpenAPIRequest( - new PathParameterExtractor('/requestbodypath'), - $noRefAPI->paths['/requestbodypath'], - Method::GET - ), new RequestProcessor( '', 'requestbodypath-get', @@ -525,14 +493,12 @@ public static function dataSetsForBuild(): Generator 'body' => new Field('requestBody', new IsInt()), ] ), + new PathParameterExtractor('/requestbodypath'), + $noRefAPI->paths['/requestbodypath'], + Method::GET, ]; yield 'Request: operation param in query, requestBody param' => [ - new OpenAPIRequest( - new PathParameterExtractor('/requestbodypath'), - $noRefAPI->paths['/requestbodypath'], - Method::POST - ), new RequestProcessor( '', 'requestbodypath-post', @@ -554,14 +520,12 @@ public static function dataSetsForBuild(): Generator 'body' => new Field('requestBody', new IsInt()), ] ), + new PathParameterExtractor('/requestbodypath'), + $noRefAPI->paths['/requestbodypath'], + Method::POST, ]; yield 'Request: path param in path, operation param in query, header, cookie, requestBody param' => [ - new OpenAPIRequest( - new PathParameterExtractor('/requestbodypath/{id}'), - $noRefAPI->paths['/requestbodypath/{id}'], - Method::GET - ), new RequestProcessor( '', 'requestbodypath-id-get', @@ -585,6 +549,9 @@ public static function dataSetsForBuild(): Generator 'body' => new Field('requestBody', new IsFloat()), ] ), + new PathParameterExtractor('/requestbodypath/{id}'), + $noRefAPI->paths['/requestbodypath/{id}'], + Method::GET, ]; $complexQueryAPI = fn(string $xOf) => $reader->readFromString( @@ -628,11 +595,6 @@ public static function dataSetsForBuild(): Generator ); yield 'query parameter with oneOf' => [ - new OpenAPIRequest( - new PathParameterExtractor('/path'), - $complexQueryAPI('oneOf')->paths['/path'], - Method::GET - ), $complexProcessor( new OneOf( 'complexity', @@ -641,14 +603,12 @@ public static function dataSetsForBuild(): Generator ), ['complexity' => ['style' => 'form', 'explode' => true]] ), + new PathParameterExtractor('/path'), + $complexQueryAPI('oneOf')->paths['/path'], + Method::GET, ]; yield 'query parameter with anyOf' => [ - new OpenAPIRequest( - new PathParameterExtractor('/path'), - $complexQueryAPI('anyOf')->paths['/path'], - Method::GET - ), $complexProcessor( new AnyOf( 'complexity', @@ -657,14 +617,12 @@ public static function dataSetsForBuild(): Generator ), ['complexity' => ['style' => 'form', 'explode' => true]] ), + new PathParameterExtractor('/path'), + $complexQueryAPI('anyOf')->paths['/path'], + Method::GET ]; yield 'query parameter with allOf' => [ - new OpenAPIRequest( - new PathParameterExtractor('/path'), - $complexQueryAPI('allOf')->paths['/path'], - Method::GET - ), $complexProcessor( new AllOf( 'complexity', @@ -673,25 +631,22 @@ public static function dataSetsForBuild(): Generator ), ['complexity' => ['style' => 'form', 'explode' => true]] ), + new PathParameterExtractor('/path'), + $complexQueryAPI('allOf')->paths['/path'], + Method::GET, ]; } public static function dataSetsForDocExamples(): array { - $petstoreApi = (new MembraneReader([OpenAPIVersion::Version_3_0])) + $petstoreApi = new MembraneReader([OpenAPIVersion::Version_3_0]) ->readFromAbsoluteFilePath(self::FIXTURES . '/docs/petstore.yaml'); - $petstoreExpandedApi = (new MembraneReader([OpenAPIVersion::Version_3_0])) + $petstoreExpandedApi = new MembraneReader([OpenAPIVersion::Version_3_0]) ->readFromAbsoluteFilePath(self::FIXTURES . '/docs/petstore-expanded.json'); return [ 'petstore /pets get, minimal (valid)' => [ - new OpenAPIRequest( - new PathParameterExtractor('/pets'), - $petstoreApi->paths['/pets'], - Method::GET - ), - new ServerRequest('get', 'http://petstore.swagger.io/v1/pets'), Result::valid( [ 'request' => ['method' => 'get', 'operationId' => 'listPets'], @@ -702,14 +657,12 @@ public static function dataSetsForDocExamples(): array 'body' => '', ], ), + new PathParameterExtractor('/pets'), + $petstoreApi->paths['/pets'], + Method::GET, + new ServerRequest('get', 'http://petstore.swagger.io/v1/pets'), ], 'petstore /pets/{petid} get, minimal (valid)' => [ - new OpenAPIRequest( - new PathParameterExtractor('/pets/{petId}'), - $petstoreApi->paths['/pets/{petId}'], - Method::GET - ), - new ServerRequest('get', 'http://petstore.swagger.io/v1/pets/Harley'), Result::valid( [ 'request' => ['method' => 'get', 'operationId' => 'showPetById'], @@ -720,14 +673,12 @@ public static function dataSetsForDocExamples(): array 'body' => '', ], ), + new PathParameterExtractor('/pets/{petId}'), + $petstoreApi->paths['/pets/{petId}'], + Method::GET, + new ServerRequest('get', 'http://petstore.swagger.io/v1/pets/Harley'), ], 'petstore expanded /pets get (invalid)' => [ - new OpenAPIRequest( - new PathParameterExtractor('/pets'), - $petstoreExpandedApi->paths['/pets'], - Method::GET - ), - new ServerRequest('get', 'http://petstore.swagger.io/api/pets?limit=five'), Result::invalid( [ 'request' => ['method' => 'get', 'operationId' => 'findPets'], @@ -742,14 +693,12 @@ public static function dataSetsForDocExamples(): array new Message('String value must be an integer.', []) ) ), + new PathParameterExtractor('/pets'), + $petstoreExpandedApi->paths['/pets'], + Method::GET, + new ServerRequest('get', 'http://petstore.swagger.io/api/pets?limit=five'), ], 'petstore expanded /pets get, minimal (valid)' => [ - new OpenAPIRequest( - new PathParameterExtractor('/pets'), - $petstoreExpandedApi->paths['/pets'], - Method::GET - ), - new ServerRequest('get', 'http://petstore.swagger.io/api/pets?limit=5&tags=cat,tabby'), Result::valid( [ 'request' => ['method' => 'get', 'operationId' => 'findPets'], @@ -760,14 +709,21 @@ public static function dataSetsForDocExamples(): array 'body' => '', ] ), + new PathParameterExtractor('/pets'), + $petstoreExpandedApi->paths['/pets'], + Method::GET, + new ServerRequest('get', 'http://petstore.swagger.io/api/pets?limit=5&tags=cat,tabby'), ], ]; } - /** @return Generator */ public static function provideAPIWithPathParameters(): Generator @@ -778,16 +734,6 @@ public static function provideAPIWithPathParameters(): Generator string $input, array $output, ) => [ - new OpenAPIRequest( - new PathParameterExtractor($path), - V30\PathItem::fromPartial( - new Identifier('test-path'), - [], - new Partial\PathItem(path: '/path', get: $operation), - ), - Method::GET - ), - new ServerRequest('get', $input), Result::valid([ 'request' => ['method' => 'get', 'operationId' => 'test-op'], 'path' => $output, @@ -796,6 +742,14 @@ public static function provideAPIWithPathParameters(): Generator 'cookie' => [], 'body' => '', ]), + new PathParameterExtractor($path), + V30\PathItem::fromPartial( + new Identifier('test-path'), + [], + new Partial\PathItem(path: '/path', get: $operation), + ), + Method::GET, + new ServerRequest('get', $input), ]; yield 'bool path parameter (style:simple, explode:false)' => $dataSet( @@ -1479,10 +1433,13 @@ public static function provideAPIWithPathParameters(): Generator ); } - /** @return Generator */ public static function provideAPIWithQueryParameters(): Generator @@ -1492,16 +1449,6 @@ public static function provideAPIWithQueryParameters(): Generator string $input, array $output, ) => [ - new OpenAPIRequest( - new PathParameterExtractor('/pets'), - V30\PathItem::fromPartial( - new Identifier('test-path'), - [], - new Partial\PathItem(path: '/path', get: $operation), - ), - Method::GET - ), - new ServerRequest('get', '/pets?' . $input), Result::valid([ 'request' => ['method' => 'get', 'operationId' => 'test-op'], 'path' => [], @@ -1510,6 +1457,14 @@ public static function provideAPIWithQueryParameters(): Generator 'cookie' => [], 'body' => '', ]), + new PathParameterExtractor('/pets'), + V30\PathItem::fromPartial( + new Identifier('test-path'), + [], + new Partial\PathItem(path: '/path', get: $operation), + ), + Method::GET, + new ServerRequest('get', '/pets?' . $input), ]; yield 'type:string, style:form, explode:false' => $dataSet( @@ -1756,10 +1711,13 @@ public static function provideAPIWithQueryParameters(): Generator ); } - /** @return Generator */ public static function provideAPIWithHeaderParameters(): Generator @@ -1769,16 +1727,6 @@ public static function provideAPIWithHeaderParameters(): Generator array $requestHeaders, array $resultHeaders ) => [ - new OpenAPIRequest( - new PathParameterExtractor('/path'), - V30\PathItem::fromPartial( - new Identifier('test-path'), - [], - new Partial\PathItem(path: '/path', get: $operation) - ), - Method::GET - ), - new ServerRequest('get', '/path', $requestHeaders), Result::valid([ 'request' => ['method' => 'get', 'operationId' => 'test-op'], 'path' => [], @@ -1787,6 +1735,14 @@ public static function provideAPIWithHeaderParameters(): Generator 'cookie' => [], 'body' => '', ]), + new PathParameterExtractor('/path'), + V30\PathItem::fromPartial( + new Identifier('test-path'), + [], + new Partial\PathItem(path: '/path', get: $operation) + ), + Method::GET, + new ServerRequest('get', '/path', $requestHeaders), ]; yield 'string header (explode:false)' => $dataSet( diff --git a/tests/OpenAPI/Builder/OpenAPIResponseBuilderTest.php b/tests/OpenAPI/Builder/Internal/ResponseTest.php similarity index 57% rename from tests/OpenAPI/Builder/OpenAPIResponseBuilderTest.php rename to tests/OpenAPI/Builder/Internal/ResponseTest.php index 7bbeda30..b5a6328c 100644 --- a/tests/OpenAPI/Builder/OpenAPIResponseBuilderTest.php +++ b/tests/OpenAPI/Builder/Internal/ResponseTest.php @@ -2,26 +2,18 @@ declare(strict_types=1); -namespace Membrane\Tests\OpenAPI\Builder; +namespace Membrane\Tests\OpenAPI\Builder\Internal; use Generator; -use Membrane\Builder\Specification; use Membrane\Filter\String\ToUpperCase; -use Membrane\OpenAPI\Builder\APIBuilder; -use Membrane\OpenAPI\Builder\OpenAPIResponseBuilder; +use Membrane\OpenAPI\Builder\Internal; use Membrane\OpenAPI\Exception\CannotProcessOpenAPI; use Membrane\OpenAPI\Exception\CannotProcessSpecification; use Membrane\OpenAPI\ExtractPathParameters\PathMatcher; -use Membrane\OpenAPI\Specification\APISchema; -use Membrane\OpenAPI\Specification\Arrays; -use Membrane\OpenAPI\Specification\Numeric; -use Membrane\OpenAPI\Specification\Objects; -use Membrane\OpenAPI\Specification\OpenAPIResponse; use Membrane\OpenAPI\Specification\Response; -use Membrane\OpenAPI\Specification\Strings; -use Membrane\OpenAPI\Specification\TrueFalse; use Membrane\OpenAPIReader\MembraneReader; use Membrane\OpenAPIReader\OpenAPIVersion; +use Membrane\OpenAPIReader\ValueObject\Valid\{V30, V31}; use Membrane\Processor; use Membrane\Processor\AllOf; use Membrane\Processor\AnyOf; @@ -60,26 +52,19 @@ use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\TestCase; -#[CoversClass(OpenAPIResponseBuilder::class)] +#[CoversClass(Internal\Response::class)] #[CoversClass(CannotProcessSpecification::class)] #[CoversClass(CannotProcessOpenAPI::class)] -#[CoversClass(APIBuilder::class)] -#[UsesClass(OpenAPIResponse::class)] -#[UsesClass(\Membrane\OpenAPI\Builder\Arrays::class)] -#[UsesClass(\Membrane\OpenAPI\Builder\TrueFalse::class)] -#[UsesClass(\Membrane\OpenAPI\Builder\Numeric::class)] -#[UsesClass(\Membrane\OpenAPI\Builder\Objects::class)] -#[UsesClass(\Membrane\OpenAPI\Builder\Strings::class)] +#[CoversClass(Internal\Schema::class)] +#[UsesClass(Internal\Arrays::class)] +#[UsesClass(Internal\TrueFalse::class)] +#[UsesClass(Internal\Numeric::class)] +#[UsesClass(Internal\Objects::class)] +#[UsesClass(Internal\Strings::class)] #[UsesClass(PathMatcher::class)] #[UsesClass(AllOf::class)] #[UsesClass(AnyOf::class)] #[UsesClass(OneOf::class)] -#[UsesClass(APISchema::class)] -#[UsesClass(Arrays::class)] -#[UsesClass(TrueFalse::class)] -#[UsesClass(Numeric::class)] -#[UsesClass(Objects::class)] -#[UsesClass(Strings::class)] #[UsesClass(Response::class)] #[UsesClass(BeforeSet::class)] #[UsesClass(Collection::class)] @@ -105,47 +90,23 @@ #[UsesClass(IsList::class)] #[UsesClass(IsString::class)] #[UsesClass(\Membrane\Validator\Utility\AnyOf::class)] -class OpenAPIResponseBuilderTest extends TestCase +class ResponseTest extends TestCase { - public const DIR = __DIR__ . '/../../fixtures/OpenAPI/'; + public const DIR = __DIR__ . '/../../../fixtures/OpenAPI/'; #[Test, TestDox('It throws an exception if you try to use the keyword "not"')] public function throwsExceptionIfNotIsFound(): void { - $openApi = (new MembraneReader([ + $openApi = new MembraneReader([ OpenAPIVersion::Version_3_0, - ]))->readFromAbsoluteFilePath(self::DIR . 'noReferences.json'); + ])->readFromAbsoluteFilePath(self::DIR . 'noReferences.json'); $operation = $openApi->paths['/responsepath']->get; - $sut = new OpenAPIResponseBuilder(); - $response = new OpenAPIResponse( - $operation->operationId, - '360', - $operation->responses['360'], - ); - + $sut = new Internal\Response(); self::expectExceptionObject(CannotProcessOpenAPI::unsupportedKeyword('not')); - $sut->build($response); - } - - #[Test, TestDox('It supports the Response Specification')] - public function supportsResponseSpecification(): void - { - $specification = self::createStub(OpenAPIResponse::class); - $sut = new OpenAPIResponseBuilder(); - - self::assertTrue($sut->supports($specification)); - } - - #[Test, TestDox('It does not support any Specifications that are not Response')] - public function doesNotSupportSpecificationsThatAreNotResponse(): void - { - $specification = self::createStub(\Membrane\Builder\Specification::class); - $sut = new OpenAPIResponseBuilder(); - - self::assertFalse($sut->supports($specification)); + $sut->build($operation->responses['360']); } public static function dataSetsforBuilds(): array @@ -159,83 +120,43 @@ public static function dataSetsforBuilds(): array return [ 'no properties' => [ - new OpenAPIResponse( - $noReferences->paths['/path']->get->operationId, - '200', - $noReferences->paths['/path']->get->responses['200'] - ), + $noReferences->paths['/path']->get->responses['200'], new Field('', new Passes()), ], 'int' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '200', - $noReferences->paths['/responsepath']->get->responses['200'] - ), + $noReferences->paths['/responsepath']->get->responses['200'], new Field('', new IsInt()), ], 'nullable int' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '201', - $noReferences->paths['/responsepath']->get->responses['201'] - ), + $noReferences->paths['/responsepath']->get->responses['201'], new AnyOf('', new Field('', new IsInt()), new Field('', new IsNull())), ], 'int, inclusive min' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '202', - $noReferences->paths['/responsepath']->get->responses['202'] - ), + $noReferences->paths['/responsepath']->get->responses['202'], new Field('', new IsInt(), new Minimum(0)), ], 'int, exclusive min' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '203', - $noReferences->paths['/responsepath']->get->responses['203'] - ), + $noReferences->paths['/responsepath']->get->responses['203'], new Field('', new IsInt(), new Minimum(0, true)), ], 'int, inclusive max' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '204', - $noReferences->paths['/responsepath']->get->responses['204'] - ), + $noReferences->paths['/responsepath']->get->responses['204'], new Field('', new IsInt(), new Maximum(100)), ], 'int, exclusive max' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '205', - $noReferences->paths['/responsepath']->get->responses['205'] - ), + $noReferences->paths['/responsepath']->get->responses['205'], new Field('', new IsInt(), new Maximum(100, true)), ], 'int, multipleOf' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '206', - $noReferences->paths['/responsepath']->get->responses['206'] - ), + $noReferences->paths['/responsepath']->get->responses['206'], new Field('', new IsInt(), new MultipleOf(3)), ], 'int, enum' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '207', - $noReferences->paths['/responsepath']->get->responses['207'] - ), + $noReferences->paths['/responsepath']->get->responses['207'], new Field('', new IsInt(), new Contained([1, 2, 3])), ], 'nullable int, enum, exclusive min, inclusive max, multipleOf' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '209', - $noReferences->paths['/responsepath']->get->responses['209'] - ), + $noReferences->paths['/responsepath']->get->responses['209'], new AnyOf( '', new Field( @@ -250,59 +171,31 @@ public static function dataSetsforBuilds(): array ), ], 'number' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '210', - $noReferences->paths['/responsepath']->get->responses['210'] - ), + $noReferences->paths['/responsepath']->get->responses['210'], new Field('', new IsNumber()), ], 'nullable number' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '211', - $noReferences->paths['/responsepath']->get->responses['211'] - ), + $noReferences->paths['/responsepath']->get->responses['211'], new AnyOf('', new Field('', new IsNumber()), new Field('', new IsNull())), ], 'number, enum' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '212', - $noReferences->paths['/responsepath']->get->responses['212'] - ), + $noReferences->paths['/responsepath']->get->responses['212'], new Field('', new IsNumber(), new Contained([1, 2.3, 4])), ], 'number, float format' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '213', - $noReferences->paths['/responsepath']->get->responses['213'] - ), + $noReferences->paths['/responsepath']->get->responses['213'], new Field('', new IsFloat()), ], 'nullable number, float format' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '214', - $noReferences->paths['/responsepath']->get->responses['214'] - ), + $noReferences->paths['/responsepath']->get->responses['214'], new AnyOf('', new Field('', new IsFloat()), new Field('', new IsNull())), ], 'number, double format' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '215', - $noReferences->paths['/responsepath']->get->responses['215'] - ), + $noReferences->paths['/responsepath']->get->responses['215'], new Field('', new IsFloat()), ], 'nullable number, enum, inclusive min, exclusive max, multipleOf' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '219', - $noReferences->paths['/responsepath']->get->responses['219'] - ), + $noReferences->paths['/responsepath']->get->responses['219'], new AnyOf( '', new Field( @@ -317,43 +210,23 @@ public static function dataSetsforBuilds(): array ), ], 'string' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '220', - $noReferences->paths['/responsepath']->get->responses['220'] - ), + $noReferences->paths['/responsepath']->get->responses['220'], new Field('', new IsString()), ], 'nullable string' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '221', - $noReferences->paths['/responsepath']->get->responses['221'] - ), + $noReferences->paths['/responsepath']->get->responses['221'], new AnyOf('', new Field('', new IsString()), new Field('', new IsNull())), ], 'string, enum' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '222', - $noReferences->paths['/responsepath']->get->responses['222'] - ), + $noReferences->paths['/responsepath']->get->responses['222'], new Field('', new IsString(), new Contained(['a', 'b', 'c'])), ], 'string, date format' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '223', - $noReferences->paths['/responsepath']->get->responses['223'] - ), + $noReferences->paths['/responsepath']->get->responses['223'], new Field('', new IsString(), new DateString('Y-m-d', true)), ], 'string, date-time format' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '224', - $noReferences->paths['/responsepath']->get->responses['224'] - ), + $noReferences->paths['/responsepath']->get->responses['224'], new Field( '', new IsString(), @@ -365,35 +238,19 @@ public static function dataSetsforBuilds(): array ), ], 'string, minLength' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '225', - $noReferences->paths['/responsepath']->get->responses['225'] - ), + $noReferences->paths['/responsepath']->get->responses['225'], new Field('', new IsString(), new Length(5)), ], 'string, maxLength' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '226', - $noReferences->paths['/responsepath']->get->responses['226'] - ), + $noReferences->paths['/responsepath']->get->responses['226'], new Field('', new IsString(), new Length(0, 10)), ], 'string, pattern' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '227', - $noReferences->paths['/responsepath']->get->responses['227'] - ), + $noReferences->paths['/responsepath']->get->responses['227'], new Field('', new IsString(), new Regex('#[A-Za-z]+#u')), ], 'nullable string, enum, minLength, maxLength, pattern' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '229', - $noReferences->paths['/responsepath']->get->responses['229'] - ), + $noReferences->paths['/responsepath']->get->responses['229'], new AnyOf( '', new Field( @@ -407,35 +264,19 @@ public static function dataSetsforBuilds(): array ), ], 'bool' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '230', - $noReferences->paths['/responsepath']->get->responses['230'] - ), + $noReferences->paths['/responsepath']->get->responses['230'], new Field('', new IsBool()), ], 'nullable bool' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '231', - $noReferences->paths['/responsepath']->get->responses['231'] - ), + $noReferences->paths['/responsepath']->get->responses['231'], new AnyOf('', new Field('', new IsBool()), new Field('', new IsNull())), ], 'bool, enum' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '232', - $noReferences->paths['/responsepath']->get->responses['232'] - ), + $noReferences->paths['/responsepath']->get->responses['232'], new Field('', new IsBool(), new Contained([true])), ], 'nullable bool, enum' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '239', - $noReferences->paths['/responsepath']->get->responses['239'] - ), + $noReferences->paths['/responsepath']->get->responses['239'], new AnyOf( '', new Field('', new IsBool(), new Contained([true, null])), @@ -443,19 +284,11 @@ public static function dataSetsforBuilds(): array ), ], 'array of ints' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '240', - $noReferences->paths['/responsepath']->get->responses['240'] - ), + $noReferences->paths['/responsepath']->get->responses['240'], new Collection('', new BeforeSet(new IsList()), new Field('', new IsInt())), ], 'array of strings, enum' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '241', - $noReferences->paths['/responsepath']->get->responses['241'] - ), + $noReferences->paths['/responsepath']->get->responses['241'], new Collection( '', new BeforeSet(new IsList(), new Contained([['a', 'b', 'c'], ['d', 'e', 'f']])), @@ -463,11 +296,7 @@ public static function dataSetsforBuilds(): array ), ], 'nullable array of strings' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '242', - $noReferences->paths['/responsepath']->get->responses['242'] - ), + $noReferences->paths['/responsepath']->get->responses['242'], new AnyOf( '', new Collection('', new BeforeSet(new IsList()), new Field('', new IsString())), @@ -475,35 +304,19 @@ public static function dataSetsforBuilds(): array ), ], 'array of booleans, minItems' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '243', - $noReferences->paths['/responsepath']->get->responses['243'] - ), + $noReferences->paths['/responsepath']->get->responses['243'], new Collection('', new BeforeSet(new IsList(), new Count(5)), new Field('', new IsBool())), ], 'array of floats, maxItems' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '244', - $noReferences->paths['/responsepath']->get->responses['244'] - ), + $noReferences->paths['/responsepath']->get->responses['244'], new Collection('', new BeforeSet(new IsList(), new Count(0, 5)), new Field('', new IsFloat())), ], 'array of numbers, uniqueItems' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '245', - $noReferences->paths['/responsepath']->get->responses['245'] - ), + $noReferences->paths['/responsepath']->get->responses['245'], new Collection('', new BeforeSet(new IsList(), new Unique()), new Field('', new IsNumber())), ], 'nullable array of nullable numbers, enum, minItems, maxItems, uniqueItems' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '269', - $noReferences->paths['/responsepath']->get->responses['269'] - ), + $noReferences->paths['/responsepath']->get->responses['269'], new AnyOf( '', new Collection( @@ -520,11 +333,7 @@ public static function dataSetsforBuilds(): array ), ], 'object with (string) name' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '270', - $noReferences->paths['/responsepath']->get->responses['270'] - ), + $noReferences->paths['/responsepath']->get->responses['270'], new FieldSet( '', new BeforeSet(new IsArray()), @@ -532,11 +341,7 @@ public static function dataSetsforBuilds(): array ), ], 'object with (int) id, enum' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '271', - $noReferences->paths['/responsepath']->get->responses['271'] - ), + $noReferences->paths['/responsepath']->get->responses['271'], new FieldSet( '', new BeforeSet(new IsArray(), new Contained([['id' => 5], ['id' => 10]])), @@ -544,11 +349,7 @@ public static function dataSetsforBuilds(): array ), ], 'nullable object with (float) price' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '272', - $noReferences->paths['/responsepath']->get->responses['272'] - ), + $noReferences->paths['/responsepath']->get->responses['272'], new AnyOf( '', new FieldSet('', new BeforeSet(new IsArray()), new Field('price', new IsFloat())), @@ -556,11 +357,7 @@ public static function dataSetsforBuilds(): array ), ], 'object with (string) name, (int) id, (bool) status' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '273', - $noReferences->paths['/responsepath']->get->responses['273'] - ), + $noReferences->paths['/responsepath']->get->responses['273'], new FieldSet( '', new BeforeSet(new IsArray()), @@ -570,11 +367,7 @@ public static function dataSetsforBuilds(): array ), ], 'object with (string) name, (int) id, (bool) status, required' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '274', - $noReferences->paths['/responsepath']->get->responses['274'] - ), + $noReferences->paths['/responsepath']->get->responses['274'], new FieldSet( '', new BeforeSet(new IsArray(), new RequiredFields('name', 'id')), @@ -584,11 +377,7 @@ public static function dataSetsforBuilds(): array ), ], 'nullable object with (string) name, (int) id, (bool) status, enum, required' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '299', - $noReferences->paths['/responsepath']->get->responses['299'] - ), + $noReferences->paths['/responsepath']->get->responses['299'], new FieldSet( '', new BeforeSet( @@ -607,19 +396,11 @@ public static function dataSetsforBuilds(): array ), ], 'allOf, one object (should act like normal object)' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '300', - $noReferences->paths['/responsepath']->get->responses['300'] - ), + $noReferences->paths['/responsepath']->get->responses['300'], new FieldSet('', new Field('name', new IsString()), new BeforeSet(new IsArray())), ], 'allOf, two objects, one identical parameter' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '301', - $noReferences->paths['/responsepath']->get->responses['301'] - ), + $noReferences->paths['/responsepath']->get->responses['301'], new AllOf( '', new FieldSet('Branch-1', new Field('id', new IsInt()), new BeforeSet(new IsArray())), @@ -627,11 +408,7 @@ public static function dataSetsforBuilds(): array ), ], 'allOf, two objects, one unique parameters' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '302', - $noReferences->paths['/responsepath']->get->responses['302'] - ), + $noReferences->paths['/responsepath']->get->responses['302'], new AllOf( '', new FieldSet('Branch-1', new Field('id', new IsInt()), new BeforeSet(new IsArray())), @@ -639,11 +416,7 @@ public static function dataSetsforBuilds(): array ), ], 'allOf, two objects, conflicting parameter' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '303', - $noReferences->paths['/responsepath']->get->responses['303'] - ), + $noReferences->paths['/responsepath']->get->responses['303'], new AllOf( '', new FieldSet('Branch-1', new Field('id', new IsInt()), new BeforeSet(new IsArray())), @@ -651,11 +424,7 @@ public static function dataSetsforBuilds(): array ), ], 'allOf, two objects, unique parameters, one requiredField' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '304', - $noReferences->paths['/responsepath']->get->responses['304'] - ), + $noReferences->paths['/responsepath']->get->responses['304'], new AllOf( '', new FieldSet('Branch-1', new Field('id', new IsInt()), new BeforeSet(new IsArray())), @@ -667,11 +436,7 @@ public static function dataSetsforBuilds(): array ), ], 'allOf, two objects, unique parameters, two requiredField' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '305', - $noReferences->paths['/responsepath']->get->responses['305'] - ), + $noReferences->paths['/responsepath']->get->responses['305'], new AllOf( '', new FieldSet( @@ -687,11 +452,7 @@ public static function dataSetsforBuilds(): array ), ], 'allOf, two objects, unique parameters, two requiredFields requiring the other schemas property' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '306', - $noReferences->paths['/responsepath']->get->responses['306'] - ), + $noReferences->paths['/responsepath']->get->responses['306'], new AllOf( '', new FieldSet( @@ -707,19 +468,11 @@ public static function dataSetsforBuilds(): array ), ], 'anyOf, one object (should act like normal object)' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '320', - $noReferences->paths['/responsepath']->get->responses['320'] - ), + $noReferences->paths['/responsepath']->get->responses['320'], new FieldSet('', new Field('name', new IsString()), new BeforeSet(new IsArray())), ], 'anyOf, two objects, one identical parameter' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '321', - $noReferences->paths['/responsepath']->get->responses['321'] - ), + $noReferences->paths['/responsepath']->get->responses['321'], new AnyOf( '', new FieldSet('Branch-1', new Field('id', new IsInt()), new BeforeSet(new IsArray())), @@ -727,11 +480,7 @@ public static function dataSetsforBuilds(): array ), ], 'anyOf, two objects, one unique parameters' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '322', - $noReferences->paths['/responsepath']->get->responses['322'] - ), + $noReferences->paths['/responsepath']->get->responses['322'], new AnyOf( '', new FieldSet('Branch-1', new Field('id', new IsInt()), new BeforeSet(new IsArray())), @@ -739,11 +488,7 @@ public static function dataSetsforBuilds(): array ), ], 'anyOf, two objects, conflicting parameter' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '323', - $noReferences->paths['/responsepath']->get->responses['323'] - ), + $noReferences->paths['/responsepath']->get->responses['323'], new AnyOf( '', new FieldSet('Branch-1', new Field('id', new IsInt()), new BeforeSet(new IsArray())), @@ -751,11 +496,7 @@ public static function dataSetsforBuilds(): array ), ], 'anyOf, two objects, unique parameters, one requiredField' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '324', - $noReferences->paths['/responsepath']->get->responses['324'] - ), + $noReferences->paths['/responsepath']->get->responses['324'], new AnyOf( '', new FieldSet('Branch-1', new Field('id', new IsInt()), new BeforeSet(new IsArray())), @@ -767,11 +508,7 @@ public static function dataSetsforBuilds(): array ), ], 'anyOf, two objects, unique parameters, two requiredField' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '325', - $noReferences->paths['/responsepath']->get->responses['325'] - ), + $noReferences->paths['/responsepath']->get->responses['325'], new AnyOf( '', new FieldSet( @@ -787,11 +524,7 @@ public static function dataSetsforBuilds(): array ), ], 'anyOf, two objects, unique parameters, two requiredFields requiring the other schemas property' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '326', - $noReferences->paths['/responsepath']->get->responses['326'] - ), + $noReferences->paths['/responsepath']->get->responses['326'], new AnyOf( '', new FieldSet( @@ -807,19 +540,11 @@ public static function dataSetsforBuilds(): array ), ], 'oneOf, one object (should act like normal object)' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '340', - $noReferences->paths['/responsepath']->get->responses['340'] - ), + $noReferences->paths['/responsepath']->get->responses['340'], new FieldSet('', new Field('name', new IsString()), new BeforeSet(new IsArray())), ], 'oneOf, two objects, one identical parameter' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '341', - $noReferences->paths['/responsepath']->get->responses['341'] - ), + $noReferences->paths['/responsepath']->get->responses['341'], new OneOf( '', new FieldSet('Branch-1', new Field('id', new IsInt()), new BeforeSet(new IsArray())), @@ -827,11 +552,7 @@ public static function dataSetsforBuilds(): array ), ], 'oneOf, two objects, one unique parameters' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '342', - $noReferences->paths['/responsepath']->get->responses['342'] - ), + $noReferences->paths['/responsepath']->get->responses['342'], new OneOf( '', new FieldSet('Branch-1', new Field('id', new IsInt()), new BeforeSet(new IsArray())), @@ -839,11 +560,7 @@ public static function dataSetsforBuilds(): array ), ], 'oneOf, two objects, conflicting parameter' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '343', - $noReferences->paths['/responsepath']->get->responses['343'] - ), + $noReferences->paths['/responsepath']->get->responses['343'], new OneOf( '', new FieldSet('Branch-1', new Field('id', new IsInt()), new BeforeSet(new IsArray())), @@ -851,11 +568,7 @@ public static function dataSetsforBuilds(): array ), ], 'oneOf, two objects, unique parameters, one requiredField' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '344', - $noReferences->paths['/responsepath']->get->responses['344'] - ), + $noReferences->paths['/responsepath']->get->responses['344'], new OneOf( '', new FieldSet('Branch-1', new Field('id', new IsInt()), new BeforeSet(new IsArray())), @@ -867,11 +580,7 @@ public static function dataSetsforBuilds(): array ), ], 'oneOf, two objects, unique parameters, two requiredField' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '345', - $noReferences->paths['/responsepath']->get->responses['345'] - ), + $noReferences->paths['/responsepath']->get->responses['345'], new OneOf( '', new FieldSet( @@ -887,11 +596,7 @@ public static function dataSetsforBuilds(): array ), ], 'oneOf, two objects, unique parameters, two requiredFields requiring the other schemas property' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '346', - $noReferences->paths['/responsepath']->get->responses['346'] - ), + $noReferences->paths['/responsepath']->get->responses['346'], new OneOf( '', new FieldSet( @@ -907,35 +612,19 @@ public static function dataSetsforBuilds(): array ), ], 'schema with no specified type' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '404', - $noReferences->paths['/responsepath']->get->responses['404'] - ), + $noReferences->paths['/responsepath']->get->responses['404'], new Field('', new Passes()), ], 'schema with empty content' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '405', - $noReferences->paths['/responsepath']->get->responses['405'] - ), + $noReferences->paths['/responsepath']->get->responses['405'], new Field('', new Passes()), ], 'schema with no content' => [ - new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '406', - $noReferences->paths['/responsepath']->get->responses['406'] - ), + $noReferences->paths['/responsepath']->get->responses['406'], new Field('', new Passes()), ], 'petstore.yaml: /pets path -> get operation -> 200 response' => [ - new OpenAPIResponse( - $petstore->paths['/pets']->get->operationId, - '200', - $petstore->paths['/pets']->get->responses['200'] - ), + $petstore->paths['/pets']->get->responses['200'], new Collection( '', new BeforeSet(new IsList(), new Count(0, 100)), @@ -953,25 +642,19 @@ public static function dataSetsforBuilds(): array #[Test, TestDox('It builds processors that can validate data matches response content')] #[DataProvider('dataSetsforBuilds')] - public function buildsTest(Specification $spec, Processor $expected): void - { - $sut = new OpenAPIResponseBuilder(); - - $processor = $sut->build($spec); - - self::assertEquals($expected, $processor); + public function buildsTest( + V30\Response | V31\Response $response, + Processor $expected, + ): void { + self::assertEquals($expected, new Internal\Response()->build($response)); } public static function dataSetsForDocExamples(): array { - $petstore = (new MembraneReader([OpenAPIVersion::Version_3_0])) + $petstore = new MembraneReader([OpenAPIVersion::Version_3_0]) ->readFromAbsoluteFilePath(self::DIR . 'docs/petstore.yaml'); - $petsGet200Response = new OpenAPIResponse( - $petstore->paths['/pets']->get->operationId, - '200', - $petstore->paths['/pets']->get->responses['200'] - ); + $petsGet200Response = $petstore->paths['/pets']->get->responses['200']; return [ 'dataSet A' => [ @@ -1028,32 +711,29 @@ public static function dataSetsForDocExamples(): array #[DataProvider('dataSetsForDocExamples')] #[Test] - public function docsTest(Specification $spec, array $data, Result $expected): void - { - $sut = new OpenAPIResponseBuilder(); - - $processor = $sut->build($spec); + public function docsTest( + V30\Response | V31\Response $response, + array $data, + Result $expected, + ): void { + $processor = new Internal\Response()->build($response); self::assertEquals($expected, $processor->process(new FieldName(''), $data)); } #[Test] #[DataProvider('provideDateStrings')] - public function itValidatesDateTime(Result $expected, string $dateTime): void + public function itValidatesDateTime( + Result $expected, + string $dateTime, + ): void { - $noReferences = (new MembraneReader([ + $noReferences = new MembraneReader([ OpenAPIVersion::Version_3_0, - ]))->readFromAbsoluteFilePath(self::DIR . 'noReferences.json'); - - $specification = new OpenAPIResponse( - $noReferences->paths['/responsepath']->get->operationId, - '224', - $noReferences->paths['/responsepath']->get->responses['224'] - ); - - $sut = new OpenAPIResponseBuilder(); + ])->readFromAbsoluteFilePath(self::DIR . 'noReferences.json'); - $processor = $sut->build($specification); + $processor = new Internal\Response() + ->build($noReferences->paths['/responsepath']->get->responses['224']); self::assertEquals($expected, $processor->process(new FieldName(''), $dateTime)); } diff --git a/tests/OpenAPI/Builder/Internal/StringsTest.php b/tests/OpenAPI/Builder/Internal/StringsTest.php new file mode 100644 index 00000000..9baa1164 --- /dev/null +++ b/tests/OpenAPI/Builder/Internal/StringsTest.php @@ -0,0 +1,121 @@ + [ + new Field('mvp', new IsString()), + 'mvp', + new V30\Schema( + new Identifier('test'), + new Partial\Schema(type: 'string'), + )->value, + ], + 'date' => [ + new Field( + 'date', + new IsString(), + new DateString('Y-m-d', true), + ), + 'date', + new V30\Schema( + new Identifier(''), + new Partial\Schema(type: 'string', format: 'date') + )->value, + ], + 'date-time' => [ + new Field( + 'date-time', + new IsString(), + new ToUpperCase(), + new \Membrane\Validator\Utility\AnyOf( + new DateString('Y-m-d\TH:i:sP', true), + new DateString('Y-m-d\TH:i:sp', true), + ), + ), + 'date-time', + new V30\Schema( + new Identifier(''), + new Partial\Schema(type: 'string', format: 'date-time'), + )->value, + ], + 'detailed input' => [ + new Field( + 'max', + new IsString(), + new Contained(['1970/01/01', null]), + new DateString('Y-m-d', true), + new Length(0, 100), + new Regex('#.+#u'), + ), + 'max', + new V30\Schema( + new Identifier(''), + new Partial\Schema( + type: 'string', + enum: [new Value('1970/01/01'), new Value(null)], + maxLength: 100, + minLength: 0, + pattern: '.+', + format: 'date', + ), + )->value, + ], + ]; + } + + #[DataProvider('specificationsToBuild')] + #[Test] + public function buildTest( + Processor $expected, + string $fieldName, + V30\Keywords | V31\Keywords $keywords, + bool $convertFromArray = false, + ?string $style = null, + ): void { + self::assertEquals( + $expected, + new Strings()->build( + $fieldName, + $keywords, + $convertFromArray, + $style, + ), + ); + } +} diff --git a/tests/OpenAPI/Builder/Internal/TrueFalseTest.php b/tests/OpenAPI/Builder/Internal/TrueFalseTest.php new file mode 100644 index 00000000..8829265a --- /dev/null +++ b/tests/OpenAPI/Builder/Internal/TrueFalseTest.php @@ -0,0 +1,99 @@ + [ + new Field('mvp', new IsBool()), + 'mvp', + new V30\Schema( + new Identifier('test'), + new Partial\Schema(type: 'boolean') + )->value, + ], + 'MVP from string' => [ + new Field('mvp-from-string', new BoolString(), new ToBool()), + 'mvp-from-string', + new V30\Schema( + new Identifier('test'), + new Partial\Schema(type: 'boolean') + )->value, + true, + ], + 'max' => [ + new Field('max', new IsBool(), new Contained([true, null])), + 'max', + new V30\Schema( + new Identifier('test'), + new Partial\Schema( + type: 'boolean', + enum: [new Value(true), new Value(null)], + ) + )->value, + ], + 'max from string' => [ + new Field('max-from-string', new BoolString(), new ToBool(), new Contained([true, null])), + 'max-from-string', + new V30\Schema( + new Identifier('test'), + new Partial\Schema( + type: 'boolean', + enum: [new Value(true), new Value(null)], + ), + )->value, + true, + ], + ]; + } + + #[Test] + #[DataProvider('specificationsToBuild')] + public function buildTest( + Processor $expected, + string $fieldName, + V30\Keywords | V31\Keywords $keywords, + bool $convertFromString = false, + bool $convertFromArray = false, + ?string $style = null, + ): void { + self::assertEquals( + $expected, + new TrueFalse()->build( + $fieldName, + $keywords, + $convertFromString, + $convertFromArray, + $style, + ), + ); + } +} diff --git a/tests/OpenAPI/Builder/NumericTest.php b/tests/OpenAPI/Builder/NumericTest.php deleted file mode 100644 index 89e75913..00000000 --- a/tests/OpenAPI/Builder/NumericTest.php +++ /dev/null @@ -1,175 +0,0 @@ -supports($specification)); - } - - #[Test] - public function doesNotSupportSpecificationsOtherThanNumeric(): void - { - $specification = self::createStub(\Membrane\Builder\Specification::class); - $sut = new Numeric(); - - self::assertFalse($sut->supports($specification)); - } - - public static function specificationsToBuild(): array - { - return [ - 'integer input to convert from string' => [ - new Specification\Numeric( - '', - (new V30\Schema(new Identifier(''), new Partial\Schema(type: 'integer')))->value, - true - ), - new Field('', new IntString(), new ToInt()), - ], - 'strict integer input' => [ - new Specification\Numeric( - '', - (new V30\Schema(new Identifier(''), new Partial\Schema(type: 'integer')))->value, - false, - ), - new Field('', new IsInt()), - ], - 'number input to convert from string' => [ - new Specification\Numeric( - '', - (new V30\Schema(new Identifier(''), new Partial\Schema(type: 'number')))->value, - true, - ), - new Field('', new NumericString(), new ToNumber()), - ], - 'strict number input' => [ - new Specification\Numeric( - '', - (new V30\Schema(new Identifier(''), new Partial\Schema(type: 'number')))->value, - false, - ), - new Field('', new IsNumber()), - ], - 'float input to convert from string' => [ - new Specification\Numeric( - '', - (new V30\Schema(new Identifier(''), new Partial\Schema(type: 'number', format: 'float')))->value, - true, - ), - new Field('', new NumericString(), new ToFloat()), - ], - 'strict float input' => [ - new Specification\Numeric( - '', - (new V30\Schema(new Identifier(''), new Partial\Schema(type: 'number', format: 'float')))->value, - false, - ), - new Field('', new IsFloat()), - ], - 'detailed input to convert from string' => [ - new Specification\Numeric( - '', - (new V30\Schema(new Identifier(''), new Partial\Schema( - type: 'integer', - enum: [new Value(1), new Value(2), new Value(3), new Value(null)], - multipleOf: 3, - exclusiveMaximum: true, - exclusiveMinimum: true, - maximum: 4, - minimum: 0, - format: 'int', - )))->value, - true - ), - new Field( - '', - new IntString(), - new ToInt(), - new Contained([1, 2, 3, null]), - new Maximum(4, true), - new Minimum(0, true), - new MultipleOf(3) - ) - ], - 'strict detailed input' => [ - new Specification\Numeric( - '', - (new V30\Schema(new Identifier(''), new Partial\Schema( - type: 'integer', - enum: [new Value(1), new Value(2), new Value(3), new Value(null)], - multipleOf: 3, - exclusiveMaximum: true, - exclusiveMinimum: true, - maximum: 4, - minimum: 0, - format: 'int', - )))->value, - false - ), - new Field( - '', - new IsInt(), - new Contained([1, 2, 3, null]), - new Maximum(4, true), - new Minimum(0, true), - new MultipleOf(3) - ) - ], - ]; - } - - #[DataProvider('specificationsToBuild')] - #[Test] - public function buildTest(Specification\Numeric $specification, Processor $expected): void - { - $sut = new Numeric(); - - $actual = $sut->build($specification); - - self::assertEquals($expected, $actual); - } -} diff --git a/tests/OpenAPI/Builder/ObjectsTest.php b/tests/OpenAPI/Builder/ObjectsTest.php deleted file mode 100644 index a3fe8f7a..00000000 --- a/tests/OpenAPI/Builder/ObjectsTest.php +++ /dev/null @@ -1,242 +0,0 @@ -supports($specification)); - } - - #[Test] - public function doesNotSupportSpecificationsThatAreNotArrays(): void - { - $specification = self::createStub(\Membrane\Builder\Specification::class); - $sut = new Objects(); - - self::assertFalse($sut->supports($specification)); - } - - public static function specificationsToBuild(): array - { - return [ - '3.0 minimum input' => [ - new Specification\Objects( - '', - (new V30\Schema(new Identifier(''), new Partial\Schema(type: 'object')))->value, - ), - new FieldSet('', new BeforeSet(new IsArray())), - ], - '3.0 minProperties greater than zero' => [ - new Specification\Objects( - '', - (new V30\Schema(new Identifier(''), new Partial\Schema(type: 'object', minProperties: 1)))->value, - ), - new FieldSet('', new BeforeSet(new IsArray(), new Count(1))), - ], - '3.0 maxProperties' => [ - new Specification\Objects( - '', - (new V30\Schema(new Identifier(''), new Partial\Schema(type: 'object', maxProperties: 1)))->value, - ), - new FieldSet('', new BeforeSet(new IsArray(), new Count(0, 1))), - ], - '3.0 minProperties and maxProperties' => [ - new Specification\Objects( - '', - (new V30\Schema( - new Identifier(''), new Partial\Schema( - type: 'object', - maxProperties: 1, - minProperties: 1, - ) - ))->value, - ), - new FieldSet('', new BeforeSet(new IsArray(), new Count(1, 1))), - ], - '3.0 integer property' => [ - new Specification\Objects( - '', - (new V30\Schema( - new Identifier(''), new Partial\Schema( - type: 'object', - properties: ['a' => new Partial\Schema(type: 'integer')], - ) - ))->value, - ), - new FieldSet('', new BeforeSet(new IsArray()), new Field('a', new IsInt())), - ], - '3.0 additionalProperties:false' => [ - new Specification\Objects( - '', - (new V30\Schema( - new Identifier(''), new Partial\Schema( - type: 'object', - properties: ['a' => new Partial\Schema(type: 'integer')], - additionalProperties: false, - ) - ))->value, - ), - new FieldSet('', new BeforeSet(new IsArray(), new FixedFields('a')), new Field('a', new IsInt())), - ], - '3.0 property of string|integer' => [ - new Specification\Objects( - '', - (new V30\Schema( - new Identifier(''), new Partial\Schema( - type: 'object', - properties: ['a' => new Partial\Schema(anyOf: [ - new Partial\Schema(type: 'string'), - new Partial\Schema(type: 'integer'), - ])], - ) - ))->value, - ), - new FieldSet( - '', - new BeforeSet(new IsArray()), - new AnyOf('a', new Field('Branch-1', new IsString()), new Field('Branch-2', new IsInt())), - ), - ], - '3.1 property of string|integer' => [ - new Specification\Objects( - '', - (new V31\Schema( - new Identifier(''), new Partial\Schema( - type: 'object', - properties: ['a' => new Partial\Schema(type: ['string', 'integer'])], - ) - ))->value, - ), - new FieldSet( - '', - new BeforeSet(new IsArray()), - new AnyOf('a', new Field('a', new IsString()), new Field('a', new IsInt())), - ), - ], - 'complex additional properties' => [ - new Specification\Objects( - '', - (new V30\Schema( - new Identifier(''), new Partial\Schema( - type: 'object', - maxProperties: 5, - minProperties: 2, - additionalProperties: new Partial\Schema(oneOf: [ - new Partial\Schema(type: 'boolean'), - new Partial\Schema(type: 'integer'), - ]), - ) - ))->value, - ), - new FieldSet( - '', - new BeforeSet(new IsArray(), new Count(2, 5)), - new DefaultProcessor( - new OneOf( - '', - new Field('Branch-1', new IsBool()), - new Field('Branch-2', new IsInt()), - ) - ) - ), - ], - 'detailed input' => [ - new Specification\Objects( - '', - (new V30\Schema( - new Identifier(''), new Partial\Schema( - type: 'object', - enum: [new Value(['id' => 5, 'name' => 'Blink']), new Value(null)], - required: ['id', 'name'], - properties: [ - 'id' => new Partial\Schema(type: 'integer'), - 'name' => new Partial\Schema(type: 'string'), - ], - additionalProperties: new Partial\Schema(type: 'string'), - format: 'pet', - ) - ))->value, - ), - new FieldSet( - '', - new BeforeSet( - new IsArray(), - new Contained([['id' => 5, 'name' => 'Blink'], null]), - new RequiredFields('id', 'name') - ), - DefaultProcessor::fromFiltersAndValidators(new IsString()), - new Field('id', new IsInt()), - new Field('name', new IsString()) - ) - ], - ]; - } - - #[Test] - #[DataProvider('specificationsToBuild')] - public function buildTest(Specification\Objects $specification, Processor $expected): void - { - $sut = new Objects(); - - $actual = $sut->build($specification); - - self::assertEquals($expected, $actual); - } -} diff --git a/tests/OpenAPI/Builder/ParameterBuilderTest.php b/tests/OpenAPI/Builder/ParameterBuilderTest.php deleted file mode 100644 index 54299f14..00000000 --- a/tests/OpenAPI/Builder/ParameterBuilderTest.php +++ /dev/null @@ -1,104 +0,0 @@ -sut = new OpenAPIBuilder\ParameterBuilder(); - } - - #[Test, TestDox('It does not support any Specifications other than Parameter')] - public function doesNotSupportSpecificationsOtherThanParameter(): void - { - self::assertFalse($this->sut->supports(self::createStub(Specification::class))); - } - - #[Test, TestDox('It supports the Parameter Specification')] - public function supportsTheParameterSpecification(): void - { - self::assertTrue($this->sut->supports(self::createStub(OpenAPISpecification\Parameter::class))); - } - - public static function provideParameterSpecificationsToBuildFrom(): array - { - return [ - [ - new V30\Parameter(new Identifier('test'), new Partial\Parameter( - name: 'id', - in: 'path', - required: true, - schema: new Partial\Schema(type: 'integer'), - )), - new Processor\Field('id', new IsInt()) - ], - [ - new V30\Parameter(new Identifier('test'), new Partial\Parameter( - name: 'tags', - in: 'query', - style: 'spaceDelimited', - explode: false, - schema: new Partial\Schema( - type: 'array', - items: new Partial\Schema(type: 'string'), - ), - )), - new Processor\Collection( - 'tags', - new Processor\BeforeSet(new SpaceDelimited(), new IsList()), - new Processor\Field('', new IsString()) - ), - ], - ]; - } - - #[Test, TestDox('It Builds a Processor that can validate against the Parameter Specification')] - #[DataProvider('provideParameterSpecificationsToBuildFrom')] - public function itBuildsProcessorsForParameters( - V30\Parameter|V31\Parameter $parameter, - Processor $expectedProcessor - ): void { - $actualProcessor = $this->sut - ->build(new OpenAPISpecification\Parameter($parameter)); - - self::assertEquals($expectedProcessor, $actualProcessor); - } -} diff --git a/tests/OpenAPI/Builder/RequestBuilderTest.php b/tests/OpenAPI/Builder/RequestBuilderTest.php index 0586d942..1dd9369b 100644 --- a/tests/OpenAPI/Builder/RequestBuilderTest.php +++ b/tests/OpenAPI/Builder/RequestBuilderTest.php @@ -9,13 +9,8 @@ use Membrane\Filter\String\Explode; use Membrane\Filter\String\Implode; use Membrane\Filter\Type\ToInt; -use Membrane\OpenAPI\Builder\APIBuilder; -use Membrane\OpenAPI\Builder\Arrays; -use Membrane\OpenAPI\Builder\Numeric; -use Membrane\OpenAPI\Builder\OpenAPIRequestBuilder; -use Membrane\OpenAPI\Builder\ParameterBuilder; +use Membrane\OpenAPI\Builder\Internal; use Membrane\OpenAPI\Builder\RequestBuilder; -use Membrane\OpenAPI\Builder\Strings; use Membrane\OpenAPI\ContentType; use Membrane\OpenAPI\Exception\CannotProcessOpenAPI; use Membrane\OpenAPI\Exception\CannotProcessSpecification; @@ -24,9 +19,6 @@ use Membrane\OpenAPI\Filter\PathMatcher; use Membrane\OpenAPI\Filter\QueryStringToArray; use Membrane\OpenAPI\Processor\Request as RequestProcessor; -use Membrane\OpenAPI\Specification\APISchema; -use Membrane\OpenAPI\Specification\OpenAPIRequest; -use Membrane\OpenAPI\Specification\Parameter; use Membrane\OpenAPI\Specification\Request; use Membrane\OpenAPIReader\OpenAPIVersion; use Membrane\OpenAPIReader\Reader; @@ -61,24 +53,17 @@ #[CoversClass(CannotProcessSpecification::class)] #[CoversClass(CannotProcessOpenAPI::class)] #[UsesClass(HumanReadable::class)] -#[UsesClass(APIBuilder::class)] -#[UsesClass(OpenAPIRequestBuilder::class)] -#[UsesClass(OpenAPIRequest::class)] +#[UsesClass(Internal\Schema::class)] +#[UsesClass(Internal\Request::class)] +#[UsesClass(Internal\Arrays::class)] +#[UsesClass(Internal\Numeric::class)] +#[UsesClass(Internal\Strings::class)] #[UsesClass(Request::class)] -#[UsesClass(Arrays::class)] -#[UsesClass(Numeric::class)] -#[UsesClass(Strings::class)] -#[UsesClass(Parameter::class)] -#[UsesClass(ParameterBuilder::class)] #[UsesClass(QueryStringToArray::class)] #[UsesClass(Form::class)] #[UsesClass(PathMatcher::class)] #[UsesClass(PathMatcherClass::class)] #[UsesClass(RequestProcessor::class)] -#[UsesClass(APISchema::class)] -#[UsesClass(\Membrane\OpenAPI\Specification\Arrays::class)] -#[UsesClass(\Membrane\OpenAPI\Specification\Numeric::class)] -#[UsesClass(\Membrane\OpenAPI\Specification\Strings::class)] #[UsesClass(ToInt::class)] #[UsesClass(Explode::class)] #[UsesClass(Implode::class)] @@ -109,7 +94,7 @@ public function throwsExceptionIfParameterHasContentThatIsNotJson(): void $specification = new Request($openAPIFilePath, '/requestpathexceptions', Method::POST); $sut = new RequestBuilder(); - $openApi = (new Reader([OpenAPIVersion::Version_3_0])) + $openApi = new Reader([OpenAPIVersion::Version_3_0]) ->readFromAbsoluteFilePath($openAPIFilePath); $mediaTypes = array_keys($openApi->paths->getPath('/requestpathexceptions')->post->parameters[0]->content); diff --git a/tests/OpenAPI/Builder/ResponseBuilderTest.php b/tests/OpenAPI/Builder/ResponseBuilderTest.php index dbbafd68..50e74db2 100644 --- a/tests/OpenAPI/Builder/ResponseBuilderTest.php +++ b/tests/OpenAPI/Builder/ResponseBuilderTest.php @@ -6,21 +6,14 @@ use Membrane\Builder\Specification; use Membrane\Filter\String\ToUpperCase; -use Membrane\OpenAPI\Builder\APIBuilder; -use Membrane\OpenAPI\Builder\OpenAPIResponseBuilder; +use Membrane\OpenAPI\Builder\Internal; +use Membrane\OpenAPI\Builder\Internal\Schema; use Membrane\OpenAPI\Builder\ResponseBuilder; use Membrane\OpenAPI\Exception\CannotProcessOpenAPI; use Membrane\OpenAPI\Exception\CannotProcessResponse; use Membrane\OpenAPI\Exception\CannotProcessSpecification; use Membrane\OpenAPI\ExtractPathParameters\PathMatcher; -use Membrane\OpenAPI\Specification\APISchema; -use Membrane\OpenAPI\Specification\Arrays; -use Membrane\OpenAPI\Specification\Numeric; -use Membrane\OpenAPI\Specification\Objects; -use Membrane\OpenAPI\Specification\OpenAPIResponse; use Membrane\OpenAPI\Specification\Response; -use Membrane\OpenAPI\Specification\Strings; -use Membrane\OpenAPI\Specification\TrueFalse; use Membrane\OpenAPIReader\ValueObject\Valid\Enum\Method; use Membrane\Processor; use Membrane\Processor\AllOf; @@ -64,24 +57,17 @@ #[CoversClass(CannotProcessResponse::class)] #[CoversClass(CannotProcessSpecification::class)] #[CoversClass(CannotProcessOpenAPI::class)] -#[UsesClass(APIBuilder::class)] -#[UsesClass(OpenAPIResponseBuilder::class)] -#[UsesClass(OpenAPIResponse::class)] -#[UsesClass(\Membrane\OpenAPI\Builder\Arrays::class)] -#[UsesClass(\Membrane\OpenAPI\Builder\TrueFalse::class)] -#[UsesClass(\Membrane\OpenAPI\Builder\Numeric::class)] -#[UsesClass(\Membrane\OpenAPI\Builder\Objects::class)] -#[UsesClass(\Membrane\OpenAPI\Builder\Strings::class)] +#[UsesClass(Internal\Schema::class)] +#[UsesClass(Internal\Response::class)] +#[UsesClass(\Membrane\OpenAPI\Builder\Internal\Arrays::class)] +#[UsesClass(\Membrane\OpenAPI\Builder\Internal\TrueFalse::class)] +#[UsesClass(\Membrane\OpenAPI\Builder\Internal\Numeric::class)] +#[UsesClass(\Membrane\OpenAPI\Builder\Internal\Objects::class)] +#[UsesClass(\Membrane\OpenAPI\Builder\Internal\Strings::class)] #[UsesClass(PathMatcher::class)] #[UsesClass(AllOf::class)] #[UsesClass(AnyOf::class)] #[UsesClass(OneOf::class)] -#[UsesClass(APISchema::class)] -#[UsesClass(Arrays::class)] -#[UsesClass(TrueFalse::class)] -#[UsesClass(Numeric::class)] -#[UsesClass(Objects::class)] -#[UsesClass(Strings::class)] #[UsesClass(Response::class)] #[UsesClass(BeforeSet::class)] #[UsesClass(Collection::class)] @@ -119,7 +105,12 @@ public function setUp(): void #[Test, TestDox('It throws an exception if you try to use the keyword "not"')] public function throwsExceptionIfNotIsFound(): void { - $response = new Response(self::DIR . 'noReferences.json', '/responsepath', Method::GET, '360'); + $response = new Response( + self::DIR . 'noReferences.json', + '/responsepath', + Method::GET, + '360', + ); self::expectExceptionObject(CannotProcessOpenAPI::unsupportedKeyword('not')); @@ -181,7 +172,7 @@ public function throwsExceptionIfPathCannotBeFound(): void $specification = new Response(self::DIR . 'noReferences.json', '/nonexistentpath', Method::GET, '200'); - (new ResponseBuilder())->build($specification); + new ResponseBuilder()->build($specification); } public static function dataSetsforBuilds(): array diff --git a/tests/OpenAPI/Builder/StringsTest.php b/tests/OpenAPI/Builder/StringsTest.php deleted file mode 100644 index 5c9f3f8c..00000000 --- a/tests/OpenAPI/Builder/StringsTest.php +++ /dev/null @@ -1,126 +0,0 @@ -supports($specification)); - } - - #[Test] - public function doesNotSupportNonStringsSpecification(): void - { - $specification = self::createStub(\Membrane\Builder\Specification::class); - $sut = new Strings(); - - self::assertFalse($sut->supports($specification)); - } - - public static function specificationsToBuild(): array - { - return [ - 'minimum input' => [ - new Specification\Strings( - '', - (new V30\Schema(new Identifier('test'), new Partial\Schema(type: 'string')))->value, - ), - new Field('', new IsString()), - ], - 'date input' => [ - new Specification\Strings( - '', - (new V30\Schema(new Identifier(''), new Partial\Schema(type: 'string', format: 'date')))->value, - ), - new Field('', new IsString(), new DateString('Y-m-d', true)), - ], - 'date-time input' => [ - new Specification\Strings( - '', - (new V30\Schema(new Identifier(''), new Partial\Schema(type: 'string', format: 'date-time')))->value, - ), - new Field( - '', - new IsString(), - new ToUpperCase(), - new \Membrane\Validator\Utility\AnyOf( - new DateString('Y-m-d\TH:i:sP', true), - new DateString('Y-m-d\TH:i:sp', true), - ), - ), - ], - 'detailed input' => [ - new Specification\Strings( - '', - (new V30\Schema( - new Identifier(''), new Partial\Schema( - type: 'string', - enum: [new Value('1970/01/01'), new Value(null)], - maxLength: 100, - minLength: 0, - pattern: '.+', - format: 'date', - ) - ))->value, - ), - new Field( - '', - new IsString(), - new Contained(['1970/01/01', null]), - new DateString('Y-m-d', true), - new Length(0, 100), - new Regex('#.+#u'), - ) - ], - ]; - } - - #[DataProvider('specificationsToBuild')] - #[Test] - public function buildTest(Specification\Strings $specification, Processor $expected): void - { - $sut = new Strings(); - - $actual = $sut->build($specification); - - self::assertEquals($expected, $actual); - } -} diff --git a/tests/OpenAPI/Builder/TrueFalseTest.php b/tests/OpenAPI/Builder/TrueFalseTest.php deleted file mode 100644 index b9b3fdf1..00000000 --- a/tests/OpenAPI/Builder/TrueFalseTest.php +++ /dev/null @@ -1,120 +0,0 @@ -supports($specification)); - } - - #[Test] - public function doesNotSupportNonNumericSpecification(): void - { - $specification = self::createStub(\Membrane\Builder\Specification::class); - $sut = new TrueFalse(); - - self::assertFalse($sut->supports($specification)); - } - - public static function specificationsToBuild(): array - { - return [ - 'input to convert from string' => [ - new Specification\TrueFalse( - '', - (new V30\Schema( - new Identifier('test'), - new Partial\Schema(type: 'boolean') - ))->value, - true, - ), - new Field('', new BoolString(), new ToBool()), - ], - 'strict input' => [ - new Specification\TrueFalse( - '', - (new V30\Schema( - new Identifier('test'), - new Partial\Schema(type: 'boolean') - ))->value, - false, - ), - new Field('', new IsBool()), - ], - 'detailed input to convert from string' => [ - new Specification\TrueFalse( - '', - (new V30\Schema( - new Identifier('test'), - new Partial\Schema( - type: 'boolean', - enum: [new Value(true), new Value(null)], - format: 'rather pointless boolean', - ) - ))->value, - true - ), - new Field('', new BoolString(), new ToBool(), new Contained([true, null])), - ], - 'strict detailed input' => [ - new Specification\TrueFalse( - '', - (new V30\Schema( - new Identifier('test'), - new Partial\Schema( - type: 'boolean', - enum: [new Value(true), new Value(null)], - format: 'rather pointless boolean', - ) - ))->value, - false - ), - new Field('', new IsBool(), new Contained([true, null])), - ], - ]; - } - - #[Test] - #[DataProvider('specificationsToBuild')] - public function buildTest(Specification\TrueFalse $specification, Processor $expected): void - { - $sut = new TrueFalse(); - - $actual = $sut->build($specification); - - self::assertEquals($expected, $actual); - } -} diff --git a/tests/OpenAPI/Filter/QueryStringToArrayTest.php b/tests/OpenAPI/Filter/QueryStringToArrayTest.php index 80bd18c7..d7911231 100644 --- a/tests/OpenAPI/Filter/QueryStringToArrayTest.php +++ b/tests/OpenAPI/Filter/QueryStringToArrayTest.php @@ -6,7 +6,6 @@ use Generator; use Membrane\OpenAPI\Filter\QueryStringToArray; -use Membrane\OpenAPI\Specification\Parameter; use Membrane\Renderer\HumanReadable; use Membrane\Result\Message; use Membrane\Result\MessageSet; diff --git a/tests/OpenAPI/Specification/ArraysTest.php b/tests/OpenAPI/Specification/ArraysTest.php deleted file mode 100644 index e541792a..00000000 --- a/tests/OpenAPI/Specification/ArraysTest.php +++ /dev/null @@ -1,103 +0,0 @@ -value - ); - } - - #[Test] - public function throwsExceptionForInvalidType(): void - { - self::expectExceptionObject(CannotProcessSpecification::mismatchedType(['array'], ['string'])); - - new Arrays( - '', - (new V30\Schema(new Identifier('test'), new Partial\Schema(type: 'string')))->value - ); - } - - public static function dataSetsToConstruct(): array - { - return [ - 'default values' => [ - new V30\Schema(new Identifier('test'), new Partial\Schema(type: 'array')), - [ - 'items' => new V30\Schema( - new Identifier('test', 'items'), - true - ), - 'maxItems' => null, - 'minItems' => 0, - 'uniqueItems' => false, - 'enum' => null, - 'format' => '', - ], - ], - 'assigned values' => [ - new V30\Schema(new Identifier('test'), new Partial\Schema( - type: 'array', - enum: [new Value([1, 2, 3]), new Value([5, 6, 7])], - maxItems: 5, - minItems: 2, - uniqueItems: true, - items: new Partial\Schema(type: 'integer'), - format: 'array of ints', - )), - [ - 'items' => new V30\Schema( - new Identifier('test', 'items'), - new Partial\Schema(type: 'integer'), - ), - 'maxItems' => 5, - 'minItems' => 2, - 'uniqueItems' => true, - 'enum' => [[1, 2, 3], [5, 6, 7]], - 'format' => 'array of ints', - ], - ], - ]; - } - - #[Test] - #[DataProvider('dataSetsToConstruct')] - public function constructTest( - V30\Schema | V31\Schema $schema, - array $expected - ): void { - $sut = new Arrays('', $schema->value); - - foreach ($expected as $key => $value) { - if ($key === 'items') { - self::assertEquals($value, $sut->$key, sprintf('%s does not meet expected value', $key)); - } else { - self::assertSame($value, $sut->$key, sprintf('%s does not meet expected value', $key)); - } - } - } -} diff --git a/tests/OpenAPI/Specification/NumericTest.php b/tests/OpenAPI/Specification/NumericTest.php deleted file mode 100644 index f1e10f85..00000000 --- a/tests/OpenAPI/Specification/NumericTest.php +++ /dev/null @@ -1,135 +0,0 @@ -value, - ); - } - - #[Test] - public function throwsExceptionForInvalidType(): void - { - self::expectExceptionObject( - CannotProcessSpecification::mismatchedType(['integer', 'number'], ['string']), - ); - - new Numeric( - '', - (new V30\Schema(new Identifier('test'), new Partial\Schema(type: 'string')))->value, - ); - } - - public static function dataSetsToConstruct(): array - { - return [ - 'default values for number' => [ - new V30\Schema(new Identifier('test'), new Partial\Schema(type: 'number')), - [ - 'type' => 'number', - 'maximum' => null, - 'minimum' => null, - 'exclusiveMaximum' => false, - 'exclusiveMinimum' => false, - 'multipleOf' => null, - 'enum' => null, - ], - ], - 'default values for integer' => [ - new V30\Schema(new Identifier('test'), new Partial\Schema(type: 'integer')), - [ - 'type' => 'integer', - 'maximum' => null, - 'minimum' => null, - 'exclusiveMaximum' => false, - 'exclusiveMinimum' => false, - 'multipleOf' => null, - 'enum' => null, - ], - ], - 'assigned values for number' => [ - new V30\Schema(new Identifier('test'), new Partial\Schema( - type: 'number', - enum: [new Value(3), new Value(9)], - multipleOf: 3, - exclusiveMaximum: true, - exclusiveMinimum: true, - maximum: 10, - minimum: 1, - format: 'float', - )), - [ - 'type' => 'number', - 'maximum' => 10, - 'minimum' => 1, - 'exclusiveMaximum' => true, - 'exclusiveMinimum' => true, - 'multipleOf' => 3, - 'enum' => [3, 9], - 'format' => 'float', - ], - ], - 'assigned values for integer' => [ - new V30\Schema(new Identifier('test'), new Partial\Schema( - type: 'integer', - enum: [new Value(9)], - multipleOf: 3, - exclusiveMaximum: true, - exclusiveMinimum: true, - maximum: 10, - minimum: 1, - format: 'square of 3', - )), - [ - 'type' => 'integer', - 'maximum' => 10, - 'minimum' => 1, - 'exclusiveMaximum' => true, - 'exclusiveMinimum' => true, - 'multipleOf' => 3, - 'enum' => [9], - 'format' => 'square of 3', - ], - ], - ]; - } - - #[DataProvider('dataSetsToConstruct')] - #[Test] - public function constructTest( - V30\Schema $schema, - array $expected - ): void { - $sut = new Numeric('', $schema->value); - - foreach ($expected as $key => $value) { - self::assertSame($value, $sut->$key, sprintf('%s did not meet expected value', $key)); - } - } -} diff --git a/tests/OpenAPI/Specification/ObjectsTest.php b/tests/OpenAPI/Specification/ObjectsTest.php deleted file mode 100644 index d8e29055..00000000 --- a/tests/OpenAPI/Specification/ObjectsTest.php +++ /dev/null @@ -1,115 +0,0 @@ -value - ); - } - - #[Test] - public function throwsExceptionForIncorrectType(): void - { - self::expectExceptionObject(CannotProcessSpecification::mismatchedType(['object'], ['string'])); - - new Objects( - '', - (new V30\Schema(new Identifier('test'), new Partial\Schema(type: 'string')))->value, - ); - } - - public static function dataSetsToConstruct(): array - { - return [ - 'default values' => [ - new V30\Schema(new Identifier('test'), new Partial\Schema(type: 'object')), - [ - 'additionalProperties' => new V30\Schema( - new Identifier('test', 'additionalProperties'), - true, - ), - 'properties' => [], - 'required' => [], - 'enum' => null, - 'format' => '', - ], - ], - 'additionalProperties assigned false' => [ - new V30\Schema(new Identifier('test'), new Partial\Schema( - type: 'object', - additionalProperties: false, - )), - [ - 'additionalProperties' => new V30\Schema( - new Identifier('test', 'additionalProperties'), - false, - ), - 'properties' => [], - 'required' => [], - 'enum' => null, - 'format' => '', - ], - ], - 'all relevant keywords assigned values' => [ - new V30\Schema(new Identifier('test'), new Partial\Schema( - type: 'object', - enum: [new Value(['id' => 5]), new Value(['id' => 10])], - required: ['id'], - properties: ['id' => new Partial\Schema(type: 'integer')], - additionalProperties: new Partial\Schema(type: 'string'), - format: 'you cannot say yes', - )), - [ - 'additionalProperties' => new V30\Schema( - new Identifier('test', 'additionalProperties'), - new Partial\Schema(type: 'string') - ), - 'properties' => ['id' => new V30\Schema( - new Identifier('test', 'properties(id)'), - new Partial\Schema(type: 'integer') - )], - 'required' => ['id'], - 'enum' => [['id' => 5], ['id' => 10]], - 'format' => 'you cannot say yes', - ], - ], - ]; - } - - #[DataProvider('dataSetsToConstruct')] - #[Test] - public function constructTest( - V30\Schema | V31\Schema $schema, - array $expected - ): void { - $sut = new Objects('', $schema->value); - - foreach ($expected as $key => $value) { - self::assertEquals($value, $sut->$key, sprintf('%s does not meet expected value', $key)); - } - } -} diff --git a/tests/OpenAPI/Specification/OpenAPIRequestTest.php b/tests/OpenAPI/Specification/OpenAPIRequestTest.php deleted file mode 100644 index 18021a17..00000000 --- a/tests/OpenAPI/Specification/OpenAPIRequestTest.php +++ /dev/null @@ -1,96 +0,0 @@ -openApi = (new MembraneReader([OpenAPIVersion::Version_3_0])) - ->readFromAbsoluteFilePath(__DIR__ . '/../../fixtures/OpenAPI/docs/petstore-expanded.json'); - $this->pathParameterExtractor = new PathParameterExtractor('/pets'); - } - - #[Test, TestDox('If the method given is not specified on the PathItem then an exception will be thrown')] - public function throwsExceptionIfMethodNotFound(): void - { - self::expectExceptionObject(CannotProcessSpecification::methodNotFound(Method::DELETE->value)); - - new OpenAPIRequest($this->pathParameterExtractor, $this->openApi->paths['/pets'], Method::DELETE); - } - - #[Test, TestDox('Throws an exception if the request body contains content that is not supported')] - public function throwsExceptionIfRequestBodyContentContainsUnsupportedMediaTypes(): void - { - $pathItem = (new MembraneReader([OpenAPIVersion::Version_3_0])) - ->readFromAbsoluteFilePath(__DIR__ . '/../../fixtures/OpenAPI/noReferences.json') - ->paths['/path']; - - $pathParameterExtractor = new PathParameterExtractor('/path'); - - self::expectExceptionObject( - CannotProcessOpenAPI::unsupportedMediaTypes(...array_keys($pathItem->put->requestBody->content)) - ); - - new OpenAPIRequest($pathParameterExtractor, $pathItem, Method::PUT); - } - - #[Test, TestDox('$parameters will contain an array of parameters with their names as keys')] - public function parameterswillContainRelevantParameters(): void - { - $expected = $this->openApi->paths['/pets']->get->parameters; - - $sut = new OpenAPIRequest($this->pathParameterExtractor, $this->openApi->paths['/pets'], Method::GET); - self::assertEquals($expected, $sut->parameters); - } - - #[Test, TestDox('$requestBodySchema will be null if request body has no content')] - public function requestBodySchemaIsNullIfRequestBodyHasNoContent(): void - { - $sut = new OpenAPIRequest($this->pathParameterExtractor, $this->openApi->paths['/pets'], Method::GET); - - self::assertNull($sut->requestBodySchema); - } - - #[Test, TestDox('$requestBodySchema will contain the request body schema if it exists')] - public function requestBodySchemaWillContainRelevantRequestBodyContent(): void - { - $expected = $this->openApi->paths['/pets']->post->requestBody->content['application/json']->schema; - $sut = new OpenAPIRequest($this->pathParameterExtractor, $this->openApi->paths['/pets'], Method::POST); - - self::assertEquals($expected, $sut->requestBodySchema); - } - - #[Test, TestDox('$operationId contains operationId for matching Operation Object')] - public function operationIdContainsRelevantOperationId(): void - { - $sut = new OpenAPIRequest($this->pathParameterExtractor, $this->openApi->paths['/pets'], Method::GET); - - self::assertEquals('findPets', $sut->operationId); - } -} diff --git a/tests/OpenAPI/Specification/OpenAPIResponseTest.php b/tests/OpenAPI/Specification/OpenAPIResponseTest.php deleted file mode 100644 index e4bce68f..00000000 --- a/tests/OpenAPI/Specification/OpenAPIResponseTest.php +++ /dev/null @@ -1,74 +0,0 @@ - new Partial\MediaType( - contentType: 'application/pdf', - schema: new Partial\Schema(type: 'string'), - )] - )); - - self::expectExceptionObject(CannotProcessOpenAPI::unsupportedMediaTypes(...array_keys($response->content))); - - new OpenAPIResponse('testOperation', '200', $response); - } - - #[Test, TestDox('$schema contains a Schema Object if the response has empty content')] - public function schemaIsNullIfContentIsEmpty(): void - { - $response = new V30\Response(new Identifier('test'), new Partial\Response( - description: 'Success', - headers: [], - content: [] - )); - - $sut = new OpenAPIResponse('testOperation', '200', $response); - - self::assertNull($sut->schema); - } - - #[Test, TestDox('$schema contains a Schema Object if the response has content')] - public function schemaContainsResponseSchemaIfContentExists(): void - { - $expected = new V30\Schema( - new Identifier('test', 'application/json', 'schema'), - new Partial\Schema(type: 'integer') - ); - - $response = new V30\Response(new Identifier('test'), new Partial\Response( - description: 'Success', - headers: [], - content: ['application/pdf' => new Partial\MediaType( - contentType: 'application/json', - schema: new Partial\Schema(type: 'integer'), - )] - )); - - $sut = new OpenAPIResponse('testOperation', '200', $response); - - self::assertEquals($expected, $sut->schema); - } -} diff --git a/tests/OpenAPI/Specification/ParameterTest.php b/tests/OpenAPI/Specification/ParameterTest.php deleted file mode 100644 index 4447c13f..00000000 --- a/tests/OpenAPI/Specification/ParameterTest.php +++ /dev/null @@ -1,195 +0,0 @@ - [ - new V30\Parameter(new Identifier('test'), new Partial\Parameter( - name: 'id', - in: 'path', - required: true, - style: 'matrix', - schema: new Partial\Schema(type: 'integer'), - )), - [ - 'name' => 'id', - 'in' => 'path', - 'required' => true, - 'style' => 'matrix', - 'explode' => false, - 'schema' => new V30\Schema( - new Identifier('test', 'id(path)', 'schema'), - new Partial\Schema(type: 'integer'), - ), - ], - ], - '"style": "label" in "path"' => [ - new V30\Parameter(new Identifier('test'), new Partial\Parameter( - name: 'id', - in: 'path', - required: true, - style: 'label', - schema: new Partial\Schema(type: 'integer'), - )), - [ - 'name' => 'id', - 'in' => 'path', - 'required' => true, - 'style' => 'label', - 'explode' => false, - 'schema' => new V30\Schema( - new Identifier('test', 'id(path)', 'schema'), - new Partial\Schema(type: 'integer'), - ), - ], - ], - '"style":"form" in "query"' => [ - new V30\Parameter(new Identifier('test'), new Partial\Parameter( - name: 'id', - in: 'query', - required: false, - style: 'form', - schema: new Partial\Schema(type: 'integer'), - )), - [ - 'name' => 'id', - 'in' => 'query', - 'required' => false, - 'style' => 'form', - 'explode' => true, - 'schema' => new V30\Schema( - new Identifier('test', 'id(query)', 'schema'), - new Partial\Schema(type: 'integer'), - ), - ], - ], - '"style":"simple" in "path"' => [ - new V30\Parameter(new Identifier('test'), new Partial\Parameter( - name: 'id', - in: 'path', - required: true, - style: 'simple', - schema: new Partial\Schema(type: 'integer'), - )), - [ - 'name' => 'id', - 'in' => 'path', - 'required' => true, - 'style' => 'simple', - 'explode' => false, - 'schema' => new V30\Schema( - new Identifier('test', 'id(path)', 'schema'), - new Partial\Schema(type: 'integer'), - ), - ], - ], - '"style":"spaceDelimited" in "query"' => [ - new V30\Parameter(new Identifier('test'), new Partial\Parameter( - name: 'id', - in: 'query', - required: false, - style: 'spaceDelimited', - schema: new Partial\Schema(type: 'integer'), - )), - [ - 'name' => 'id', - 'in' => 'query', - 'required' => false, - 'style' => 'spaceDelimited', - 'explode' => false, - 'schema' => new V30\Schema( - new Identifier('test', 'id(query)', 'schema'), - new Partial\Schema(type: 'integer'), - ), - ], - ], - '"style":"pipeDelimited" in "query"' => [ - new V30\Parameter(new Identifier('test'), new Partial\Parameter( - name: 'id', - in: 'query', - required: false, - style: 'pipeDelimited', - schema: new Partial\Schema(type: 'integer'), - )), - [ - 'name' => 'id', - 'in' => 'query', - 'required' => false, - 'style' => 'pipeDelimited', - 'explode' => false, - 'schema' => new V30\Schema( - new Identifier('test', 'id(query)', 'schema'), - new Partial\Schema(type: 'integer'), - ), - ], - ], - '"style":"deepObject" in "query"' => [ - new V30\Parameter(new Identifier('test'), new Partial\Parameter( - name: 'id', - in: 'query', - required: false, - style: 'deepObject', - explode: false, - schema: new Partial\Schema(type: 'object'), - )), - [ - 'name' => 'id', - 'in' => 'query', - 'required' => false, - 'style' => 'deepObject', - 'explode' => false, - 'schema' => new V30\Schema( - new Identifier('test', 'id(query)', 'schema'), - new Partial\Schema(type: 'object'), - ), - ], - ], - ]; - } - - #[Test] - #[TestDox('It will construct itself from valid Parameters')] - #[DataProvider('provideValidParameters')] - public function itConstructsFromValidParameters( - V30\Parameter|V31\Parameter $parameter, - array $expectedProperties - ): void { - $sut = new Parameter($parameter); - - foreach ($expectedProperties as $key => $value) { - self::assertEquals($value, $sut->$key, sprintf("'%s' doesn't match expected", $key)); - } - } -} diff --git a/tests/OpenAPI/Specification/StringsTest.php b/tests/OpenAPI/Specification/StringsTest.php deleted file mode 100644 index 83fbe178..00000000 --- a/tests/OpenAPI/Specification/StringsTest.php +++ /dev/null @@ -1,88 +0,0 @@ -value, - ); - } - - #[Test] - public function throwsExceptionForIncorrectType(): void - { - self::expectExceptionObject(CannotProcessSpecification::mismatchedType(['string'], ['integer'])); - - new Strings( - '', - (new V30\Schema(new Identifier('test'), new Partial\Schema(type: 'integer')))->value, - ); - } - - public static function dataSetsToConstruct(): array - { - return [ - 'default values' => [ - new V30\Schema(new Identifier('test'), new Partial\Schema(type: 'string')), - [ - 'maxLength' => null, - 'minLength' => 0, - 'pattern' => null, - 'enum' => null, - 'format' => '', - ], - ], - 'assigned values' => [ - new V30\Schema(new Identifier('test'), new Partial\Schema( - type: 'string', - enum: [new Value('This is a string'), new Value('So is this')], - maxLength: 20, - minLength: 6, - pattern: '.+', - format: 'arbitrary', - )), - [ - 'maxLength' => 20, - 'minLength' => 6, - 'pattern' => '.+', - 'enum' => ['This is a string', 'So is this'], - 'format' => 'arbitrary', - ], - ], - ]; - } - - #[DataProvider('dataSetsToConstruct')] - #[Test] - public function constructTest(V30\Schema|V31\Schema $schema, array $expected): void - { - $sut = new Strings('', $schema->value); - - foreach ($expected as $key => $value) { - self::assertSame($value, $sut->$key, sprintf('%s does not meet expected value', $key)); - } - } -} diff --git a/tests/OpenAPI/Specification/TrueFalseTest.php b/tests/OpenAPI/Specification/TrueFalseTest.php deleted file mode 100644 index bd285b54..00000000 --- a/tests/OpenAPI/Specification/TrueFalseTest.php +++ /dev/null @@ -1,81 +0,0 @@ -value - ); - } - - #[Test] - public function throwsExceptionForInvalidType(): void - { - self::expectExceptionObject(CannotProcessSpecification::mismatchedType(['boolean'], ['string'])); - - new TrueFalse( - '', - (new V30\Schema(new Identifier('test'), new Partial\Schema(type: 'string')))->value - ); - } - - public static function dataSetsToConstruct(): array - { - return [ - 'default values' => [ - new V30\Schema(new Identifier('test'), new Partial\Schema(type: 'boolean')), - [ - 'enum' => null, - 'format' => '', - ], - ], - 'assigned values' => [ - new V30\Schema(new Identifier('test'), new Partial\Schema( - type: 'boolean', - enum: [new Value(false), new Value(null)], - format: 'you cannot say yes', - )), - [ - 'enum' => [false, null], - 'format' => 'you cannot say yes', - ], - ], - ]; - } - - #[DataProvider('dataSetsToConstruct')] - #[Test] - public function constructTest( - V30\Schema | V31\Schema $schema, - array $expected - ): void { - $sut = new TrueFalse('', $schema->value); - - foreach ($expected as $key => $value) { - self::assertSame($value, $sut->$key, sprintf('%s does not meet expected value', $key)); - } - } -} diff --git a/tests/fixtures/OpenAPI/Provider.php b/tests/fixtures/OpenAPI/Provider.php new file mode 100644 index 00000000..c63d047c --- /dev/null +++ b/tests/fixtures/OpenAPI/Provider.php @@ -0,0 +1,20 @@ +value: + operationId: testcase + parameters: + - name: $parameter + in: header + content: + $mediaType: + schema: + type: integer + responses: + 200: + description: Success + YAML; + + return self::reader() + ->readFromString($api, FileFormat::Yaml) + ->paths[$path]; + } +}