From df4562019deee7201f30396bfe76e74acbe176f4 Mon Sep 17 00:00:00 2001 From: pkowalczyk <11366345+PabloKowalczyk@users.noreply.github.com> Date: Sat, 11 Jun 2022 17:40:00 +0200 Subject: [PATCH 1/4] Enable PHPCSFixer cache --- .gitignore | 1 + .php-cs-fixer.dist.php | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index d554ecc..4ed011e 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ build/ vendor/ composer.lock perf/blackfire.io.env +.php-cs-fixer.cache diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 1fb6523..609ea9d 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -3,7 +3,6 @@ declare(strict_types=1); return (new PhpCsFixer\Config()) - ->setUsingCache(false) ->setRules([ 'native_function_invocation' => [ 'exclude' => [ From 7a994d7aba5c6cb57c30401d05bc9f8088654ca6 Mon Sep 17 00:00:00 2001 From: pkowalczyk <11366345+PabloKowalczyk@users.noreply.github.com> Date: Sat, 11 Jun 2022 17:40:23 +0200 Subject: [PATCH 2/4] Apply cs fixer to "tests" directory --- .php-cs-fixer.dist.php | 1 + 1 file changed, 1 insertion(+) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 609ea9d..3d70fe5 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -15,6 +15,7 @@ ->setFinder( PhpCsFixer\Finder::create() ->in(__DIR__ . '/src') + ->in(__DIR__ . '/tests') ->append([__FILE__]) ) ; From 64f530c13af0404e7aa22c2e33a0e30c64b04e85 Mon Sep 17 00:00:00 2001 From: pkowalczyk <11366345+PabloKowalczyk@users.noreply.github.com> Date: Sat, 11 Jun 2022 17:41:03 +0200 Subject: [PATCH 3/4] Add new rules to CS Fixer --- .php-cs-fixer.dist.php | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 3d70fe5..ebe82df 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -4,9 +4,47 @@ return (new PhpCsFixer\Config()) ->setRules([ + '@Symfony' => true, + 'array_syntax' => ['syntax' => 'short'], + 'protected_to_private' => false, + 'combine_consecutive_unsets' => true, + 'combine_consecutive_issets' => true, + 'compact_nullable_typehint' => true, + 'declare_strict_types' => true, + 'dir_constant' => true, + 'ereg_to_preg' => true, + 'explicit_indirect_variable' => true, + 'explicit_string_variable' => true, + 'function_to_constant' => true, + 'is_null' => true, + 'modernize_types_casting' => true, + 'linebreak_after_opening_tag' => true, + 'list_syntax' => ['syntax' => 'short'], + 'mb_str_functions' => true, + 'no_alias_functions' => true, + 'no_homoglyph_names' => true, + 'no_php4_constructor' => true, + 'no_useless_else' => true, + 'no_useless_return' => true, + 'ordered_class_elements' => true, + 'ordered_imports' => true, + 'php_unit_construct' => true, + 'php_unit_dedicate_assert' => true, + 'php_unit_expectation' => true, + 'php_unit_mock' => true, + 'php_unit_namespaced' => true, + 'php_unit_method_casing' => ['case' => 'snake_case'], + 'random_api_migration' => true, + 'strict_comparison' => true, + 'strict_param' => true, + 'ternary_to_null_coalescing' => true, + 'concat_space' => [ + 'spacing' => 'one', + ], + 'single_line_throw' => false, 'native_function_invocation' => [ 'exclude' => [ - '_' + '_', ], 'include' => ['@all'], ], From 1f5eeb6bbeb76ace9c4f0f68ee233aa6e326e779 Mon Sep 17 00:00:00 2001 From: pkowalczyk <11366345+PabloKowalczyk@users.noreply.github.com> Date: Sat, 11 Jun 2022 17:41:37 +0200 Subject: [PATCH 4/4] Apply CS fixer to codebase --- src/Contracts/Encoder/EncoderInterface.php | 77 +---- src/Contracts/Factories/FactoryInterface.php | 108 +------ .../Http/Headers/AcceptMediaTypeInterface.php | 23 +- .../HeaderParametersParserInterface.php | 18 +- .../Http/Headers/MediaTypeInterface.php | 24 +- .../Http/Query/BaseQueryParserInterface.php | 19 +- src/Contracts/Http/ResponsesInterface.php | 43 ++- .../Parser/DocumentDataInterface.php | 14 +- .../Parser/EditableContextInterface.php | 13 +- src/Contracts/Parser/IdentifierInterface.php | 16 +- .../Parser/ParsedResultInterface.php | 11 +- src/Contracts/Parser/ParserInterface.php | 13 +- .../Parser/RelationshipDataInterface.php | 26 +- .../Parser/RelationshipInterface.php | 20 +- src/Contracts/Parser/ResourceInterface.php | 20 +- .../Representation/BaseWriterInterface.php | 38 +-- .../DocumentWriterInterface.php | 29 +- .../Representation/ErrorWriterInterface.php | 14 +- .../FieldSetFilterInterface.php | 21 +- src/Contracts/Schema/BaseLinkInterface.php | 20 +- src/Contracts/Schema/ContextInterface.php | 16 +- src/Contracts/Schema/DocumentInterface.php | 10 +- src/Contracts/Schema/ErrorInterface.php | 26 +- src/Contracts/Schema/IdentifierInterface.php | 16 +- src/Contracts/Schema/LinkInterface.php | 10 +- .../Schema/LinkWithAliasesInterface.php | 10 +- src/Contracts/Schema/PositionInterface.php | 18 +- .../Schema/SchemaContainerInterface.php | 14 +- src/Contracts/Schema/SchemaInterface.php | 50 +--- src/Encoder/Encoder.php | 137 +++------ src/Encoder/EncoderPropertiesTrait.php | 281 ++++++------------ src/Exceptions/BaseJsonApiException.php | 9 +- src/Exceptions/InvalidArgumentException.php | 10 +- src/Exceptions/JsonApiException.php | 29 +- src/Exceptions/LogicException.php | 10 +- src/Factories/Factory.php | 166 +++++------ src/Http/BaseResponses.php | 64 ++-- src/Http/Headers/AcceptMediaType.php | 57 +--- src/Http/Headers/HeaderParametersParser.php | 53 ++-- src/Http/Headers/MediaType.php | 143 +++------ src/Http/Query/BaseQueryParser.php | 35 +-- src/Http/Query/BaseQueryParserTrait.php | 84 ++---- src/I18n/Messages.php | 25 +- src/I18n/format.php | 11 +- src/Parser/IdentifierAndResource.php | 95 +++--- src/Parser/Parser.php | 186 ++++-------- .../RelationshipData/BaseRelationshipData.php | 25 +- .../ParseRelationshipDataTrait.php | 46 +-- .../ParseRelationshipLinksTrait.php | 65 ++-- .../RelationshipDataIsCollection.php | 36 +-- .../RelationshipDataIsIdentifier.php | 34 +-- .../RelationshipDataIsNull.php | 25 +- .../RelationshipDataIsResource.php | 33 +- src/Representation/BaseWriter.php | 68 ++--- src/Representation/DocumentWriter.php | 129 +++----- src/Representation/ErrorWriter.php | 29 +- src/Representation/FieldSetFilter.php | 49 +-- src/Schema/BaseSchema.php | 41 +-- src/Schema/Error.php | 87 ++---- src/Schema/ErrorCollection.php | 223 +++----------- src/Schema/Identifier.php | 38 +-- src/Schema/Link.php | 40 +-- src/Schema/LinkWithAliases.php | 31 +- src/Schema/SchemaContainer.php | 98 ++---- tests/BaseTestCase.php | 12 +- tests/Data/Collection.php | 23 +- tests/Data/Models/Author.php | 24 +- tests/Data/Models/AuthorCModel.php | 34 +-- tests/Data/Models/AuthorIdentity.php | 12 +- tests/Data/Models/Comment.php | 13 +- tests/Data/Models/CommentIdentity.php | 12 +- tests/Data/Models/Post.php | 21 +- tests/Data/Models/Site.php | 17 +- tests/Data/Schemas/AuthorCModelSchema.php | 33 +- tests/Data/Schemas/AuthorSchema.php | 61 ++-- tests/Data/Schemas/CommentSchema.php | 26 +- tests/Data/Schemas/DevSchema.php | 69 ++--- tests/Data/Schemas/PostSchema.php | 39 ++- tests/Data/Schemas/SiteSchema.php | 29 +- tests/Encoder/EncodeErrorsTest.php | 38 ++- tests/Encoder/EncodeIncludedObjectsTest.php | 129 ++++---- tests/Encoder/EncodeSimpleObjectsTest.php | 149 +++++----- .../Encoder/EncodeSparseAndFieldSetsTest.php | 56 ++-- tests/Encoder/EncoderTest.php | 118 ++++---- tests/Exceptions/JsonApiExceptionTest.php | 25 +- .../Issue154/CustomContainerInterface.php | 12 +- tests/Extensions/Issue154/CustomEncoder.php | 14 +- .../Issue154/CustomEncoderInterface.php | 12 +- tests/Extensions/Issue154/CustomFactory.php | 13 +- .../Issue154/CustomSchemaContainer.php | 11 +- tests/Extensions/Issue154/IssueTest.php | 13 +- tests/Extensions/Issue169/CustomEncoder.php | 35 +-- tests/Extensions/Issue169/CustomFactory.php | 11 +- tests/Extensions/Issue169/IssueTest.php | 28 +- tests/Extensions/Issue231/CustomEncoder.php | 12 +- tests/Extensions/Issue231/CustomFactory.php | 11 +- tests/Extensions/Issue231/CustomParser.php | 24 +- tests/Extensions/Issue231/IssueTest.php | 25 +- .../Extensions/Issue236/BaseCustomSchema.php | 28 +- .../Issue236/CustomAuthorSchema.php | 33 +- .../Issue236/CustomCommentSchema.php | 29 +- tests/Extensions/Issue236/CustomEncoder.php | 12 +- tests/Extensions/Issue236/CustomFactory.php | 11 +- .../Issue236/CustomIdentifierAndResource.php | 33 +- tests/Extensions/Issue236/IssueTest.php | 28 +- tests/Extensions/Issue236/SchemaFields.php | 57 +--- .../Extensions/Issue236/SchemaFieldsTrait.php | 18 +- tests/Extensions/Issue47/CustomEncoder.php | 12 +- tests/Extensions/Issue47/CustomFactory.php | 11 +- .../Extensions/Issue47/CustomFieldsFilter.php | 41 +-- tests/Extensions/Issue47/IssueTest.php | 11 +- tests/Extensions/Issue47/User.php | 18 +- tests/Extensions/Issue47/UserBaseSchema.php | 23 +- tests/Extensions/Issue67/CustomEncoder.php | 12 +- tests/Extensions/Issue67/CustomFactory.php | 11 +- tests/Extensions/Issue67/IssueTest.php | 13 +- tests/Extensions/Issue81/CommentSchema.php | 21 +- tests/Extensions/Issue81/IssueTest.php | 15 +- tests/Extensions/Issue82/AuthorSchema.php | 23 +- tests/Extensions/Issue82/IssueTest.php | 13 +- tests/Extensions/Issue91/Category.php | 24 +- tests/Extensions/Issue91/CategorySchema.php | 29 +- tests/Extensions/Issue91/IssueTest.php | 19 +- tests/Http/Headers/AcceptHeaderTest.php | 89 +++--- .../Headers/HeaderParametersParserTest.php | 98 +++--- tests/Http/Headers/MediaTypeTest.php | 57 ++-- tests/Http/Query/BaseQueryParserTest.php | 105 +++---- tests/Http/ResponsesTest.php | 107 +++---- tests/I18n/MessagesTest.php | 13 +- tests/Parser/RelationshipDataTest.php | 38 +-- tests/Sample/EncodeTest.php | 33 +- tests/Schema/ErrorCollectionTest.php | 59 ++-- tests/Schema/SchemaContainerTest.php | 48 ++- 133 files changed, 1925 insertions(+), 3657 deletions(-) diff --git a/src/Contracts/Encoder/EncoderInterface.php b/src/Contracts/Encoder/EncoderInterface.php index 3d29c53..ec0c793 100644 --- a/src/Contracts/Encoder/EncoderInterface.php +++ b/src/Contracts/Encoder/EncoderInterface.php @@ -1,8 +1,10 @@ - $link, ...` format. * - * @param array $links - * * @see LinkInterface - * - * @return self */ public function withLinks(array $links): self; /** * Add profile links that will be encoded with data. Links must be in `$link1, $link2, ...` format. * - * @param iterable $links - * * @see LinkWithAliasesInterface - * - * @return self */ public function withProfile(iterable $links): self; @@ -119,18 +90,12 @@ public function withProfile(iterable $links): self; * Add meta information that will be encoded with data. If 'null' meta will not appear in a document. * * @param mixed|null $meta - * - * @return self */ public function withMeta($meta): self; /** * If called JSON API version information will be added to a document. * - * @param string $version - * - * @return self - * * @see http://jsonapi.org/format/#document-jsonapi-object */ public function withJsonApiVersion(string $version): self; @@ -140,8 +105,6 @@ public function withJsonApiVersion(string $version): self; * * @param mixed $meta * - * @return self - * * @see http://jsonapi.org/format/#document-jsonapi-object */ public function withJsonApiMeta($meta): self; @@ -150,11 +113,8 @@ public function withJsonApiMeta($meta): self; * Add 'self' Link to top-level document's 'links' section for relationship specified. * * @param object $resource - * @param string $relationshipName * * @see http://jsonapi.org/format/#fetching-relationships - * - * @return self */ public function withRelationshipSelfLink($resource, string $relationshipName): self; @@ -162,45 +122,32 @@ public function withRelationshipSelfLink($resource, string $relationshipName): s * Add 'related' Link to top-level document's 'links' section for relationship specified. * * @param object $resource - * @param string $relationshipName * * @see http://jsonapi.org/format/#fetching-relationships - * - * @return self */ public function withRelationshipRelatedLink($resource, string $relationshipName): self; /** * Reset encoder settings to defaults. - * - * @return self */ public function reset(): self; /** * Encode input as JSON API string. * - * @param object|iterable|null $data Data to encode. - * - * @return string + * @param object|iterable|null $data data to encode */ public function encodeData($data): string; /** * Encode input as JSON API string with a list of resource identifiers. * - * @param object|iterable|null $data Data to encode. - * - * @return string + * @param object|iterable|null $data data to encode */ public function encodeIdentifiers($data): string; /** * Encode error as JSON API string. - * - * @param ErrorInterface $error - * - * @return string */ public function encodeError(ErrorInterface $error): string; @@ -208,19 +155,13 @@ public function encodeError(ErrorInterface $error): string; * Encode errors as JSON API string. * * @see ErrorInterface - * - * @param iterable $errors - * - * @return string */ public function encodeErrors(iterable $errors): string; /** * Encode input meta as JSON API string. * - * @param mixed $meta Meta information. - * - * @return string + * @param mixed $meta meta information */ public function encodeMeta($meta): string; } diff --git a/src/Contracts/Factories/FactoryInterface.php b/src/Contracts/Factories/FactoryInterface.php index 282df2e..e1362ef 100644 --- a/src/Contracts/Factories/FactoryInterface.php +++ b/src/Contracts/Factories/FactoryInterface.php @@ -1,8 +1,10 @@ -|null $parameters - * - * @return MediaTypeInterface */ public function createMediaType(string $type, string $subType, array $parameters = null): MediaTypeInterface; /** * Create media type for Accept HTTP header. * - * @param int $position - * @param string $type - * @param string $subType * @param array|null $parameters - * @param float $quality - * - * @return AcceptMediaTypeInterface */ public function createAcceptMediaType( int $position, @@ -264,11 +184,5 @@ public function createAcceptMediaType( float $quality = 1.0 ): AcceptMediaTypeInterface; - /** - * @param array $fieldSets - * @param array $includePaths - * - * @return EditableContextInterface - */ public function createParserContext(array $fieldSets, array $includePaths): EditableContextInterface; } diff --git a/src/Contracts/Http/Headers/AcceptMediaTypeInterface.php b/src/Contracts/Http/Headers/AcceptMediaTypeInterface.php index 0b7c0c2..8c94209 100644 --- a/src/Contracts/Http/Headers/AcceptMediaTypeInterface.php +++ b/src/Contracts/Http/Headers/AcceptMediaTypeInterface.php @@ -1,9 +1,11 @@ -createSchemaContainer($schemas); - $encoder = $factory->createEncoder($container); + $encoder = $factory->createEncoder($container); return $encoder; } /** - * @inheritdoc + * {@inheritdoc} */ public function encodeData($data): string { // encode to json - $array = $this->encodeDataToArray($data); + $array = $this->encodeDataToArray($data); $result = $this->encodeToJson($array); return $result; } /** - * @inheritdoc + * {@inheritdoc} */ public function encodeIdentifiers($data): string { // encode to json - $array = $this->encodeIdentifiersToArray($data); + $array = $this->encodeIdentifiersToArray($data); $result = $this->encodeToJson($array); return $result; } /** - * @inheritdoc + * {@inheritdoc} */ public function encodeError(ErrorInterface $error): string { // encode to json - $array = $this->encodeErrorToArray($error); + $array = $this->encodeErrorToArray($error); $result = $this->encodeToJson($array); return $result; } /** - * @inheritdoc + * {@inheritdoc} */ public function encodeErrors(iterable $errors): string { // encode to json - $array = $this->encodeErrorsToArray($errors); + $array = $this->encodeErrorsToArray($errors); $result = $this->encodeToJson($array); return $result; } /** - * @inheritdoc + * {@inheritdoc} */ public function encodeMeta($meta): string { // encode to json - $array = $this->encodeMetaToArray($meta); + $array = $this->encodeMetaToArray($meta); $result = $this->encodeToJson($array); return $result; } - /** - * @return FactoryInterface - */ protected static function createFactory(): FactoryInterface { return new Factory(); } /** - * @param object|iterable|null $data Data to encode. - * - * @return array + * @param object|iterable|null $data data to encode * * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ protected function encodeDataToArray($data): array { - if (\is_array($data) === false && \is_object($data) === false && $data !== null) { + if (false === \is_array($data) && false === \is_object($data) && null !== $data) { throw new InvalidArgumentException(); } $context = $this->getFactory()->createParserContext($this->getFieldSets(), $this->getIncludePaths()); - $parser = $this->getFactory()->createParser($this->getSchemaContainer(), $context); - $writer = $this->createDocumentWriter(); - $filter = $this->getFactory()->createFieldSetFilter($this->getFieldSets()); + $parser = $this->getFactory()->createParser($this->getSchemaContainer(), $context); + $writer = $this->createDocumentWriter(); + $filter = $this->getFactory()->createFieldSetFilter($this->getFieldSets()); // write header $this->writeHeader($writer); @@ -191,7 +180,7 @@ protected function encodeDataToArray($data): array foreach ($parser->parse($data, $this->getIncludePaths()) as $item) { if ($item instanceof ResourceInterface) { if ($item->getPosition()->getLevel() > ParserInterface::ROOT_LEVEL) { - if ($filter->shouldOutputRelationship($item->getPosition()) === true) { + if (true === $filter->shouldOutputRelationship($item->getPosition())) { $writer->addResourceToIncluded($item, $filter); } } else { @@ -202,10 +191,10 @@ protected function encodeDataToArray($data): array $writer->addIdentifierToData($item); } else { \assert($item instanceof DocumentDataInterface); - \assert($item->getPosition()->getLevel() === 0); - if ($item->isCollection() === true) { + \assert(0 === $item->getPosition()->getLevel()); + if (true === $item->isCollection()) { $writer->setDataAsArray(); - } elseif ($item->isNull() === true) { + } elseif (true === $item->isNull()) { $writer->setNullToData(); } } @@ -220,25 +209,23 @@ protected function encodeDataToArray($data): array } /** - * @param object|iterable|null $data Data to encode. - * - * @return array + * @param object|iterable|null $data data to encode * * @SuppressWarnings(PHPMD.ElseExpression) */ protected function encodeIdentifiersToArray($data): array { $context = $this->getFactory()->createParserContext($this->getFieldSets(), $this->getIncludePaths()); - $parser = $this->getFactory()->createParser($this->getSchemaContainer(), $context); - $writer = $this->createDocumentWriter(); - $filter = $this->getFactory()->createFieldSetFilter($this->getFieldSets()); + $parser = $this->getFactory()->createParser($this->getSchemaContainer(), $context); + $writer = $this->createDocumentWriter(); + $filter = $this->getFactory()->createFieldSetFilter($this->getFieldSets()); // write header $this->writeHeader($writer); // write body - $includePaths = $this->getIncludePaths(); - $expectIncluded = empty($includePaths) === false; + $includePaths = $this->getIncludePaths(); + $expectIncluded = false === empty($includePaths); // https://github.com/neomerx/json-api/issues/218 // @@ -255,13 +242,13 @@ protected function encodeIdentifiersToArray($data): array foreach ($parser->parse($data, $includePaths) as $item) { if ($item instanceof ResourceInterface) { if ($item->getPosition()->getLevel() > ParserInterface::ROOT_LEVEL) { - \assert($expectIncluded === true); - if ($filter->shouldOutputRelationship($item->getPosition()) === true) { + \assert(true === $expectIncluded); + if (true === $filter->shouldOutputRelationship($item->getPosition())) { $writer->addResourceToIncluded($item, $filter); } } else { $writer->addIdentifierToData($item); - if ($expectIncluded === true) { + if (true === $expectIncluded) { $writer->addResourceToIncluded($item, $filter); } } @@ -270,10 +257,10 @@ protected function encodeIdentifiersToArray($data): array $writer->addIdentifierToData($item); } else { \assert($item instanceof DocumentDataInterface); - \assert($item->getPosition()->getLevel() === 0); - if ($item->isCollection() === true) { + \assert(0 === $item->getPosition()->getLevel()); + if (true === $item->isCollection()) { $writer->setDataAsArray(); - } elseif ($item->isNull() === true) { + } elseif (true === $item->isNull()) { $writer->setNullToData(); } } @@ -287,11 +274,6 @@ protected function encodeIdentifiersToArray($data): array return $array; } - /** - * @param ErrorInterface $error - * - * @return array - */ protected function encodeErrorToArray(ErrorInterface $error): array { $writer = $this->createErrorWriter(); @@ -310,11 +292,6 @@ protected function encodeErrorToArray(ErrorInterface $error): array return $array; } - /** - * @param iterable $errors - * - * @return array - */ protected function encodeErrorsToArray(iterable $errors): array { $writer = $this->createErrorWriter(); @@ -339,8 +316,6 @@ protected function encodeErrorsToArray(iterable $errors): array /** * @param $meta - * - * @return array */ protected function encodeMetaToArray($meta): array { @@ -362,59 +337,42 @@ protected function encodeMetaToArray($meta): array return $array; } - /** - * @param BaseWriterInterface $writer - * - * @return void - */ protected function writeHeader(BaseWriterInterface $writer): void { - if ($this->hasMeta() === true) { + if (true === $this->hasMeta()) { $writer->setMeta($this->getMeta()); } - if ($this->hasJsonApiVersion() === true) { + if (true === $this->hasJsonApiVersion()) { $writer->setJsonApiVersion($this->getJsonApiVersion()); } - if ($this->hasJsonApiMeta() === true) { + if (true === $this->hasJsonApiMeta()) { $writer->setJsonApiMeta($this->getJsonApiMeta()); } - if ($this->hasLinks() === true) { + if (true === $this->hasLinks()) { $writer->setLinks($this->getLinks()); } - if ($this->hasProfile() === true) { + if (true === $this->hasProfile()) { $writer->setProfile($this->getProfile()); } } - /** - * @param BaseWriterInterface $writer - * - * @return void - */ protected function writeFooter(BaseWriterInterface $writer): void { - \assert($writer !== null); + \assert(null !== $writer); } /** * Encode array to JSON. - * - * @param array $document - * - * @return string */ protected function encodeToJson(array $document): string { return \json_encode($document, $this->getEncodeOptions(), $this->getEncodeDepth()); } - /** - * @return DocumentWriterInterface - */ private function createDocumentWriter(): DocumentWriterInterface { $writer = $this->getFactory()->createDocumentWriter(); @@ -423,9 +381,6 @@ private function createDocumentWriter(): DocumentWriterInterface return $writer; } - /** - * @return ErrorWriterInterface - */ private function createErrorWriter(): ErrorWriterInterface { $writer = $this->getFactory()->createErrorWriter(); diff --git a/src/Encoder/EncoderPropertiesTrait.php b/src/Encoder/EncoderPropertiesTrait.php index ad4ae04..bad6ffb 100644 --- a/src/Encoder/EncoderPropertiesTrait.php +++ b/src/Encoder/EncoderPropertiesTrait.php @@ -1,8 +1,10 @@ -links = null; - $this->profile = null; - $this->hasMeta = false; - $this->meta = null; + $this->links = null; + $this->profile = null; + $this->hasMeta = false; + $this->meta = null; $this->jsonApiVersion = null; - $this->jsonApiMeta = null; + $this->jsonApiMeta = null; $this->hasJsonApiMeta = false; $this @@ -135,19 +128,6 @@ public function reset( return $this; } - /** - * @return SchemaContainerInterface - */ - protected function getSchemaContainer(): SchemaContainerInterface - { - return $this->container; - } - - /** - * @param SchemaContainerInterface $container - * - * @return self - */ public function setContainer(SchemaContainerInterface $container): self { $this->container = $container; @@ -155,19 +135,6 @@ public function setContainer(SchemaContainerInterface $container): self return $this; } - /** - * @return FactoryInterface - */ - protected function getFactory(): FactoryInterface - { - return $this->factory; - } - - /** - * @param FactoryInterface $factory - * - * @return self - */ public function setFactory(FactoryInterface $factory): self { $this->factory = $factory; @@ -176,8 +143,6 @@ public function setFactory(FactoryInterface $factory): self } /** - * @param string $prefix - * * @return self|EncoderInterface */ public function withUrlPrefix(string $prefix): EncoderInterface @@ -186,17 +151,8 @@ public function withUrlPrefix(string $prefix): EncoderInterface return $this; } - /** - * @return string - */ - protected function getUrlPrefix(): string - { - return $this->urlPrefix; - } /** - * @param iterable $paths - * * @return self|EncoderInterface */ public function withIncludedPaths(iterable $paths): EncoderInterface @@ -208,7 +164,7 @@ public function withIncludedPaths(iterable $paths): EncoderInterface function (array $paths): bool { $pathsOk = true; foreach ($paths as $path) { - $pathsOk = $pathsOk === true && \is_string($path) === true && empty($path) === false; + $pathsOk = true === $pathsOk && true === \is_string($path) && false === empty($path); } return $pathsOk; @@ -223,16 +179,6 @@ function (array $paths): bool { } /** - * @return array - */ - protected function getIncludePaths(): array - { - return $this->includePaths; - } - - /** - * @param array $fieldSets - * * @return self|EncoderInterface */ public function withFieldSets(array $fieldSets): EncoderInterface @@ -242,18 +188,7 @@ public function withFieldSets(array $fieldSets): EncoderInterface return $this; } - /** - * @return array - */ - protected function getFieldSets(): array - { - return $this->fieldSets; - } - - /** - * @param int $options - * * @return self|EncoderInterface */ public function withEncodeOptions(int $options): EncoderInterface @@ -264,16 +199,6 @@ public function withEncodeOptions(int $options): EncoderInterface } /** - * @return int - */ - protected function getEncodeOptions(): int - { - return $this->encodeOptions; - } - - /** - * @param int $depth - * * @return self|EncoderInterface */ public function withEncodeDepth(int $depth): EncoderInterface @@ -286,21 +211,11 @@ public function withEncodeDepth(int $depth): EncoderInterface } /** - * @return int - */ - protected function getEncodeDepth(): int - { - return $this->encodeDepth; - } - - /** - * @param iterable $links - * * @return self|EncoderInterface */ public function withLinks(iterable $links): EncoderInterface { - $this->links = $this->hasLinks() === false ? + $this->links = false === $this->hasLinks() ? $links : $this->links = \array_merge( $this->iterableToArray($this->getLinks()), @@ -311,24 +226,6 @@ public function withLinks(iterable $links): EncoderInterface } /** - * @return bool - */ - protected function hasLinks(): bool - { - return $this->links !== null; - } - - /** - * @return iterable - */ - protected function getLinks(): iterable - { - return $this->links; - } - - /** - * @param iterable $links - * * @return self|EncoderInterface */ public function withProfile(iterable $links): EncoderInterface @@ -338,22 +235,6 @@ public function withProfile(iterable $links): EncoderInterface return $this; } - /** - * @return bool - */ - protected function hasProfile(): bool - { - return $this->profile !== null; - } - - /** - * @return iterable - */ - protected function getProfile(): iterable - { - return $this->profile; - } - /** * @param mixed $meta * @@ -361,20 +242,12 @@ protected function getProfile(): iterable */ public function withMeta($meta): EncoderInterface { - $this->meta = $meta; + $this->meta = $meta; $this->hasMeta = true; return $this; } - /** - * @return bool - */ - protected function hasMeta(): bool - { - return $this->hasMeta; - } - /** * @return mixed */ @@ -384,8 +257,6 @@ public function getMeta() } /** - * @param string $version - * * @return self|EncoderInterface */ public function withJsonApiVersion(string $version): EncoderInterface @@ -395,22 +266,6 @@ public function withJsonApiVersion(string $version): EncoderInterface return $this; } - /** - * @return bool - */ - protected function hasJsonApiVersion(): bool - { - return $this->jsonApiVersion !== null; - } - - /** - * @return string - */ - protected function getJsonApiVersion(): string - { - return $this->jsonApiVersion; - } - /** * @param mixed $meta * @@ -418,31 +273,14 @@ protected function getJsonApiVersion(): string */ public function withJsonApiMeta($meta): EncoderInterface { - $this->jsonApiMeta = $meta; + $this->jsonApiMeta = $meta; $this->hasJsonApiMeta = true; return $this; } /** - * @return bool - */ - protected function hasJsonApiMeta(): bool - { - return $this->hasJsonApiMeta; - } - - /** - * @return mixed - */ - protected function getJsonApiMeta() - { - return $this->jsonApiMeta; - } - - /** - * @param mixed $resource - * @param string $relationshipName + * @param mixed $resource * * @return self|EncoderInterface */ @@ -458,8 +296,7 @@ public function withRelationshipSelfLink($resource, string $relationshipName): E } /** - * @param mixed $resource - * @param string $relationshipName + * @param mixed $resource * * @return self|EncoderInterface */ @@ -474,14 +311,92 @@ public function withRelationshipRelatedLink($resource, string $relationshipName) ]); } + protected function getSchemaContainer(): SchemaContainerInterface + { + return $this->container; + } + + protected function getFactory(): FactoryInterface + { + return $this->factory; + } + + protected function getUrlPrefix(): string + { + return $this->urlPrefix; + } + + protected function getIncludePaths(): array + { + return $this->includePaths; + } + + protected function getFieldSets(): array + { + return $this->fieldSets; + } + + protected function getEncodeOptions(): int + { + return $this->encodeOptions; + } + + protected function getEncodeDepth(): int + { + return $this->encodeDepth; + } + + protected function hasLinks(): bool + { + return null !== $this->links; + } + + protected function getLinks(): iterable + { + return $this->links; + } + + protected function hasProfile(): bool + { + return null !== $this->profile; + } + + protected function getProfile(): iterable + { + return $this->profile; + } + + protected function hasMeta(): bool + { + return $this->hasMeta; + } + + protected function hasJsonApiVersion(): bool + { + return null !== $this->jsonApiVersion; + } + + protected function getJsonApiVersion(): string + { + return $this->jsonApiVersion; + } + + protected function hasJsonApiMeta(): bool + { + return $this->hasJsonApiMeta; + } + /** - * @param iterable $value - * - * @return array + * @return mixed */ + protected function getJsonApiMeta() + { + return $this->jsonApiMeta; + } + private function iterableToArray(iterable $value): array { - /** @var Traversable|array $value */ - return \is_array($value) === true ? $value : \iterator_to_array($value); + /* @var Traversable|array $value */ + return true === \is_array($value) ? $value : \iterator_to_array($value); } } diff --git a/src/Exceptions/BaseJsonApiException.php b/src/Exceptions/BaseJsonApiException.php index 92f60aa..bf38050 100644 --- a/src/Exceptions/BaseJsonApiException.php +++ b/src/Exceptions/BaseJsonApiException.php @@ -1,8 +1,10 @@ -errors = clone $errors; - } elseif (\is_iterable($errors) === true) { + } elseif (true === \is_iterable($errors)) { $this->errors = new ErrorCollection(); $this->addErrors($errors); } else { @@ -78,21 +75,11 @@ public function __construct($errors, int $httpCode = self::DEFAULT_HTTP_CODE, Ex $this->httpCode = $httpCode; } - /** - * @param ErrorInterface $error - * - * @return void - */ public function addError(ErrorInterface $error): void { $this->errors[] = $error; } - /** - * @param iterable $errors - * - * @return void - */ public function addErrors(iterable $errors): void { foreach ($errors as $error) { @@ -100,17 +87,11 @@ public function addErrors(iterable $errors): void } } - /** - * @return ErrorCollection - */ public function getErrors(): ErrorCollection { return $this->errors; } - /** - * @return int - */ public function getHttpCode(): int { return $this->httpCode; diff --git a/src/Exceptions/LogicException.php b/src/Exceptions/LogicException.php index 94bfc8a..954602d 100644 --- a/src/Exceptions/LogicException.php +++ b/src/Exceptions/LogicException.php @@ -1,9 +1,11 @@ -level = $level; - $this->path = $path; - $this->parentType = $parentType; + $this->level = $level; + $this->path = $path; + $this->parentType = $parentType; $this->parentRelationship = $parentRelationship; } /** - * @inheritdoc + * {@inheritdoc} */ public function getLevel(): int { @@ -117,7 +110,7 @@ public function getLevel(): int } /** - * @inheritdoc + * {@inheritdoc} */ public function getPath(): string { @@ -125,7 +118,7 @@ public function getPath(): string } /** - * @inheritdoc + * {@inheritdoc} */ public function getParentType(): ?string { @@ -133,7 +126,7 @@ public function getParentType(): ?string } /** - * @inheritdoc + * {@inheritdoc} */ public function getParentRelationship(): ?string { @@ -143,7 +136,7 @@ public function getParentRelationship(): ?string } /** - * @inheritdoc + * {@inheritdoc} */ public function createParser( SchemaContainerInterface $container, @@ -153,7 +146,7 @@ public function createParser( } /** - * @inheritdoc + * {@inheritdoc} */ public function createDocumentWriter(): DocumentWriterInterface { @@ -161,7 +154,7 @@ public function createDocumentWriter(): DocumentWriterInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function createErrorWriter(): ErrorWriterInterface { @@ -169,7 +162,7 @@ public function createErrorWriter(): ErrorWriterInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function createFieldSetFilter(array $fieldSets): FieldSetFilterInterface { @@ -177,7 +170,7 @@ public function createFieldSetFilter(array $fieldSets): FieldSetFilterInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function createParsedResource( EditableContextInterface $context, @@ -189,35 +182,30 @@ public function createParsedResource( } /** - * @inheritdoc + * {@inheritdoc} */ public function createParsedIdentifier( PositionInterface $position, SchemaIdentifierInterface $identifier ): ParserIdentifierInterface { - return new class ($position, $identifier) implements ParserIdentifierInterface - { + return new class($position, $identifier) implements ParserIdentifierInterface { private PositionInterface $position; private SchemaIdentifierInterface $identifier; - /** - * @param PositionInterface $position - * @param SchemaIdentifierInterface $identifier - */ public function __construct( PositionInterface $position, SchemaIdentifierInterface $identifier ) { - $this->position = $position; + $this->position = $position; $this->identifier = $identifier; // for test coverage only - \assert($this->getPosition() !== null); + \assert(null !== $this->getPosition()); } /** - * @inheritdoc + * {@inheritdoc} */ public function getType(): string { @@ -225,7 +213,7 @@ public function getType(): string } /** - * @inheritdoc + * {@inheritdoc} */ public function getId(): ?string { @@ -233,7 +221,7 @@ public function getId(): ?string } /** - * @inheritdoc + * {@inheritdoc} */ public function hasIdentifierMeta(): bool { @@ -241,7 +229,7 @@ public function hasIdentifierMeta(): bool } /** - * @inheritdoc + * {@inheritdoc} */ public function getIdentifierMeta() { @@ -249,7 +237,7 @@ public function getIdentifierMeta() } /** - * @inheritdoc + * {@inheritdoc} */ public function getPosition(): PositionInterface { @@ -259,7 +247,7 @@ public function getPosition(): PositionInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function createLink(bool $isSubUrl, string $value, bool $hasMeta, $meta = null): LinkInterface { @@ -267,7 +255,7 @@ public function createLink(bool $isSubUrl, string $value, bool $hasMeta, $meta = } /** - * @inheritdoc + * {@inheritdoc} * * @SuppressWarnings(PHPMD.UnusedLocalVariable) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) @@ -281,16 +269,7 @@ public function createRelationship( bool $hasMeta, $meta ): RelationshipInterface { - return new class ( - $position, - $hasData, - $data, - $hasLinks, - $links, - $hasMeta, - $meta - ) implements RelationshipInterface - { + return new class($position, $hasData, $data, $hasLinks, $links, $hasMeta, $meta) implements RelationshipInterface { private PositionInterface $position; private bool $hasData; @@ -311,13 +290,7 @@ public function createRelationship( private bool $metaIsCallable; /** - * @param PositionInterface $position - * @param bool $hasData - * @param RelationshipDataInterface|null $data - * @param bool $hasLinks - * @param iterable|null $links - * @param bool $hasMeta - * @param mixed $meta + * @param mixed $meta */ public function __construct( PositionInterface $position, @@ -329,22 +302,22 @@ public function __construct( $meta ) { \assert($position->getLevel() > ParserInterface::ROOT_LEVEL); - \assert(empty($position->getPath()) === false); - \assert(($hasData === false && $data === null) || ($hasData === true && $data !== null)); - \assert(($hasLinks === false && $links === null) || ($hasLinks === true && $links !== null)); - - $this->position = $position; - $this->hasData = $hasData; - $this->data = $data; - $this->hasLinks = $hasLinks; - $this->links = $links; - $this->hasMeta = $hasMeta; - $this->meta = $meta; + \assert(false === empty($position->getPath())); + \assert((false === $hasData && null === $data) || (true === $hasData && null !== $data)); + \assert((false === $hasLinks && null === $links) || (true === $hasLinks && null !== $links)); + + $this->position = $position; + $this->hasData = $hasData; + $this->data = $data; + $this->hasLinks = $hasLinks; + $this->links = $links; + $this->hasMeta = $hasMeta; + $this->meta = $meta; $this->metaIsCallable = \is_callable($meta); } /** - * @inheritdoc + * {@inheritdoc} */ public function getPosition(): PositionInterface { @@ -352,7 +325,7 @@ public function getPosition(): PositionInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function hasData(): bool { @@ -360,7 +333,7 @@ public function hasData(): bool } /** - * @inheritdoc + * {@inheritdoc} */ public function getData(): RelationshipDataInterface { @@ -370,7 +343,7 @@ public function getData(): RelationshipDataInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function hasLinks(): bool { @@ -378,7 +351,7 @@ public function hasLinks(): bool } /** - * @inheritdoc + * {@inheritdoc} */ public function getLinks(): iterable { @@ -388,7 +361,7 @@ public function getLinks(): iterable } /** - * @inheritdoc + * {@inheritdoc} */ public function hasMeta(): bool { @@ -396,14 +369,14 @@ public function hasMeta(): bool } /** - * @inheritdoc + * {@inheritdoc} */ public function getMeta() { \assert($this->hasMeta()); - if ($this->metaIsCallable === true) { - $this->meta = \call_user_func($this->meta); + if (true === $this->metaIsCallable) { + $this->meta = \call_user_func($this->meta); $this->metaIsCallable = false; } @@ -413,7 +386,7 @@ public function getMeta() } /** - * @inheritdoc + * {@inheritdoc} */ public function createRelationshipDataIsResource( SchemaContainerInterface $schemaContainer, @@ -425,7 +398,7 @@ public function createRelationshipDataIsResource( } /** - * @inheritdoc + * {@inheritdoc} */ public function createRelationshipDataIsIdentifier( SchemaContainerInterface $schemaContainer, @@ -437,7 +410,7 @@ public function createRelationshipDataIsIdentifier( } /** - * @inheritdoc + * {@inheritdoc} */ public function createRelationshipDataIsCollection( SchemaContainerInterface $schemaContainer, @@ -449,7 +422,7 @@ public function createRelationshipDataIsCollection( } /** - * @inheritdoc + * {@inheritdoc} */ public function createRelationshipDataIsNull(): RelationshipDataInterface { @@ -457,7 +430,7 @@ public function createRelationshipDataIsNull(): RelationshipDataInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function createMediaType(string $type, string $subType, array $parameters = null): MediaTypeInterface { @@ -465,7 +438,7 @@ public function createMediaType(string $type, string $subType, array $parameters } /** - * @inheritdoc + * {@inheritdoc} */ public function createAcceptMediaType( int $position, @@ -478,32 +451,27 @@ public function createAcceptMediaType( } /** - * @inheritdoc + * {@inheritdoc} * * @SuppressWarnings(PHPMD.UndefinedVariable) PHPMD currently has a glitch with `$position` in `setPosition` */ public function createParserContext(array $fieldSets, array $includePaths): EditableContextInterface { - return new class ($fieldSets, $includePaths) implements EditableContextInterface - { + return new class($fieldSets, $includePaths) implements EditableContextInterface { private array $fieldSets; private array $includePaths; private ?PositionInterface $position = null; - /** - * @param array $fieldSets - * @param array $includePaths - */ public function __construct(array $fieldSets, array $includePaths) { - $this->fieldSets = $fieldSets; + $this->fieldSets = $fieldSets; $this->includePaths = $includePaths; } /** - * @inheritdoc + * {@inheritdoc} */ public function getFieldSets(): array { @@ -511,7 +479,7 @@ public function getFieldSets(): array } /** - * @inheritdoc + * {@inheritdoc} */ public function getIncludePaths(): array { @@ -519,19 +487,19 @@ public function getIncludePaths(): array } /** - * @inheritdoc + * {@inheritdoc} */ public function getPosition(): PositionInterface { // parser's implementation should guarantee that position will always be initialized // before use in a schema. - \assert($this->position !== null); + \assert(null !== $this->position); return $this->position; } /** - * @inheritdoc + * {@inheritdoc} */ public function setPosition(PositionInterface $position): void { diff --git a/src/Http/BaseResponses.php b/src/Http/BaseResponses.php index 541afb9..cfdf4c8 100644 --- a/src/Http/BaseResponses.php +++ b/src/Http/BaseResponses.php @@ -1,8 +1,10 @@ -getEncoder()->encodeData($resource); + $content = $this->getEncoder()->encodeData($resource); $headers[self::HEADER_LOCATION] = $url; return $this->createJsonApiResponse($content, self::HTTP_CREATED, $headers, true); } /** - * @inheritdoc + * {@inheritdoc} */ public function getCodeResponse(int $statusCode, array $headers = []) { @@ -86,7 +64,7 @@ public function getCodeResponse(int $statusCode, array $headers = []) } /** - * @inheritdoc + * {@inheritdoc} */ public function getMetaResponse($meta, int $statusCode = self::HTTP_OK, array $headers = []) { @@ -96,7 +74,7 @@ public function getMetaResponse($meta, int $statusCode = self::HTTP_OK, array $h } /** - * @inheritDoc + * {@inheritDoc} */ public function getIdentifiersResponse($data, int $statusCode = self::HTTP_OK, array $headers = []) { @@ -106,13 +84,13 @@ public function getIdentifiersResponse($data, int $statusCode = self::HTTP_OK, a } /** - * @inheritdoc + * {@inheritdoc} * * @SuppressWarnings(PHPMD.ElseExpression) */ public function getErrorResponse($errors, int $statusCode = self::HTTP_BAD_REQUEST, array $headers = []) { - if (\is_iterable($errors) === true) { + if (true === \is_iterable($errors)) { /** @var iterable $errors */ $content = $this->getEncoder()->encodeErrors($errors); } else { @@ -124,10 +102,18 @@ public function getErrorResponse($errors, int $statusCode = self::HTTP_BAD_REQUE } /** - * @param string|null $content - * @param int $statusCode - * @param array $headers - * @param bool $addContentType + * Create HTTP response. + * + * @return mixed + */ + abstract protected function createResponse(?string $content, int $statusCode, array $headers); + + abstract protected function getEncoder(): EncoderInterface; + + abstract protected function getMediaType(): MediaTypeInterface; + + /** + * @param bool $addContentType * * @return mixed * @@ -139,7 +125,7 @@ protected function createJsonApiResponse( array $headers = [], $addContentType = true ) { - if ($addContentType === true) { + if (true === $addContentType) { $headers[self::HEADER_CONTENT_TYPE] = $this->getMediaType()->getMediaType(); } diff --git a/src/Http/Headers/AcceptMediaType.php b/src/Http/Headers/AcceptMediaType.php index 055c052..b8bf9ef 100644 --- a/src/Http/Headers/AcceptMediaType.php +++ b/src/Http/Headers/AcceptMediaType.php @@ -1,8 +1,10 @@ -|null $parameters - * @param float $quality */ public function __construct( int $position, @@ -62,11 +57,11 @@ public function __construct( $quality = \floor($quality * 1000) / 1000; $this->position = $position; - $this->quality = $quality; + $this->quality = $quality; } /** - * @inheritdoc + * {@inheritdoc} */ public function getPosition(): int { @@ -74,49 +69,41 @@ public function getPosition(): int } /** - * @inheritdoc + * {@inheritdoc} */ public function getQuality(): float { return $this->quality; } - /** - * @return Closure - */ public static function getCompare(): Closure { return function (AcceptMediaTypeInterface $lhs, AcceptMediaTypeInterface $rhs) { $qualityCompare = self::compareQuality($lhs->getQuality(), $rhs->getQuality()); - if ($qualityCompare !== 0) { + if (0 !== $qualityCompare) { return $qualityCompare; } $typeCompare = self::compareStrings($lhs->getType(), $rhs->getType()); - if ($typeCompare !== 0) { + if (0 !== $typeCompare) { return $typeCompare; } $subTypeCompare = self::compareStrings($lhs->getSubType(), $rhs->getSubType()); - if ($subTypeCompare !== 0) { + if (0 !== $subTypeCompare) { return $subTypeCompare; } $parametersCompare = self::compareParameters($lhs->getParameters(), $rhs->getParameters()); - if ($parametersCompare !== 0) { + if (0 !== $parametersCompare) { return $parametersCompare; } - return ($lhs->getPosition() - $rhs->getPosition()); + return $lhs->getPosition() - $rhs->getPosition(); }; } /** - * @param float $lhs - * @param float $rhs - * - * @return int - * * @SuppressWarnings(PHPMD.ElseExpression) */ private static function compareQuality(float $lhs, float $rhs): int @@ -126,30 +113,18 @@ private static function compareQuality(float $lhs, float $rhs): int // rfc2616: 3 digits are meaningful (#3.9 Quality Values) if (\abs($qualityDiff) < 0.001) { return 0; - } else { - return $lhs > $rhs ? -1 : 1; } + + return $lhs > $rhs ? -1 : 1; } - /** - * @param string $lhs - * @param string $rhs - * - * @return int - */ private static function compareStrings(string $lhs, string $rhs): int { - return ($rhs !== '*' ? 1 : 0) - ($lhs !== '*' ? 1 : 0); + return ('*' !== $rhs ? 1 : 0) - ('*' !== $lhs ? 1 : 0); } - /** - * @param array|null $lhs - * @param array|null $rhs - * - * @return int - */ private static function compareParameters(?array $lhs, ?array $rhs): int { - return (empty($lhs) !== false ? 1 : 0) - (empty($rhs) !== false ? 1 : 0); + return (false !== empty($lhs) ? 1 : 0) - (false !== empty($rhs) ? 1 : 0); } } diff --git a/src/Http/Headers/HeaderParametersParser.php b/src/Http/Headers/HeaderParametersParser.php index 46ef69a..33aaaa0 100644 --- a/src/Http/Headers/HeaderParametersParser.php +++ b/src/Http/Headers/HeaderParametersParser.php @@ -1,8 +1,10 @@ -factory = $factory; } /** - * @inheritdoc + * {@inheritdoc} */ public function parseAcceptHeader(string $value): iterable { - if (empty($value) === true) { + if (true === empty($value)) { throw new InvalidArgumentException('value'); } - $ranges = \preg_split("/,(?=([^\"]*\"[^\"]*\")*[^\"]*$)/", $value); - $count = is_countable($ranges) ? \count($ranges) : 0; + $ranges = \preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $value); + $count = \is_countable($ranges) ? \count($ranges) : 0; for ($idx = 0; $idx < $count; ++$idx) { $fields = \explode(';', $ranges[$idx]); - if (\strpos($fields[0], '/') === false) { + if (false === \mb_strpos($fields[0], '/')) { throw new InvalidArgumentException('mediaType'); } @@ -66,27 +62,27 @@ public function parseAcceptHeader(string $value): iterable } /** - * @inheritdoc + * {@inheritdoc} */ public function parseContentTypeHeader(string $mediaType): MediaTypeInterface { $fields = \explode(';', $mediaType); - if (\strpos($fields[0], '/') === false) { + if (false === \mb_strpos($fields[0], '/')) { throw new InvalidArgumentException('mediaType'); } [$type, $subType] = \explode('/', $fields[0], 2); $parameters = null; - $count = \count($fields); + $count = \count($fields); for ($idx = 1; $idx < $count; ++$idx) { $fieldValue = $fields[$idx]; - if (empty($fieldValue) === true) { + if (true === empty($fieldValue)) { continue; } - if (\strpos($fieldValue, '=') === false) { + if (false === \mb_strpos($fieldValue, '=')) { throw new InvalidArgumentException('mediaType'); } @@ -97,42 +93,37 @@ public function parseContentTypeHeader(string $mediaType): MediaTypeInterface return $this->factory->createMediaType($type, $subType, $parameters); } - /** - * @param array $fields - * - * @return array - */ private function parseQualityAndParameters(array $fields): array { - $quality = 1; + $quality = 1; $qParamFound = false; - $parameters = null; + $parameters = null; $count = \count($fields); for ($idx = 1; $idx < $count; ++$idx) { $fieldValue = $fields[$idx]; - if (empty($fieldValue) === true) { + if (true === empty($fieldValue)) { continue; } - if (\strpos($fieldValue, '=') === false) { + if (false === \mb_strpos($fieldValue, '=')) { throw new InvalidArgumentException('mediaType'); } [$key, $value] = \explode('=', $fieldValue, 2); - $key = \trim($key); + $key = \trim($key); $value = \trim($value, ' "'); // 'q' param separates media parameters from extension parameters - if ($key === 'q' && $qParamFound === false) { - $quality = (float)$value; + if ('q' === $key && false === $qParamFound) { + $quality = (float) $value; $qParamFound = true; continue; } - if ($qParamFound === false) { + if (false === $qParamFound) { $parameters[$key] = $value; } } diff --git a/src/Http/Headers/MediaType.php b/src/Http/Headers/MediaType.php index 175e7e6..90d719a 100644 --- a/src/Http/Headers/MediaType.php +++ b/src/Http/Headers/MediaType.php @@ -1,8 +1,10 @@ - true, + ]; private string $type; private string $subType; @@ -41,38 +48,27 @@ class MediaType implements MediaTypeInterface private ?array $parameters; /** - * A list of parameter names for case-insensitive compare. Keys must be lower-cased. - * - * @var array - */ - protected const PARAMETER_NAMES = [ - 'charset' => true, - ]; - - /** - * @param string $type - * @param string $subType * @param array|null $parameters */ public function __construct(string $type, string $subType, array $parameters = null) { $type = \trim($type); - if (empty($type) === true) { + if (true === empty($type)) { throw new InvalidArgumentException('type'); } $subType = \trim($subType); - if (empty($subType) === true) { + if (true === empty($subType)) { throw new InvalidArgumentException('subType'); } - $this->type = $type; - $this->subType = $subType; + $this->type = $type; + $this->subType = $subType; $this->parameters = $parameters; } /** - * @inheritdoc + * {@inheritdoc} */ public function getType(): string { @@ -80,7 +76,7 @@ public function getType(): string } /** - * @inheritdoc + * {@inheritdoc} */ public function getSubType(): string { @@ -88,11 +84,11 @@ public function getSubType(): string } /** - * @inheritdoc + * {@inheritdoc} */ public function getMediaType(): string { - if ($this->mediaType === null) { + if (null === $this->mediaType) { $this->mediaType = $this->type . '/' . $this->getSubType(); } @@ -100,7 +96,7 @@ public function getMediaType(): string } /** - * @inheritdoc + * {@inheritdoc} */ public function getParameters(): ?array { @@ -108,7 +104,7 @@ public function getParameters(): ?array } /** - * @inheritdoc + * {@inheritdoc} */ public function matchesTo(MediaTypeInterface $mediaType): bool { @@ -119,7 +115,7 @@ public function matchesTo(MediaTypeInterface $mediaType): bool } /** - * @inheritdoc + * {@inheritdoc} */ public function equalsTo(MediaTypeInterface $mediaType): bool { @@ -129,67 +125,42 @@ public function equalsTo(MediaTypeInterface $mediaType): bool $this->isMediaParametersEqual($mediaType); } - /** - * @param MediaTypeInterface $mediaType - * - * @return bool - */ private function isTypeMatches(MediaTypeInterface $mediaType): bool { - return $mediaType->getType() === '*' || $this->isTypeEquals($mediaType); + return '*' === $mediaType->getType() || $this->isTypeEquals($mediaType); } - /** - * @param MediaTypeInterface $mediaType - * - * @return bool - */ private function isTypeEquals(MediaTypeInterface $mediaType): bool { // Type, subtype and param name should be compared case-insensitive // https://tools.ietf.org/html/rfc7231#section-3.1.1.1 - return \strcasecmp($this->type, $mediaType->getType()) === 0; + return 0 === \strcasecmp($this->type, $mediaType->getType()); } - /** - * @param MediaTypeInterface $mediaType - * - * @return bool - */ private function isSubTypeMatches(MediaTypeInterface $mediaType): bool { - return $mediaType->getSubType() === '*' || $this->isSubTypeEquals($mediaType); + return '*' === $mediaType->getSubType() || $this->isSubTypeEquals($mediaType); } - /** - * @param MediaTypeInterface $mediaType - * - * @return bool - */ private function isSubTypeEquals(MediaTypeInterface $mediaType): bool { // Type, subtype and param name should be compared case-insensitive // https://tools.ietf.org/html/rfc7231#section-3.1.1.1 - return \strcasecmp($this->getSubType(), $mediaType->getSubType()) === 0; + return 0 === \strcasecmp($this->getSubType(), $mediaType->getSubType()); } - /** - * @param MediaTypeInterface $mediaType - * - * @return bool - */ private function isMediaParametersMatch(MediaTypeInterface $mediaType): bool { - if ($this->bothMediaTypeParamsEmpty($mediaType) === true) { + if (true === $this->bothMediaTypeParamsEmpty($mediaType)) { return true; } elseif ($this->bothMediaTypeParamsNotEmptyAndEqualInSize($mediaType)) { // Type, subtype and param name should be compared case-insensitive // https://tools.ietf.org/html/rfc7231#section-3.1.1.1 - $ourParameters = \array_change_key_case($this->parameters); + $ourParameters = \array_change_key_case($this->parameters); $parametersToCompare = \array_change_key_case($mediaType->getParameters()); // if at least one name are different they are not equal - if (empty(\array_diff_key($ourParameters, $parametersToCompare)) === false) { + if (false === empty(\array_diff_key($ourParameters, $parametersToCompare))) { return false; } @@ -198,7 +169,7 @@ private function isMediaParametersMatch(MediaTypeInterface $mediaType): bool // > 'Parameter values might or might not be case-sensitive, depending on // the semantics of the parameter name.' foreach ($ourParameters as $name => $value) { - if ($this->paramValuesMatch($name, $value, $parametersToCompare[$name]) === false) { + if (false === $this->paramValuesMatch($name, $value, $parametersToCompare[$name])) { return false; } } @@ -209,23 +180,18 @@ private function isMediaParametersMatch(MediaTypeInterface $mediaType): bool return false; } - /** - * @param MediaTypeInterface $mediaType - * - * @return bool - */ private function isMediaParametersEqual(MediaTypeInterface $mediaType): bool { - if ($this->bothMediaTypeParamsEmpty($mediaType) === true) { + if (true === $this->bothMediaTypeParamsEmpty($mediaType)) { return true; } elseif ($this->bothMediaTypeParamsNotEmptyAndEqualInSize($mediaType)) { // Type, subtype and param name should be compared case-insensitive // https://tools.ietf.org/html/rfc7231#section-3.1.1.1 - $ourParameters = \array_change_key_case($this->parameters); + $ourParameters = \array_change_key_case($this->parameters); $parametersToCompare = \array_change_key_case($mediaType->getParameters()); // if at least one name are different they are not equal - if (empty(\array_diff_key($ourParameters, $parametersToCompare)) === false) { + if (false === empty(\array_diff_key($ourParameters, $parametersToCompare))) { return false; } @@ -234,7 +200,7 @@ private function isMediaParametersEqual(MediaTypeInterface $mediaType): bool // > 'Parameter values might or might not be case-sensitive, depending on // the semantics of the parameter name.' foreach ($ourParameters as $name => $value) { - if ($this->paramValuesEqual($name, $value, $parametersToCompare[$name]) === false) { + if (false === $this->paramValuesEqual($name, $value, $parametersToCompare[$name])) { return false; } } @@ -245,64 +211,35 @@ private function isMediaParametersEqual(MediaTypeInterface $mediaType): bool return false; } - /** - * @param MediaTypeInterface $mediaType - * - * @return bool - */ private function bothMediaTypeParamsEmpty(MediaTypeInterface $mediaType): bool { - return $this->parameters === null && $mediaType->getParameters() === null; + return null === $this->parameters && null === $mediaType->getParameters(); } - /** - * @param MediaTypeInterface $mediaType - * - * @return bool - */ private function bothMediaTypeParamsNotEmptyAndEqualInSize(MediaTypeInterface $mediaType): bool { $pr1 = $this->parameters; $pr2 = $mediaType->getParameters(); - return (empty($pr1) === false && empty($pr2) === false) && (\count($pr1) === \count($pr2)); + return (false === empty($pr1) && false === empty($pr2)) && (\count($pr1) === \count($pr2)); } - /** - * @param string $name - * - * @return bool - */ private function isParamCaseInsensitive(string $name): bool { return isset(static::PARAMETER_NAMES[$name]); } - /** - * @param string $name - * @param string $value - * @param string $valueToCompare - * - * @return bool - */ private function paramValuesEqual(string $name, string $value, string $valueToCompare): bool { - $valuesEqual = $this->isParamCaseInsensitive($name) === true ? - \strcasecmp($value, $valueToCompare) === 0 : $value === $valueToCompare; + $valuesEqual = true === $this->isParamCaseInsensitive($name) ? + 0 === \strcasecmp($value, $valueToCompare) : $value === $valueToCompare; return $valuesEqual; } - /** - * @param string $name - * @param string $value - * @param string $valueToCompare - * - * @return bool - */ private function paramValuesMatch(string $name, string $value, string $valueToCompare): bool { - $valuesEqual = $valueToCompare === '*' || $this->paramValuesEqual($name, $value, $valueToCompare); + $valuesEqual = '*' === $valueToCompare || $this->paramValuesEqual($name, $value, $valueToCompare); return $valuesEqual; } diff --git a/src/Http/Query/BaseQueryParser.php b/src/Http/Query/BaseQueryParser.php index a0d3a03..169a4d0 100644 --- a/src/Http/Query/BaseQueryParser.php +++ b/src/Http/Query/BaseQueryParser.php @@ -1,8 +1,10 @@ -getProfileUrlsImpl($this->getParameters(), $this->getMessage(static::MSG_ERR_INVALID_PARAMETER)); } - /** - * @param array $parameters - * - * @return self - */ protected function setParameters(array $parameters): self { $this->parameters = $parameters; @@ -104,9 +97,6 @@ protected function setParameters(array $parameters): self return $this; } - /** - * @return array - */ protected function getParameters(): array { return $this->parameters; @@ -114,8 +104,6 @@ protected function getParameters(): array /** * @param array $messages - * - * @return self */ protected function setMessages(?array $messages): self { @@ -124,11 +112,6 @@ protected function setMessages(?array $messages): self return $this; } - /** - * @param string $message - * - * @return string - */ protected function getMessage(string $message): string { return $this->messages[$message] ?? $message; diff --git a/src/Http/Query/BaseQueryParserTrait.php b/src/Http/Query/BaseQueryParserTrait.php index 90bef25..0d6edcf 100644 --- a/src/Http/Query/BaseQueryParserTrait.php +++ b/src/Http/Query/BaseQueryParserTrait.php @@ -1,8 +1,10 @@ -splitCommaSeparatedStringAndCheckNoEmpties(P::PARAM_INCLUDE, $includes, $errorTitle); + $paths = $this->splitCommaSeparatedStringAndCheckNoEmpties(P::PARAM_INCLUDE, $includes, $errorTitle); foreach ($paths as $path) { yield $path => $this->splitStringAndCheckNoEmpties(P::PARAM_INCLUDE, $path, '.', $errorTitle); } } } - /** - * @param array $parameters - * @param string $errorTitle - * - * @return iterable - */ protected function getIncludePaths(array $parameters, string $errorTitle): iterable { $aIncludes = $this->getIncludes($parameters, $errorTitle); foreach ($aIncludes as $path => $parsed) { - \assert($parsed !== null); + \assert(null !== $parsed); yield $path; } } - /** - * @param array $parameters - * @param string $errorTitle - * - * @return iterable - */ protected function getFields(array $parameters, string $errorTitle): iterable { - if (\array_key_exists(P::PARAM_FIELDS, $parameters) === true) { + if (true === \array_key_exists(P::PARAM_FIELDS, $parameters)) { $fields = $parameters[P::PARAM_FIELDS]; - if (\is_array($fields) === false || empty($fields) === true) { + if (false === \is_array($fields) || true === empty($fields)) { throw new JsonApiException($this->createParameterError(P::PARAM_FIELDS, $errorTitle)); } @@ -80,26 +61,20 @@ protected function getFields(array $parameters, string $errorTitle): iterable } } - /** - * @param array $parameters - * @param string $errorTitle - * - * @return iterable - */ protected function getSorts(array $parameters, string $errorTitle): iterable { - if (\array_key_exists(P::PARAM_SORT, $parameters) === true) { - $sorts = $parameters[P::PARAM_SORT]; + if (true === \array_key_exists(P::PARAM_SORT, $parameters)) { + $sorts = $parameters[P::PARAM_SORT]; $values = $this->splitCommaSeparatedStringAndCheckNoEmpties(P::PARAM_SORT, $sorts, $errorTitle); foreach ($values as $orderAndField) { switch ($orderAndField[0]) { case '-': $isAsc = false; - $field = \substr($orderAndField, 1); + $field = \mb_substr($orderAndField, 1); break; case '+': $isAsc = true; - $field = \substr($orderAndField, 1); + $field = \mb_substr($orderAndField, 1); break; default: $isAsc = true; @@ -112,15 +87,9 @@ protected function getSorts(array $parameters, string $errorTitle): iterable } } - /** - * @param array $parameters - * @param string $errorTitle - * - * @return iterable - */ protected function getProfileUrls(array $parameters, string $errorTitle): iterable { - if (\array_key_exists(P::PARAM_PROFILE, $parameters) === true) { + if (true === \array_key_exists(P::PARAM_PROFILE, $parameters)) { $encodedUrls = $parameters[P::PARAM_PROFILE]; $decodedUrls = \urldecode($encodedUrls); yield from $this->splitSpaceSeparatedStringAndCheckNoEmpties( @@ -132,11 +101,7 @@ protected function getProfileUrls(array $parameters, string $errorTitle): iterab } /** - * @param string $paramName * @param string|mixed $shouldBeString - * @param string $errorTitle - * - * @return iterable */ private function splitCommaSeparatedStringAndCheckNoEmpties( string $paramName, @@ -147,11 +112,7 @@ private function splitCommaSeparatedStringAndCheckNoEmpties( } /** - * @param string $paramName * @param string|mixed $shouldBeString - * @param string $errorTitle - * - * @return iterable */ private function splitSpaceSeparatedStringAndCheckNoEmpties( string $paramName, @@ -162,12 +123,7 @@ private function splitSpaceSeparatedStringAndCheckNoEmpties( } /** - * @param string $paramName * @param string|mixed $shouldBeString - * @param string $separator - * @param string $errorTitle - * - * @return iterable * * @SuppressWarnings(PHPMD.IfStatementAssignment) */ @@ -177,13 +133,13 @@ private function splitStringAndCheckNoEmpties( string $separator, string $errorTitle ): iterable { - if (\is_string($shouldBeString) === false || ($trimmed = \trim($shouldBeString)) === '') { + if (false === \is_string($shouldBeString) || ($trimmed = \trim($shouldBeString)) === '') { throw new JsonApiException($this->createParameterError($paramName, $errorTitle)); } foreach (\explode($separator, $trimmed) as $value) { $trimmedValue = \trim($value); - if ($trimmedValue === '') { + if ('' === $trimmedValue) { throw new JsonApiException($this->createParameterError($paramName, $errorTitle)); } @@ -191,16 +147,10 @@ private function splitStringAndCheckNoEmpties( } } - /** - * @param string $paramName - * @param string $errorTitle - * - * @return ErrorInterface - */ private function createParameterError(string $paramName, string $errorTitle): ErrorInterface { $source = [Error::SOURCE_PARAMETER => $paramName]; - $error = new Error(null, null, null, null, null, $errorTitle, null, $source); + $error = new Error(null, null, null, null, null, $errorTitle, null, $source); return $error; } diff --git a/src/I18n/Messages.php b/src/I18n/Messages.php index 64e2cc9..c1f5098 100644 --- a/src/I18n/Messages.php +++ b/src/I18n/Messages.php @@ -1,9 +1,11 @@ -getSchema($data); - $this->context = $context; - $this->position = $position; - $this->factory = $factory; + $this->context = $context; + $this->position = $position; + $this->factory = $factory; $this->schemaContainer = $container; - $this->schema = $schema; - $this->data = $data; - $this->index = $schema->getId($data); - $this->type = $schema->getType(); + $this->schema = $schema; + $this->data = $data; + $this->index = $schema->getId($data); + $this->type = $schema->getType(); } /** - * @inheritdoc + * {@inheritdoc} */ public function getPosition(): PositionInterface { @@ -108,7 +104,7 @@ public function getPosition(): PositionInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function getId(): ?string { @@ -116,7 +112,7 @@ public function getId(): ?string } /** - * @inheritdoc + * {@inheritdoc} */ public function getType(): string { @@ -124,7 +120,7 @@ public function getType(): string } /** - * @inheritdoc + * {@inheritdoc} */ public function hasIdentifierMeta(): bool { @@ -132,7 +128,7 @@ public function hasIdentifierMeta(): bool } /** - * @inheritdoc + * {@inheritdoc} */ public function getIdentifierMeta() { @@ -140,7 +136,7 @@ public function getIdentifierMeta() } /** - * @inheritdoc + * {@inheritdoc} */ public function getAttributes(): iterable { @@ -150,13 +146,13 @@ public function getAttributes(): iterable } /** - * @inheritdoc + * {@inheritdoc} * * @SuppressWarnings(PHPMD.UndefinedVariable) PHPMD currently do not support `list` in `[]` syntax */ public function getRelationships(): iterable { - if ($this->relationshipsCache !== null) { + if (null !== $this->relationshipsCache) { yield from $this->relationshipsCache; return; @@ -164,12 +160,12 @@ public function getRelationships(): iterable $this->relationshipsCache = []; - $currentPath = $this->position->getPath(); - $nextLevel = $this->position->getLevel() + 1; - $nextPathPrefix = empty($currentPath) === true ? '' : $currentPath . PositionInterface::PATH_SEPARATOR; + $currentPath = $this->position->getPath(); + $nextLevel = $this->position->getLevel() + 1; + $nextPathPrefix = true === empty($currentPath) ? '' : $currentPath . PositionInterface::PATH_SEPARATOR; $this->getContext()->setPosition($this->getPosition()); foreach ($this->schema->getRelationships($this->data, $this->getContext()) as $name => $description) { - \assert($this->assertRelationshipNameAndDescription($name, $description) === true); + \assert(true === $this->assertRelationshipNameAndDescription($name, $description)); [$hasData, $relationshipData, $nextPosition] = $this->parseRelationshipData( $this->factory, @@ -186,11 +182,11 @@ public function getRelationships(): iterable $this->parseRelationshipLinks($this->schema, $this->data, $name, $description); $hasMeta = \array_key_exists(SchemaInterface::RELATIONSHIP_META, $description); - $meta = $hasMeta === true ? $description[SchemaInterface::RELATIONSHIP_META] : null; + $meta = true === $hasMeta ? $description[SchemaInterface::RELATIONSHIP_META] : null; \assert( $hasData || $hasMeta || $hasLinks, - "Relationship `$name` for type `" . $this->getType() . + "Relationship `${name}` for type `" . $this->getType() . '` MUST contain at least one of the following: links, data or meta.' ); @@ -211,17 +207,17 @@ public function getRelationships(): iterable } /** - * @inheritdoc + * {@inheritdoc} */ public function hasLinks(): bool { $this->cacheLinks(); - return empty($this->links) === false; + return false === empty($this->links); } /** - * @inheritdoc + * {@inheritdoc} */ public function getLinks(): iterable { @@ -231,7 +227,7 @@ public function getLinks(): iterable } /** - * @inheritdoc + * {@inheritdoc} */ public function hasResourceMeta(): bool { @@ -239,16 +235,13 @@ public function hasResourceMeta(): bool } /** - * @inheritdoc + * {@inheritdoc} */ public function getResourceMeta() { return $this->schema->getResourceMeta($this->data); } - /** - * @return EditableContextInterface - */ protected function getContext(): EditableContextInterface { return $this->context; @@ -259,31 +252,25 @@ protected function getContext(): EditableContextInterface */ private function cacheLinks(): void { - if ($this->links === null) { + if (null === $this->links) { $this->links = []; foreach ($this->schema->getLinks($this->data) as $name => $link) { - \assert(\is_string($name) === true && empty($name) === false); + \assert(true === \is_string($name) && false === empty($name)); \assert($link instanceof LinkInterface); $this->links[$name] = $link; } } } - /** - * @param string $name - * @param array $description - * - * @return bool - */ private function assertRelationshipNameAndDescription(string $name, array $description): bool { \assert( - \is_string($name) === true && empty($name) === false, - "Relationship names for type `" . $this->getType() . '` should be non-empty strings.' + true === \is_string($name) && false === empty($name), + 'Relationship names for type `' . $this->getType() . '` should be non-empty strings.' ); \assert( - \is_array($description) === true && empty($description) === false, - "Relationship `$name` for type `" . $this->getType() . '` should be a non-empty array.' + true === \is_array($description) && false === empty($description), + "Relationship `${name}` for type `" . $this->getType() . '` should be a non-empty array.' ); return true; diff --git a/src/Parser/Parser.php b/src/Parser/Parser.php index 5546355..14d2709 100644 --- a/src/Parser/Parser.php +++ b/src/Parser/Parser.php @@ -1,8 +1,10 @@ -resourcesTracker = []; - $this->factory = $factory; - $this->schemaContainer = $container; - $this->context = $context; + $this->factory = $factory; + $this->schemaContainer = $container; + $this->context = $context; } /** - * @inheritdoc + * {@inheritdoc} * * @SuppressWarnings(PHPMD.ElseExpression) */ public function parse($data, array $paths = []): iterable { - \assert(\is_array($data) === true || \is_object($data) === true || $data === null); + \assert(true === \is_array($data) || true === \is_object($data) || null === $data); $this->paths = $this->normalizePaths($paths); @@ -101,41 +96,53 @@ public function parse($data, array $paths = []): iterable null ); - if ($this->schemaContainer->hasSchema($data) === true) { + if (true === $this->schemaContainer->hasSchema($data)) { yield $this->createDocumentDataIsResource($rootPosition); yield from $this->parseAsResource($rootPosition, $data); } elseif ($data instanceof SchemaIdentifierInterface) { yield $this->createDocumentDataIsIdentifier($rootPosition); yield $this->parseAsIdentifier($rootPosition, $data); - } elseif (\is_array($data) === true) { + } elseif (true === \is_array($data)) { yield $this->createDocumentDataIsCollection($rootPosition); yield from $this->parseAsResourcesOrIdentifiers($rootPosition, $data); } elseif ($data instanceof Traversable) { $data = $data instanceof IteratorAggregate ? $data->getIterator() : $data; yield $this->createDocumentDataIsCollection($rootPosition); yield from $this->parseAsResourcesOrIdentifiers($rootPosition, $data); - } elseif ($data === null) { + } elseif (null === $data) { yield $this->createDocumentDataIsNull($rootPosition); } else { throw new InvalidArgumentException(_(static::MSG_NO_SCHEMA_FOUND, \get_class($data))); } } + protected function getContext(): EditableContextInterface + { + return $this->context; + } + + protected function getNormalizedPaths(): array + { + \assert(null !== $this->paths, _(static::MSG_PATHS_HAVE_NOT_BEEN_NORMALIZED_YET)); + + return $this->paths; + } + + protected function isPathRequested(string $path): bool + { + return isset($this->paths[$path]); + } + /** - * @param PositionInterface $position - * @param iterable $dataOrIds - * * @see ResourceInterface * @see IdentifierInterface - * - * @return iterable */ private function parseAsResourcesOrIdentifiers( PositionInterface $position, iterable $dataOrIds ): iterable { foreach ($dataOrIds as $dataOrId) { - if ($this->schemaContainer->hasSchema($dataOrId) === true) { + if (true === $this->schemaContainer->hasSchema($dataOrId)) { yield from $this->parseAsResource($position, $dataOrId); continue; @@ -147,47 +154,15 @@ private function parseAsResourcesOrIdentifiers( } /** - * @return EditableContextInterface - */ - protected function getContext(): EditableContextInterface - { - return $this->context; - } - - /** - * @return array - */ - protected function getNormalizedPaths(): array - { - \assert($this->paths !== null, _(static::MSG_PATHS_HAVE_NOT_BEEN_NORMALIZED_YET)); - - return $this->paths; - } - - /** - * @param string $path - * - * @return bool - */ - protected function isPathRequested(string $path): bool - { - return isset($this->paths[$path]); - } - - /** - * @param PositionInterface $position - * @param mixed $data + * @param mixed $data * * @see ResourceInterface - * - * @return iterable - * */ private function parseAsResource( PositionInterface $position, $data ): iterable { - \assert($this->schemaContainer->hasSchema($data) === true); + \assert(true === $this->schemaContainer->hasSchema($data)); $resource = $this->factory->createParsedResource( $this->getContext(), @@ -200,10 +175,6 @@ private function parseAsResource( } /** - * @param ResourceInterface $resource - * - * @return iterable - * * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ private function parseResource(ResourceInterface $resource): iterable @@ -214,12 +185,12 @@ private function parseResource(ResourceInterface $resource): iterable // for deeper levels it's not needed as they go to `included` section and it must have no more // than one instance of the same resource. - if ($seenBefore === false || $resource->getPosition()->getLevel() <= ParserInterface::ROOT_LEVEL) { + if (false === $seenBefore || $resource->getPosition()->getLevel() <= ParserInterface::ROOT_LEVEL) { yield $resource; } // parse relationships only for resources not seen before (prevents infinite loop for circular references) - if ($seenBefore === false) { + if (false === $seenBefore) { // remember by id and type $this->resourcesTracker[$resource->getId()][$resource->getType()] = true; @@ -229,13 +200,13 @@ private function parseResource(ResourceInterface $resource): iterable $isShouldParse = $this->isPathRequested($relationship->getPosition()->getPath()); - if ($isShouldParse === true && $relationship->hasData() === true) { + if (true === $isShouldParse && true === $relationship->hasData()) { $relData = $relationship->getData(); - if ($relData->isResource() === true) { + if (true === $relData->isResource()) { yield from $this->parseResource($relData->getResource()); continue; - } elseif ($relData->isCollection() === true) { + } elseif (true === $relData->isCollection()) { foreach ($relData->getResources() as $relResource) { \assert($relResource instanceof ResourceInterface || $relResource instanceof IdentifierInterface); @@ -253,34 +224,23 @@ private function parseResource(ResourceInterface $resource): iterable } } - /** - * @param PositionInterface $position - * @param SchemaIdentifierInterface $identifier - * - * @return IdentifierInterface - */ private function parseAsIdentifier( PositionInterface $position, SchemaIdentifierInterface $identifier ): IdentifierInterface { - return new class ($position, $identifier) implements IdentifierInterface - { + return new class($position, $identifier) implements IdentifierInterface { private \Neomerx\JsonApi\Contracts\Schema\PositionInterface $position; private SchemaIdentifierInterface $identifier; - /** - * @param PositionInterface $position - * @param SchemaIdentifierInterface $identifier - */ public function __construct(PositionInterface $position, SchemaIdentifierInterface $identifier) { - $this->position = $position; + $this->position = $position; $this->identifier = $identifier; } /** - * @inheritdoc + * {@inheritdoc} */ public function getPosition(): PositionInterface { @@ -288,7 +248,7 @@ public function getPosition(): PositionInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function getId(): ?string { @@ -296,7 +256,7 @@ public function getId(): ?string } /** - * @inheritdoc + * {@inheritdoc} */ public function getType(): string { @@ -304,7 +264,7 @@ public function getType(): string } /** - * @inheritdoc + * {@inheritdoc} */ public function hasIdentifierMeta(): bool { @@ -312,7 +272,7 @@ public function hasIdentifierMeta(): bool } /** - * @inheritdoc + * {@inheritdoc} */ public function getIdentifierMeta() { @@ -321,86 +281,49 @@ public function getIdentifierMeta() }; } - /** - * @param PositionInterface $position - * - * @return DocumentDataInterface - */ private function createDocumentDataIsCollection(PositionInterface $position): DocumentDataInterface { return $this->createParsedDocumentData($position, true, false); } - /** - * @param PositionInterface $position - * - * @return DocumentDataInterface - */ private function createDocumentDataIsNull(PositionInterface $position): DocumentDataInterface { return $this->createParsedDocumentData($position, false, true); } - /** - * @param PositionInterface $position - * - * @return DocumentDataInterface - */ private function createDocumentDataIsResource(PositionInterface $position): DocumentDataInterface { return $this->createParsedDocumentData($position, false, false); } - /** - * @param PositionInterface $position - * - * @return DocumentDataInterface - */ private function createDocumentDataIsIdentifier(PositionInterface $position): DocumentDataInterface { return $this->createParsedDocumentData($position, false, false); } - /** - * @param PositionInterface $position - * @param bool $isCollection - * @param bool $isNull - * - * @return DocumentDataInterface - */ private function createParsedDocumentData( PositionInterface $position, bool $isCollection, bool $isNull ): DocumentDataInterface { - return new class ( - $position, - $isCollection, - $isNull - ) implements DocumentDataInterface - { + return new class($position, $isCollection, $isNull) implements DocumentDataInterface { private \Neomerx\JsonApi\Contracts\Schema\PositionInterface $position; private bool $isCollection; private bool $isNull; - /** - * @param PositionInterface $position - * @param bool $isCollection - * @param bool $isNull - */ public function __construct( PositionInterface $position, bool $isCollection, bool $isNull ) { - $this->position = $position; + $this->position = $position; $this->isCollection = $isCollection; - $this->isNull = $isNull; + $this->isNull = $isNull; } /** - * @inheritdoc + * {@inheritdoc} */ public function getPosition(): PositionInterface { @@ -408,7 +331,7 @@ public function getPosition(): PositionInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function isCollection(): bool { @@ -416,7 +339,7 @@ public function isCollection(): bool } /** - * @inheritdoc + * {@inheritdoc} */ public function isNull(): bool { @@ -425,11 +348,6 @@ public function isNull(): bool }; } - /** - * @param iterable $paths - * - * @return array - */ private function normalizePaths(iterable $paths): array { $separator = DocumentInterface::PATH_SEPARATOR; @@ -439,7 +357,7 @@ private function normalizePaths(iterable $paths): array foreach ($paths as $path) { $curPath = ''; foreach (\explode($separator, $path) as $pathPart) { - $curPath = empty($curPath) === true ? $pathPart : $curPath . $separator . $pathPart; + $curPath = true === empty($curPath) ? $pathPart : $curPath . $separator . $pathPart; $normalizedPaths[$curPath] = true; } } diff --git a/src/Parser/RelationshipData/BaseRelationshipData.php b/src/Parser/RelationshipData/BaseRelationshipData.php index 5d01d55..17c39d2 100644 --- a/src/Parser/RelationshipData/BaseRelationshipData.php +++ b/src/Parser/RelationshipData/BaseRelationshipData.php @@ -1,8 +1,10 @@ -factory = $factory; + $this->factory = $factory; $this->schemaContainer = $schemaContainer; - $this->context = $context; - $this->position = $position; + $this->context = $context; + $this->position = $position; } /** * @param mixed $resource - * - * @return ResourceInterface */ protected function createParsedResource($resource): ResourceInterface { @@ -79,8 +70,6 @@ protected function createParsedResource($resource): ResourceInterface } /** - * @param SchemaIdentifierInterface $identifier - * * @return ResourceInterface */ protected function createParsedIdentifier(SchemaIdentifierInterface $identifier): ParserIdentifierInterface diff --git a/src/Parser/RelationshipData/ParseRelationshipDataTrait.php b/src/Parser/RelationshipData/ParseRelationshipDataTrait.php index 28ff12a..44d3b94 100644 --- a/src/Parser/RelationshipData/ParseRelationshipDataTrait.php +++ b/src/Parser/RelationshipData/ParseRelationshipDataTrait.php @@ -1,8 +1,10 @@ -parseData( + $relationshipData = true === $hasData ? $this->parseData( $factory, $container, $context, @@ -88,13 +78,7 @@ private function parseRelationshipData( } /** - * @param FactoryInterface $factory - * @param SchemaContainerInterface $container - * @param EditableContextInterface $context - * @param PositionInterface $position - * @param mixed $data - * - * @return RelationshipDataInterface + * @param mixed $data */ private function parseData( FactoryInterface $factory, @@ -104,15 +88,15 @@ private function parseData( $data ): RelationshipDataInterface { // support if data is callable (e.g. a closure used to postpone actual data reading) - if (\is_callable($data) === true) { + if (true === \is_callable($data)) { $data = \call_user_func($data); } - if ($container->hasSchema($data) === true) { + if (true === $container->hasSchema($data)) { return $factory->createRelationshipDataIsResource($container, $context, $position, $data); } elseif ($data instanceof IdentifierInterface) { return $factory->createRelationshipDataIsIdentifier($container, $context, $position, $data); - } elseif (\is_array($data) === true) { + } elseif (true === \is_array($data)) { return $factory->createRelationshipDataIsCollection($container, $context, $position, $data); } elseif ($data instanceof Traversable) { return $factory->createRelationshipDataIsCollection( @@ -121,7 +105,7 @@ private function parseData( $position, $data instanceof IteratorAggregate ? $data->getIterator() : $data ); - } elseif ($data === null) { + } elseif (null === $data) { return $factory->createRelationshipDataIsNull(); } diff --git a/src/Parser/RelationshipData/ParseRelationshipLinksTrait.php b/src/Parser/RelationshipData/ParseRelationshipLinksTrait.php index 58f5652..8d6a769 100644 --- a/src/Parser/RelationshipData/ParseRelationshipLinksTrait.php +++ b/src/Parser/RelationshipData/ParseRelationshipLinksTrait.php @@ -1,8 +1,10 @@ -isAddSelfLinkInRelationshipByDefault($name); $addRelatedLink = $description[SchemaInterface::RELATIONSHIP_LINKS_RELATED] ?? $parentSchema->isAddRelatedLinkInRelationshipByDefault($name); - \assert(\is_bool($addSelfLink) === true || $addSelfLink instanceof LinkInterface); - \assert(\is_bool($addRelatedLink) === true || $addRelatedLink instanceof LinkInterface); + \assert(true === \is_bool($addSelfLink) || $addSelfLink instanceof LinkInterface); + \assert(true === \is_bool($addRelatedLink) || $addRelatedLink instanceof LinkInterface); $schemaLinks = $description[SchemaInterface::RELATIONSHIP_LINKS] ?? []; \assert(\is_array($schemaLinks)); // if `self` or `related` link was given as LinkInterface merge it with the other links $extraSchemaLinks = null; - if (\is_bool($addSelfLink) === false) { + if (false === \is_bool($addSelfLink)) { $extraSchemaLinks[LinkInterface::SELF] = $addSelfLink; - $addSelfLink = false; + $addSelfLink = false; } - if (\is_bool($addRelatedLink) === false) { + if (false === \is_bool($addRelatedLink)) { $extraSchemaLinks[LinkInterface::RELATED] = $addRelatedLink; - $addRelatedLink = false; + $addRelatedLink = false; } - if (empty($extraSchemaLinks) === false) { + if (false === empty($extraSchemaLinks)) { // IDE do not understand it's defined without he line below \assert(isset($extraSchemaLinks)); $schemaLinks = \array_merge($extraSchemaLinks, $schemaLinks); unset($extraSchemaLinks); } - \assert(\is_bool($addSelfLink) === true && \is_bool($addRelatedLink) === true); + \assert(true === \is_bool($addSelfLink) && true === \is_bool($addRelatedLink)); - $hasLinks = $addSelfLink === true || $addRelatedLink === true || empty($schemaLinks) === false; - $links = $hasLinks === true ? + $hasLinks = true === $addSelfLink || true === $addRelatedLink || false === empty($schemaLinks); + $links = true === $hasLinks ? $this->parseLinks($parentSchema, $parentData, $name, $schemaLinks, $addSelfLink, $addRelatedLink) : null; return [$hasLinks, $links]; } /** - * @param SchemaInterface $parentSchema - * @param mixed $parentData - * @param string $relationshipName - * @param iterable $schemaLinks - * @param bool $addSelfLink - * @param bool $addRelatedLink - * - * @return iterable + * @param mixed $parentData */ private function parseLinks( SchemaInterface $parentSchema, @@ -95,30 +82,30 @@ private function parseLinks( bool $addSelfLink, bool $addRelatedLink ): iterable { - $gotSelf = false; + $gotSelf = false; $gotRelated = false; foreach ($schemaLinks as $name => $link) { \assert($link instanceof LinkInterface); - if ($name === LinkInterface::SELF) { - \assert($gotSelf === false); - $gotSelf = true; + if (LinkInterface::SELF === $name) { + \assert(false === $gotSelf); + $gotSelf = true; $addSelfLink = false; - } elseif ($name === LinkInterface::RELATED) { - \assert($gotRelated === false); - $gotRelated = true; + } elseif (LinkInterface::RELATED === $name) { + \assert(false === $gotRelated); + $gotRelated = true; $addRelatedLink = false; } yield $name => $link; } - if ($addSelfLink === true) { + if (true === $addSelfLink) { $link = $parentSchema->getRelationshipSelfLink($parentData, $relationshipName); yield LinkInterface::SELF => $link; $gotSelf = true; } - if ($addRelatedLink === true) { + if (true === $addRelatedLink) { $link = $parentSchema->getRelationshipRelatedLink($parentData, $relationshipName); yield LinkInterface::RELATED => $link; $gotRelated = true; diff --git a/src/Parser/RelationshipData/RelationshipDataIsCollection.php b/src/Parser/RelationshipData/RelationshipDataIsCollection.php index a427ac5..9990ed7 100644 --- a/src/Parser/RelationshipData/RelationshipDataIsCollection.php +++ b/src/Parser/RelationshipData/RelationshipDataIsCollection.php @@ -1,8 +1,10 @@ -parsedResources === null) { + if (null === $this->parsedResources) { foreach ($this->resources as $resourceOrIdentifier) { - $parsedResource = $resourceOrIdentifier instanceof SchemaIdentifierInterface ? + $parsedResource = $resourceOrIdentifier instanceof SchemaIdentifierInterface ? $this->createParsedIdentifier($resourceOrIdentifier) : $this->createParsedResource($resourceOrIdentifier); $this->parsedResources[] = $parsedResource; diff --git a/src/Parser/RelationshipData/RelationshipDataIsIdentifier.php b/src/Parser/RelationshipData/RelationshipDataIsIdentifier.php index 4a2b6fc..2f51842 100644 --- a/src/Parser/RelationshipData/RelationshipDataIsIdentifier.php +++ b/src/Parser/RelationshipData/RelationshipDataIsIdentifier.php @@ -1,8 +1,10 @@ -parsedIdentifier === null) { + if (null === $this->parsedIdentifier) { $this->parsedIdentifier = $this->createParsedIdentifier($this->identifier); } @@ -108,7 +100,7 @@ public function getIdentifier(): ParserIdentifierInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function getIdentifiers(): iterable { @@ -116,7 +108,7 @@ public function getIdentifiers(): iterable } /** - * @inheritdoc + * {@inheritdoc} */ public function getResource(): ResourceInterface { @@ -124,7 +116,7 @@ public function getResource(): ResourceInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function getResources(): iterable { diff --git a/src/Parser/RelationshipData/RelationshipDataIsNull.php b/src/Parser/RelationshipData/RelationshipDataIsNull.php index 7dc7cf9..e540cd1 100644 --- a/src/Parser/RelationshipData/RelationshipDataIsNull.php +++ b/src/Parser/RelationshipData/RelationshipDataIsNull.php @@ -1,8 +1,10 @@ -parsedResource === null) { + if (null === $this->parsedResource) { $this->parsedResource = $this->createParsedResource($this->resource); } @@ -123,7 +118,7 @@ public function getResource(): ResourceInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function getResources(): iterable { diff --git a/src/Representation/BaseWriter.php b/src/Representation/BaseWriter.php index 414855e..93d8bd8 100644 --- a/src/Representation/BaseWriter.php +++ b/src/Representation/BaseWriter.php @@ -1,8 +1,10 @@ -isDataAnArray === false); - \assert(\array_key_exists(DocumentInterface::KEYWORD_DATA, $this->data) === false); + \assert(false === $this->isDataAnArray); + \assert(false === \array_key_exists(DocumentInterface::KEYWORD_DATA, $this->data)); $this->data[DocumentInterface::KEYWORD_DATA] = []; - $this->isDataAnArray = true; + $this->isDataAnArray = true; return $this; } /** - * @inheritdoc + * {@inheritdoc} */ public function getDocument(): array { @@ -68,11 +67,11 @@ public function getDocument(): array } /** - * @inheritdoc + * {@inheritdoc} */ public function setMeta($meta): BaseWriterInterface { - \assert(\is_resource($meta) === false); + \assert(false === \is_resource($meta)); $this->data[DocumentInterface::KEYWORD_META] = $meta; @@ -80,7 +79,7 @@ public function setMeta($meta): BaseWriterInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function setJsonApiVersion(string $version): BaseWriterInterface { @@ -90,11 +89,11 @@ public function setJsonApiVersion(string $version): BaseWriterInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function setJsonApiMeta($meta): BaseWriterInterface { - \assert(\is_resource($meta) === false); + \assert(false === \is_resource($meta)); $this->data[DocumentInterface::KEYWORD_JSON_API][DocumentInterface::KEYWORD_META] = $meta; @@ -102,7 +101,7 @@ public function setJsonApiMeta($meta): BaseWriterInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function setUrlPrefix(string $prefix): BaseWriterInterface { @@ -112,7 +111,7 @@ public function setUrlPrefix(string $prefix): BaseWriterInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function setLinks(iterable $links): BaseWriterInterface { @@ -121,7 +120,7 @@ public function setLinks(iterable $links): BaseWriterInterface $links ); - if (empty($representation) === false) { + if (false === empty($representation)) { $this->data[DocumentInterface::KEYWORD_LINKS] = $representation; } @@ -129,7 +128,7 @@ public function setLinks(iterable $links): BaseWriterInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function setProfile(iterable $links): BaseWriterInterface { @@ -138,72 +137,51 @@ public function setProfile(iterable $links): BaseWriterInterface $links ); - if (empty($representation) === false) { + if (false === empty($representation)) { $this->data[DocumentInterface::KEYWORD_LINKS][DocumentInterface::KEYWORD_PROFILE] = $representation; } return $this; } - /** - * @return void - */ protected function reset(): void { - $this->data = []; - $this->urlPrefix = ''; + $this->data = []; + $this->urlPrefix = ''; $this->isDataAnArray = false; } - /** - * @return string - */ protected function getUrlPrefix(): string { return $this->urlPrefix; } - /** - * @param null|string $prefix - * @param iterable $links - * - * @return array - */ protected function getLinksRepresentation(?string $prefix, iterable $links): array { $result = []; foreach ($links as $name => $link) { \assert($link instanceof LinkInterface); - $result[$name] = $link->canBeShownAsString() === true ? + $result[$name] = true === $link->canBeShownAsString() ? $link->getStringRepresentation($prefix) : $link->getArrayRepresentation($prefix); } return $result; } - /** - * @param null|string $prefix - * @param iterable $links - * - * @return array - */ protected function getLinksListRepresentation(?string $prefix, iterable $links): array { $result = []; foreach ($links as $link) { \assert($link instanceof BaseLinkInterface); - $result[] = $link->canBeShownAsString() === true ? + $result[] = true === $link->canBeShownAsString() ? $link->getStringRepresentation($prefix) : $link->getArrayRepresentation($prefix); } return $result; } - /** - * @return bool - */ protected function isDataAnArray(): bool { return $this->isDataAnArray; diff --git a/src/Representation/DocumentWriter.php b/src/Representation/DocumentWriter.php index 78c4e9f..d7639f6 100644 --- a/src/Representation/DocumentWriter.php +++ b/src/Representation/DocumentWriter.php @@ -1,8 +1,10 @@ -data[DocumentInterface::KEYWORD_DATA]) === false); + \assert(false === isset($this->data[DocumentInterface::KEYWORD_DATA])); $this->data[DocumentInterface::KEYWORD_DATA] = null; return $this; } /** - * @inheritdoc + * {@inheritdoc} */ public function addIdentifierToData(IdentifierInterface $identifier): DocumentWriterInterface { @@ -59,7 +58,7 @@ public function addIdentifierToData(IdentifierInterface $identifier): DocumentWr } /** - * @inheritdoc + * {@inheritdoc} */ public function addResourceToData( ResourceInterface $resource, @@ -71,7 +70,7 @@ public function addResourceToData( } /** - * @inheritdoc + * {@inheritdoc} */ public function addResourceToIncluded( ResourceInterface $resource, @@ -84,7 +83,7 @@ public function addResourceToIncluded( // // The spec seems to be OK with it. - if ($this->hasNotBeenAdded($resource) === true) { + if (true === $this->hasNotBeenAdded($resource)) { $this->registerResource($resource); $this->addToIncluded($this->getResourceRepresentation($resource, $filter)); } @@ -93,7 +92,7 @@ public function addResourceToIncluded( } /** - * @inheritdoc + * {@inheritdoc} */ protected function reset(): void { @@ -104,21 +103,12 @@ protected function reset(): void /** * If full resource has not been added yet either to includes section. - * - * @param ResourceInterface $resource - * - * @return bool */ protected function hasNotBeenAdded(ResourceInterface $resource): bool { - return isset($this->addedResources[$resource->getId()][$resource->getType()]) === false; + return false === isset($this->addedResources[$resource->getId()][$resource->getType()]); } - /** - * @param ResourceInterface $resource - * - * @return void - */ protected function registerResource(ResourceInterface $resource): void { \assert($this->hasNotBeenAdded($resource)); @@ -126,48 +116,33 @@ protected function registerResource(ResourceInterface $resource): void $this->addedResources[$resource->getId()][$resource->getType()] = true; } - /** - * @param IdentifierInterface $identifier - * - * @return array - */ protected function getIdentifierRepresentation(IdentifierInterface $identifier): array { // it's odd not to have actual ID for identifier (which is OK for newly created resource). - \assert($identifier->getId() !== null); + \assert(null !== $identifier->getId()); - return $identifier->hasIdentifierMeta() === false ? [ + return false === $identifier->hasIdentifierMeta() ? [ DocumentInterface::KEYWORD_TYPE => $identifier->getType(), - DocumentInterface::KEYWORD_ID => $identifier->getId(), + DocumentInterface::KEYWORD_ID => $identifier->getId(), ] : [ DocumentInterface::KEYWORD_TYPE => $identifier->getType(), - DocumentInterface::KEYWORD_ID => $identifier->getId(), + DocumentInterface::KEYWORD_ID => $identifier->getId(), DocumentInterface::KEYWORD_META => $identifier->getIdentifierMeta(), ]; } - /** - * @param ResourceInterface $resource - * - * @return array - */ protected function getIdentifierRepresentationFromResource(ResourceInterface $resource): array { - return $resource->hasIdentifierMeta() === false ? [ + return false === $resource->hasIdentifierMeta() ? [ DocumentInterface::KEYWORD_TYPE => $resource->getType(), - DocumentInterface::KEYWORD_ID => $resource->getId(), + DocumentInterface::KEYWORD_ID => $resource->getId(), ] : [ DocumentInterface::KEYWORD_TYPE => $resource->getType(), - DocumentInterface::KEYWORD_ID => $resource->getId(), + DocumentInterface::KEYWORD_ID => $resource->getId(), DocumentInterface::KEYWORD_META => $resource->getIdentifierMeta(), ]; } - /** - * @param iterable $attributes - * - * @return array - */ protected function getAttributesRepresentation(iterable $attributes): array { $representation = []; @@ -178,16 +153,11 @@ protected function getAttributesRepresentation(iterable $attributes): array return $representation; } - /** - * @param iterable $relationships - * - * @return array - */ protected function getRelationshipsRepresentation(iterable $relationships): array { $representation = []; foreach ($relationships as $name => $relationship) { - \assert(\is_string($name) === true && empty($name) === false); + \assert(true === \is_string($name) && false === empty($name)); \assert($relationship instanceof RelationshipInterface); $representation[$name] = $this->getRelationshipRepresentation($relationship); } @@ -195,45 +165,35 @@ protected function getRelationshipsRepresentation(iterable $relationships): arra return $representation; } - /** - * @param RelationshipInterface $relationship - * - * @return array - */ protected function getRelationshipRepresentation(RelationshipInterface $relationship): array { $representation = []; - if ($relationship->hasLinks() === true) { + if (true === $relationship->hasLinks()) { $representation[DocumentInterface::KEYWORD_LINKS] = $this->getLinksRepresentation($this->getUrlPrefix(), $relationship->getLinks()); } - if ($relationship->hasData() === true) { + if (true === $relationship->hasData()) { $representation[DocumentInterface::KEYWORD_DATA] = $this->getRelationshipDataRepresentation( $relationship->getData() ); } - if ($relationship->hasMeta() === true) { + if (true === $relationship->hasMeta()) { $representation[DocumentInterface::KEYWORD_META] = $relationship->getMeta(); } return $representation; } - /** - * @param RelationshipDataInterface $data - * - * @return array|null - */ protected function getRelationshipDataRepresentation(RelationshipDataInterface $data): ?array { - if ($data->isResource() === true) { + if (true === $data->isResource()) { return $this->getIdentifierRepresentationFromResource($data->getResource()); - } elseif ($data->isIdentifier() === true) { + } elseif (true === $data->isIdentifier()) { return $this->getIdentifierRepresentation($data->getIdentifier()); - } elseif ($data->isCollection() === true) { + } elseif (true === $data->isCollection()) { $representation = []; foreach ($data->getIdentifiers() as $identifier) { \assert($identifier instanceof IdentifierInterface); @@ -243,17 +203,12 @@ protected function getRelationshipDataRepresentation(RelationshipDataInterface $ return $representation; } - \assert($data->isNull() === true); + \assert(true === $data->isNull()); return null; } /** - * @param ResourceInterface $resource - * @param FieldSetFilterInterface $filter - * - * @return array - * * @SuppressWarnings(PHPMD.IfStatementAssignment) */ protected function getResourceRepresentation(ResourceInterface $resource, FieldSetFilterInterface $filter): array @@ -267,9 +222,9 @@ protected function getResourceRepresentation(ResourceInterface $resource, FieldS } $attributes = $this->getAttributesRepresentation($filter->getAttributes($resource)); - if (empty($attributes) === false) { + if (false === empty($attributes)) { \assert( - \json_encode($attributes, JSON_THROW_ON_ERROR) !== false, + false !== \json_encode($attributes, JSON_THROW_ON_ERROR), 'Attributes for resource type `' . $resource->getType() . '` cannot be converted into JSON. Please check its Schema returns valid data.' ); @@ -277,29 +232,29 @@ protected function getResourceRepresentation(ResourceInterface $resource, FieldS } $relationships = $this->getRelationshipsRepresentation($filter->getRelationships($resource)); - if (empty($relationships) === false) { + if (false === empty($relationships)) { \assert( - \json_encode($relationships, JSON_THROW_ON_ERROR) !== false, + false !== \json_encode($relationships, JSON_THROW_ON_ERROR), 'Relationships for resource type `' . $resource->getType() . '` cannot be converted into JSON. Please check its Schema returns valid data.' ); $representation[DocumentInterface::KEYWORD_RELATIONSHIPS] = $relationships; } - if ($resource->hasLinks() === true) { + if (true === $resource->hasLinks()) { $links = $this->getLinksRepresentation($this->getUrlPrefix(), $resource->getLinks()); \assert( - \json_encode($links, JSON_THROW_ON_ERROR) !== false, + false !== \json_encode($links, JSON_THROW_ON_ERROR), 'Links for resource type `' . $resource->getType() . '` cannot be converted into JSON. Please check its Schema returns valid data.' ); $representation[DocumentInterface::KEYWORD_LINKS] = $links; } - if ($resource->hasResourceMeta() === true) { + if (true === $resource->hasResourceMeta()) { $meta = $resource->getResourceMeta(); \assert( - \json_encode($meta, JSON_THROW_ON_ERROR) !== false, + false !== \json_encode($meta, JSON_THROW_ON_ERROR), 'Meta for resource type `' . $resource->getType() . '` cannot be converted into JSON. Please check its Schema returns valid data.' ); @@ -309,29 +264,19 @@ protected function getResourceRepresentation(ResourceInterface $resource, FieldS return $representation; } - /** - * @param array $representation - * - * @return void - */ private function addToData(array $representation): void { - if ($this->isDataAnArray() === true) { + if (true === $this->isDataAnArray()) { $this->data[DocumentInterface::KEYWORD_DATA][] = $representation; return; } // check data has not been added yet - \assert(\array_key_exists(DocumentInterface::KEYWORD_DATA, $this->data) === false); + \assert(false === \array_key_exists(DocumentInterface::KEYWORD_DATA, $this->data)); $this->data[DocumentInterface::KEYWORD_DATA] = $representation; } - /** - * @param array $representation - * - * @return void - */ private function addToIncluded(array $representation): void { $this->data[DocumentInterface::KEYWORD_INCLUDED][] = $representation; diff --git a/src/Representation/ErrorWriter.php b/src/Representation/ErrorWriter.php index 163b310..bd19549 100644 --- a/src/Representation/ErrorWriter.php +++ b/src/Representation/ErrorWriter.php @@ -1,8 +1,10 @@ - $error->getId(), - DocumentInterface::KEYWORD_LINKS => $this->getErrorLinksRepresentation($error), + DocumentInterface::KEYWORD_ERRORS_ID => $error->getId(), + DocumentInterface::KEYWORD_LINKS => $this->getErrorLinksRepresentation($error), DocumentInterface::KEYWORD_ERRORS_STATUS => $error->getStatus(), - DocumentInterface::KEYWORD_ERRORS_CODE => $error->getCode(), - DocumentInterface::KEYWORD_ERRORS_TITLE => $error->getTitle(), + DocumentInterface::KEYWORD_ERRORS_CODE => $error->getCode(), + DocumentInterface::KEYWORD_ERRORS_TITLE => $error->getTitle(), DocumentInterface::KEYWORD_ERRORS_DETAIL => $error->getDetail(), DocumentInterface::KEYWORD_ERRORS_SOURCE => $error->getSource(), ]); - if ($error->hasMeta() === true) { + if (true === $error->hasMeta()) { $representation[DocumentInterface::KEYWORD_ERRORS_META] = $error->getMeta(); } // There is a special case when error representation is an empty array // Due to further json transform it must be an object otherwise it will be an empty array in json - $representation = empty($representation) === false ? $representation : (object)$representation; + $representation = false === empty($representation) ? $representation : (object) $representation; $this->data[DocumentInterface::KEYWORD_ERRORS][] = $representation; @@ -66,10 +65,6 @@ public function addError(ErrorInterface $error): ErrorWriterInterface } /** - * @param ErrorInterface $error - * - * @return array|null - * * @SuppressWarnings(PHPMD.IfStatementAssignment) */ private function getErrorLinksRepresentation(ErrorInterface $error): ?array diff --git a/src/Representation/FieldSetFilter.php b/src/Representation/FieldSetFilter.php index e734848..b1e5999 100644 --- a/src/Representation/FieldSetFilter.php +++ b/src/Representation/FieldSetFilter.php @@ -1,8 +1,10 @@ -fieldSets = []; foreach ($fieldSets as $type => $fields) { - \assert(\is_string($type) === true && empty($type) === false); - \assert(\is_iterable($fields) === true); + \assert(true === \is_string($type) && false === empty($type)); + \assert(true === \is_iterable($fields)); $this->fieldSets[$type] = []; foreach ($fields as $field) { - \assert(\is_string($field) === true && empty($field) === false); - \assert(isset($this->fieldSets[$type][$field]) === false); + \assert(true === \is_string($field) && false === empty($field)); + \assert(false === isset($this->fieldSets[$type][$field])); $this->fieldSets[$type][$field] = true; } @@ -52,7 +51,7 @@ public function __construct(array $fieldSets) } /** - * @inheritdoc + * {@inheritdoc} */ public function getAttributes(ResourceInterface $resource): iterable { @@ -60,7 +59,7 @@ public function getAttributes(ResourceInterface $resource): iterable } /** - * @inheritdoc + * {@inheritdoc} */ public function getRelationships(ResourceInterface $resource): iterable { @@ -68,49 +67,33 @@ public function getRelationships(ResourceInterface $resource): iterable } /** - * @inheritdoc + * {@inheritdoc} */ public function shouldOutputRelationship(PositionInterface $position): bool { $parentType = $position->getParentType(); - if ($this->hasFilter($parentType) === true) { + if (true === $this->hasFilter($parentType)) { return isset($this->getAllowedFields($parentType)[$position->getParentRelationship()]); } return true; } - /** - * @param string $type - * - * @return bool - */ protected function hasFilter(string $type): bool { - return isset($this->fieldSets[$type]) === true; + return true === isset($this->fieldSets[$type]); } - /** - * @param string $type - * - * @return array - */ protected function getAllowedFields(string $type): array { - \assert($this->hasFilter($type) === true); + \assert(true === $this->hasFilter($type)); return $this->fieldSets[$type]; } - /** - * @param string $type - * @param iterable $fields - * - * @return iterable - */ protected function filterFields(string $type, iterable $fields): iterable { - if ($this->hasFilter($type) === false) { + if (false === $this->hasFilter($type)) { yield from $fields; return; @@ -118,7 +101,7 @@ protected function filterFields(string $type, iterable $fields): iterable $allowedFields = $this->getAllowedFields($type); foreach ($fields as $name => $value) { - if (isset($allowedFields[$name]) === true) { + if (true === isset($allowedFields[$name])) { yield $name => $value; } } diff --git a/src/Schema/BaseSchema.php b/src/Schema/BaseSchema.php index 488e5d2..b7235ff 100644 --- a/src/Schema/BaseSchema.php +++ b/src/Schema/BaseSchema.php @@ -1,8 +1,10 @@ -factory = $factory; } /** - * @inheritdoc + * {@inheritdoc} */ public function getSelfLink($resource): LinkInterface { @@ -50,7 +46,7 @@ public function getSelfLink($resource): LinkInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function getLinks($resource): iterable { @@ -62,7 +58,7 @@ public function getLinks($resource): iterable } /** - * @inheritdoc + * {@inheritdoc} */ public function getRelationshipSelfLink($resource, string $name): LinkInterface { @@ -74,7 +70,7 @@ public function getRelationshipSelfLink($resource, string $name): LinkInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function getRelationshipRelatedLink($resource, string $name): LinkInterface { @@ -86,7 +82,7 @@ public function getRelationshipRelatedLink($resource, string $name): LinkInterfa } /** - * @inheritdoc + * {@inheritdoc} */ public function hasIdentifierMeta($resource): bool { @@ -94,7 +90,7 @@ public function hasIdentifierMeta($resource): bool } /** - * @inheritdoc + * {@inheritdoc} */ public function getIdentifierMeta($resource) { @@ -103,7 +99,7 @@ public function getIdentifierMeta($resource) } /** - * @inheritdoc + * {@inheritdoc} */ public function hasResourceMeta($resource): bool { @@ -111,7 +107,7 @@ public function hasResourceMeta($resource): bool } /** - * @inheritdoc + * {@inheritdoc} */ public function getResourceMeta($resource) { @@ -120,7 +116,7 @@ public function getResourceMeta($resource) } /** - * @inheritdoc + * {@inheritdoc} */ public function isAddSelfLinkInRelationshipByDefault(string $relationshipName): bool { @@ -128,16 +124,13 @@ public function isAddSelfLinkInRelationshipByDefault(string $relationshipName): } /** - * @inheritdoc + * {@inheritdoc} */ public function isAddRelatedLinkInRelationshipByDefault(string $relationshipName): bool { return true; } - /** - * @return FactoryInterface - */ protected function getFactory(): FactoryInterface { return $this->factory; @@ -145,12 +138,10 @@ protected function getFactory(): FactoryInterface /** * Get resources sub-URL. - * - * @return string */ protected function getResourcesSubUrl(): string { - if ($this->subUrl === null) { + if (null === $this->subUrl) { $this->subUrl = '/' . $this->getType(); } @@ -159,8 +150,6 @@ protected function getResourcesSubUrl(): string /** * @param mixed $resource - * - * @return string */ protected function getSelfSubUrl($resource): string { diff --git a/src/Schema/Error.php b/src/Schema/Error.php index 0b1fdd9..9fae603 100644 --- a/src/Schema/Error.php +++ b/src/Schema/Error.php @@ -1,8 +1,10 @@ -index = $index; @@ -124,7 +114,7 @@ public function setId($index): self } /** - * @inheritdoc + * {@inheritdoc} */ public function getLinks(): ?iterable { @@ -132,7 +122,7 @@ public function getLinks(): ?iterable } /** - * @inheritdoc + * {@inheritdoc} */ public function getTypeLinks(): ?iterable { @@ -140,16 +130,11 @@ public function getTypeLinks(): ?iterable } /** - * @param string $name - * @param LinkInterface|null $link - * - * @return self - * * @SuppressWarnings(PHPMD.ElseExpression) */ public function setLink(string $name, ?LinkInterface $link): self { - if ($link !== null) { + if (null !== $link) { $this->links[$name] = $link; } else { unset($this->links[$name]); @@ -158,11 +143,6 @@ public function setLink(string $name, ?LinkInterface $link): self return $this; } - /** - * @param iterable|null $typeLinks - * - * @return self - */ public function setTypeLinks(?iterable $typeLinks): self { $this->typeLinks = $typeLinks; @@ -171,18 +151,13 @@ public function setTypeLinks(?iterable $typeLinks): self } /** - * @inheritdoc + * {@inheritdoc} */ public function getStatus(): ?string { return $this->status; } - /** - * @param string|null $status - * - * @return self - */ public function setStatus(?string $status): self { $this->status = $status; @@ -191,18 +166,13 @@ public function setStatus(?string $status): self } /** - * @inheritdoc + * {@inheritdoc} */ public function getCode(): ?string { return $this->code; } - /** - * @param string|null $code - * - * @return self - */ public function setCode(?string $code): self { $this->code = $code; @@ -211,18 +181,13 @@ public function setCode(?string $code): self } /** - * @inheritdoc + * {@inheritdoc} */ public function getTitle(): ?string { return $this->title; } - /** - * @param null|string $title - * - * @return self - */ public function setTitle(?string $title): self { $this->title = $title; @@ -231,18 +196,13 @@ public function setTitle(?string $title): self } /** - * @inheritdoc + * {@inheritdoc} */ public function getDetail(): ?string { return $this->detail; } - /** - * @param null|string $detail - * - * @return self - */ public function setDetail(?string $detail): self { $this->detail = $detail; @@ -251,18 +211,13 @@ public function setDetail(?string $detail): self } /** - * @inheritdoc + * {@inheritdoc} */ public function getSource(): ?array { return $this->source; } - /** - * @param array|null $source - * - * @return self - */ public function setSource(?array $source): self { $this->source = $source; @@ -271,7 +226,7 @@ public function setSource(?array $source): self } /** - * @inheritdoc + * {@inheritdoc} */ public function hasMeta(): bool { @@ -279,7 +234,7 @@ public function hasMeta(): bool } /** - * @inheritdoc + * {@inheritdoc} */ public function getMeta() { @@ -288,13 +243,11 @@ public function getMeta() /** * @param mixed|null $meta - * - * @return self */ public function setMeta($meta): self { $this->hasMeta = true; - $this->meta = $meta; + $this->meta = $meta; return $this; } diff --git a/src/Schema/ErrorCollection.php b/src/Schema/ErrorCollection.php index f665331..ce948ac 100644 --- a/src/Schema/ErrorCollection.php +++ b/src/Schema/ErrorCollection.php @@ -1,8 +1,10 @@ -add($value) : $this->items[$offset] = $value; + null === $offset ? $this->add($value) : $this->items[$offset] = $value; } /** - * @inheritdoc + * {@inheritdoc} */ public function offsetUnset($offset) { @@ -111,11 +111,6 @@ public function getArrayCopy(): array return $this->items; } - /** - * @param ErrorInterface $error - * - * @return self - */ public function add(ErrorInterface $error): self { $this->items[] = $error; @@ -124,17 +119,8 @@ public function add(ErrorInterface $error): self } /** - * @param string $title - * @param string|null $detail - * @param string|null $status - * @param int|string|null $idx - * @param LinkInterface|null $aboutLink - * @param iterable|null $typeLinks - * @param string|null $code - * @param bool $hasMeta - * @param mixed $meta - * - * @return self + * @param int|string|null $idx + * @param mixed $meta */ public function addDataError( string $title, @@ -164,17 +150,8 @@ public function addDataError( } /** - * @param string $title - * @param string|null $detail - * @param string|null $status - * @param int|string|null $idx - * @param LinkInterface|null $aboutLink - * @param iterable|null $typeLinks - * @param string|null $code - * @param bool $hasMeta - * @param mixed $meta - * - * @return self + * @param int|string|null $idx + * @param mixed $meta */ public function addDataTypeError( string $title, @@ -204,17 +181,8 @@ public function addDataTypeError( } /** - * @param string $title - * @param string|null $detail - * @param string|null $status - * @param int|string|null $idx - * @param LinkInterface|null $aboutLink - * @param iterable|null $typeLinks - * @param string|null $code - * @param bool $hasMeta - * @param mixed $meta - * - * @return self + * @param int|string|null $idx + * @param mixed $meta */ public function addDataIdError( string $title, @@ -244,17 +212,8 @@ public function addDataIdError( } /** - * @param string $title - * @param string|null $detail - * @param string|null $status - * @param int|string|null $idx - * @param LinkInterface|null $aboutLink - * @param iterable|null $typeLinks - * @param string|null $code - * @param bool $hasMeta - * @param mixed $meta - * - * @return self + * @param int|string|null $idx + * @param mixed $meta */ public function addAttributesError( string $title, @@ -284,18 +243,9 @@ public function addAttributesError( } /** - * @param string $name - * @param string $title - * @param string|null $detail - * @param string|null $status - * @param int|string|null $idx - * @param LinkInterface|null $aboutLink - * @param iterable|null $typeLinks - * @param string|null $code - * @param bool $hasMeta - * @param mixed $meta - * - * @return self + * @param string $name + * @param int|string|null $idx + * @param mixed $meta * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ @@ -328,17 +278,8 @@ public function addDataAttributeError( } /** - * @param string $title - * @param string|null $detail - * @param string|null $status - * @param int|string|null $idx - * @param LinkInterface|null $aboutLink - * @param iterable|null $typeLinks - * @param string|null $code - * @param bool $hasMeta - * @param mixed $meta - * - * @return self + * @param int|string|null $idx + * @param mixed $meta */ public function addRelationshipsError( string $title, @@ -368,18 +309,9 @@ public function addRelationshipsError( } /** - * @param string $name - * @param string $title - * @param string|null $detail - * @param string|null $status - * @param int|string|null $idx - * @param LinkInterface|null $aboutLink - * @param iterable|null $typeLinks - * @param string|null $code - * @param bool $hasMeta - * @param mixed $meta - * - * @return self + * @param string $name + * @param int|string|null $idx + * @param mixed $meta * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ @@ -412,18 +344,9 @@ public function addRelationshipError( } /** - * @param string $name - * @param string $title - * @param string|null $detail - * @param string|null $status - * @param int|string|null $idx - * @param LinkInterface|null $aboutLink - * @param iterable|null $typeLinks - * @param string|null $code - * @param bool $hasMeta - * @param mixed $meta - * - * @return self + * @param string $name + * @param int|string|null $idx + * @param mixed $meta * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ @@ -456,18 +379,9 @@ public function addRelationshipTypeError( } /** - * @param string $name - * @param string $title - * @param string|null $detail - * @param string|null $status - * @param int|string|null $idx - * @param LinkInterface|null $aboutLink - * @param iterable|null $typeLinks - * @param string|null $code - * @param bool $hasMeta - * @param mixed $meta - * - * @return self + * @param string $name + * @param int|string|null $idx + * @param mixed $meta * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ @@ -500,18 +414,8 @@ public function addRelationshipIdError( } /** - * @param string $name - * @param string $title - * @param string|null $detail - * @param string|null $status - * @param int|string|null $idx - * @param LinkInterface|null $aboutLink - * @param iterable|null $typeLinks - * @param string|null $code - * @param bool $hasMeta - * @param mixed $meta - * - * @return self + * @param int|string|null $idx + * @param mixed $meta * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ @@ -528,7 +432,7 @@ public function addQueryParameterError( $meta = null ): self { $source = [ErrorInterface::SOURCE_PARAMETER => $name]; - $error = new Error($idx, $aboutLink, $typeLinks, $status, $code, $title, $detail, $source, $hasMeta, $meta); + $error = new Error($idx, $aboutLink, $typeLinks, $status, $code, $title, $detail, $source, $hasMeta, $meta); $this->add($error); @@ -536,18 +440,8 @@ public function addQueryParameterError( } /** @noinspection PhpTooManyParametersInspection - * @param string $title - * @param string $pointer - * @param string|null $detail - * @param string|null $status - * @param null $idx - * @param LinkInterface|null $aboutLink - * @param iterable|null $typeLinks - * @param string|null $code - * @param bool $hasMeta - * @param mixed $meta - * - * @return self + * @param null $idx + * @param mixed $meta * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ @@ -564,89 +458,54 @@ protected function addResourceError( $meta = null ): self { $source = [ErrorInterface::SOURCE_POINTER => $pointer]; - $error = new Error($idx, $aboutLink, $typeLinks, $status, $code, $title, $detail, $source, $hasMeta, $meta); + $error = new Error($idx, $aboutLink, $typeLinks, $status, $code, $title, $detail, $source, $hasMeta, $meta); $this->add($error); return $this; } - /** - * @return string - */ protected function getPathToData(): string { return '/' . DocumentInterface::KEYWORD_DATA; } - /** - * @return string - */ protected function getPathToType(): string { return $this->getPathToData() . '/' . DocumentInterface::KEYWORD_TYPE; } - /** - * @return string - */ protected function getPathToId(): string { return $this->getPathToData() . '/' . DocumentInterface::KEYWORD_ID; } - /** - * @return string - */ protected function getPathToAttributes(): string { return $this->getPathToData() . '/' . DocumentInterface::KEYWORD_ATTRIBUTES; } - /** - * @param string $name - * - * @return string - */ protected function getPathToAttribute(string $name): string { return $this->getPathToData() . '/' . DocumentInterface::KEYWORD_ATTRIBUTES . '/' . $name; } - /** - * @return string - */ protected function getPathToRelationships(): string { return $this->getPathToData() . '/' . DocumentInterface::KEYWORD_RELATIONSHIPS; } - /** - * @param string $name - * - * @return string - */ protected function getPathToRelationship(string $name): string { return $this->getPathToRelationships() . '/' . $name; } - /** - * @param string $name - * - * @return string - */ protected function getPathToRelationshipType(string $name): string { return $this->getPathToRelationship($name) . '/' . DocumentInterface::KEYWORD_DATA . '/' . DocumentInterface::KEYWORD_TYPE; } - /** - * @param string $name - * - * @return string - */ protected function getPathToRelationshipId(string $name): string { return $this->getPathToRelationship($name) . '/' . diff --git a/src/Schema/Identifier.php b/src/Schema/Identifier.php index 6f63d3e..1d3adf7 100644 --- a/src/Schema/Identifier.php +++ b/src/Schema/Identifier.php @@ -1,8 +1,10 @@ -setType($type); $this->hasMeta = $hasMeta; - $this->meta = $meta; + $this->meta = $meta; } /** - * @inheritdoc + * {@inheritdoc} */ public function getId(): string { return $this->index; } - /** - * @param string $index - * - * @return self - */ public function setId(string $index): self { $this->index = $index; @@ -74,18 +65,13 @@ public function setId(string $index): self } /** - * @inheritdoc + * {@inheritdoc} */ public function getType(): string { return $this->type; } - /** - * @param string $type - * - * @return self - */ public function setType(string $type): self { $this->type = $type; @@ -94,7 +80,7 @@ public function setType(string $type): self } /** - * @inheritdoc + * {@inheritdoc} */ public function hasIdentifierMeta(): bool { @@ -102,7 +88,7 @@ public function hasIdentifierMeta(): bool } /** - * @inheritdoc + * {@inheritdoc} */ public function getIdentifierMeta() { @@ -111,12 +97,10 @@ public function getIdentifierMeta() /** * @param mixed $meta - * - * @return self */ public function setIdentifierMeta($meta): self { - $this->meta = $meta; + $this->meta = $meta; $this->hasMeta = true; return $this; diff --git a/src/Schema/Link.php b/src/Schema/Link.php index 8976121..22b8019 100644 --- a/src/Schema/Link.php +++ b/src/Schema/Link.php @@ -1,8 +1,10 @@ -isSubUrl = $isSubUrl; - $this->value = $value; - $this->hasMeta = $hasMeta; - $this->meta = $meta; + $this->value = $value; + $this->hasMeta = $hasMeta; + $this->meta = $meta; } /** - * @inheritdoc + * {@inheritdoc} */ public function canBeShownAsString(): bool { - return $this->hasMeta === false; + return false === $this->hasMeta; } /** - * @inheritdoc + * {@inheritdoc} */ public function getStringRepresentation(string $prefix): string { - \assert($this->canBeShownAsString() === true); + \assert(true === $this->canBeShownAsString()); return $this->buildUrl($prefix); } /** - * @inheritdoc + * {@inheritdoc} */ public function getArrayRepresentation(string $prefix): array { - \assert($this->canBeShownAsString() === false); + \assert(false === $this->canBeShownAsString()); \assert($this->hasMeta); @@ -96,11 +89,6 @@ public function getArrayRepresentation(string $prefix): array ]; } - /** - * @param string $prefix - * - * @return string - */ protected function buildUrl(string $prefix): string { return $this->isSubUrl ? $prefix . $this->value : $this->value; diff --git a/src/Schema/LinkWithAliases.php b/src/Schema/LinkWithAliases.php index b00d4d3..680b837 100644 --- a/src/Schema/LinkWithAliases.php +++ b/src/Schema/LinkWithAliases.php @@ -1,8 +1,10 @@ - $alias) { - \assert(\is_string($name) === true && empty($name) === false); - \assert(\is_string($alias) === true && empty($alias) === false); + \assert(true === \is_string($name) && false === empty($name)); + \assert(true === \is_string($alias) && false === empty($alias)); $aliasesArray[$name] = $alias; } - $this->aliases = $aliasesArray; + $this->aliases = $aliasesArray; $this->hasAliases = !empty($aliasesArray); parent::__construct($isSubUrl, $value, $hasMeta, $meta); } /** - * @inheritdoc + * {@inheritdoc} */ public function canBeShownAsString(): bool { - return parent::canBeShownAsString() && $this->hasAliases === false; + return parent::canBeShownAsString() && false === $this->hasAliases; } /** - * @inheritdoc + * {@inheritdoc} */ public function getArrayRepresentation(string $prefix): array { - $linkRepresentation = parent::canBeShownAsString() === true ? [ + $linkRepresentation = true === parent::canBeShownAsString() ? [ DocumentInterface::KEYWORD_HREF => $this->buildUrl($prefix), ] : parent::getArrayRepresentation($prefix); - if ($this->hasAliases === true) { + if (true === $this->hasAliases) { $linkRepresentation[DocumentInterface::KEYWORD_ALIASES] = $this->aliases; } diff --git a/src/Schema/SchemaContainer.php b/src/Schema/SchemaContainer.php index bd6bf6a..b0e800b 100644 --- a/src/Schema/SchemaContainer.php +++ b/src/Schema/SchemaContainer.php @@ -1,8 +1,10 @@ -factory = $factory; @@ -69,36 +64,33 @@ public function __construct(FactoryInterface $factory, iterable $schemas) /** * Register provider for resource type. * - * @param string $type * @param string|Closure $schema * - * @return void - * * @SuppressWarnings(PHPMD.StaticAccess) * @SuppressWarnings(PHPMD.ElseExpression) * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function register(string $type, $schema): void { - if (empty($type) === true || \class_exists($type) === false) { + if (true === empty($type) || false === \class_exists($type)) { throw new InvalidArgumentException(_(static::MSG_INVALID_MODEL_TYPE)); } $isOk = ( ( - \is_string($schema) === true && - empty($schema) === false && - \class_exists($schema) === true && - \in_array(SchemaInterface::class, \class_implements($schema)) === true + true === \is_string($schema) && + false === empty($schema) && + true === \class_exists($schema) && + true === \in_array(SchemaInterface::class, \class_implements($schema), true) ) || \is_callable($schema) || $schema instanceof SchemaInterface ); - if ($isOk === false) { + if (false === $isOk) { throw new InvalidArgumentException(_(static::MSG_INVALID_SCHEME, $type)); } - if ($this->hasProviderMapping($type) === true) { + if (true === $this->hasProviderMapping($type)) { throw new InvalidArgumentException(_(static::MSG_TYPE_REUSE_FORBIDDEN, $type)); } @@ -113,10 +105,6 @@ public function register(string $type, $schema): void /** * Register providers for resource types. - * - * @param iterable $schemas - * - * @return void */ public function registerCollection(iterable $schemas): void { @@ -126,7 +114,7 @@ public function registerCollection(iterable $schemas): void } /** - * @inheritdoc + * {@inheritdoc} */ public function getSchema($resource): SchemaInterface { @@ -138,55 +126,48 @@ public function getSchema($resource): SchemaInterface } /** - * @inheritdoc + * {@inheritdoc} */ public function hasSchema($resourceObject): bool { - return \is_object($resourceObject) === true && - $this->hasProviderMapping($this->getResourceType($resourceObject)) === true; + return true === \is_object($resourceObject) && + true === $this->hasProviderMapping($this->getResourceType($resourceObject)); } /** - * @inheritdoc + * {@inheritdoc} * * @SuppressWarnings(PHPMD.StaticAccess) * @SuppressWarnings(PHPMD.ElseExpression) */ protected function getSchemaByType(string $type): SchemaInterface { - if ($this->hasCreatedProvider($type) === true) { + if (true === $this->hasCreatedProvider($type)) { return $this->getCreatedProvider($type); } $classNameOrCallable = $this->getProviderMapping($type); - if (\is_string($classNameOrCallable) === true) { + if (true === \is_string($classNameOrCallable)) { $schema = $this->createSchemaFromClassName($classNameOrCallable); } else { - \assert(\is_callable($classNameOrCallable) === true); + \assert(true === \is_callable($classNameOrCallable)); $schema = $this->createSchemaFromCallable($classNameOrCallable); } $this->setCreatedProvider($type, $schema); - /** @var SchemaInterface $schema */ + /* @var SchemaInterface $schema */ $this->setResourceToJsonTypeMapping($schema->getType(), $type); return $schema; } - /** - * @param string $type - * - * @return bool - */ protected function hasProviderMapping(string $type): bool { return isset($this->providerMapping[$type]); } /** - * @param string $type - * * @return mixed */ protected function getProviderMapping(string $type) @@ -195,53 +176,28 @@ protected function getProviderMapping(string $type) } /** - * @param string $type * @param string|Closure $schema - * - * @return void */ protected function setProviderMapping(string $type, $schema): void { $this->providerMapping[$type] = $schema; } - /** - * @param string $type - * - * @return bool - */ protected function hasCreatedProvider(string $type): bool { return isset($this->createdProviders[$type]); } - /** - * @param string $type - * - * @return SchemaInterface - */ protected function getCreatedProvider(string $type): SchemaInterface { return $this->createdProviders[$type]; } - /** - * @param string $type - * @param SchemaInterface $provider - * - * @return void - */ protected function setCreatedProvider(string $type, SchemaInterface $provider): void { $this->createdProviders[$type] = $provider; } - /** - * @param string $resourceType - * @param string $jsonType - * - * @return void - */ protected function setResourceToJsonTypeMapping(string $resourceType, string $jsonType): void { $this->resType2JsonType[$resourceType] = $jsonType; @@ -249,24 +205,17 @@ protected function setResourceToJsonTypeMapping(string $resourceType, string $js /** * @param object $resource - * - * @return string */ protected function getResourceType($resource): string { \assert( - \is_object($resource) === true, + true === \is_object($resource), 'Unable to get a type of the resource as it is not an object.' ); return \get_class($resource); } - /** - * @param callable $callable - * - * @return SchemaInterface - */ protected function createSchemaFromCallable(callable $callable): SchemaInterface { $schema = \call_user_func($callable, $this->factory); @@ -274,11 +223,6 @@ protected function createSchemaFromCallable(callable $callable): SchemaInterface return $schema; } - /** - * @param string $className - * - * @return SchemaInterface - */ protected function createSchemaFromClassName(string $className): SchemaInterface { $schema = new $className($this->factory); diff --git a/tests/BaseTestCase.php b/tests/BaseTestCase.php index d99cbca..d6cb5e6 100644 --- a/tests/BaseTestCase.php +++ b/tests/BaseTestCase.php @@ -1,8 +1,10 @@ -data); + return \array_key_exists($offset, $this->data); } /** - * @inheritdoc + * {@inheritdoc} */ public function offsetGet($offset) { @@ -46,15 +45,15 @@ public function offsetGet($offset) } /** - * @inheritdoc + * {@inheritdoc} */ public function offsetSet($offset, $value) { - $offset === null ? $this->data[] = $value : $this->data[$offset] = $value; + null === $offset ? $this->data[] = $value : $this->data[$offset] = $value; } /** - * @inheritdoc + * {@inheritdoc} */ public function offsetUnset($offset) { @@ -62,7 +61,7 @@ public function offsetUnset($offset) } /** - * @inheritdoc + * {@inheritdoc} */ public function getIterator() { diff --git a/tests/Data/Models/Author.php b/tests/Data/Models/Author.php index 926d634..6b994ad 100644 --- a/tests/Data/Models/Author.php +++ b/tests/Data/Models/Author.php @@ -1,8 +1,10 @@ -{self::ATTRIBUTE_ID} = $identity; + $author->{self::ATTRIBUTE_ID} = $identity; $author->{self::ATTRIBUTE_FIRST_NAME} = $firstName; - $author->{self::ATTRIBUTE_LAST_NAME} = $lastName; + $author->{self::ATTRIBUTE_LAST_NAME} = $lastName; - $comments === null ?: $author->{self::LINK_COMMENTS} = $comments; + null === $comments ?: $author->{self::LINK_COMMENTS} = $comments; return $author; } /** * @param mixed $meta - * - * @return self */ public function setIdentifierMeta($meta): self { @@ -67,8 +59,6 @@ public function setIdentifierMeta($meta): self /** * @param mixed $meta - * - * @return self */ public function setResourceMeta($meta): self { diff --git a/tests/Data/Models/AuthorCModel.php b/tests/Data/Models/AuthorCModel.php index 7aad5cc..b04917f 100644 --- a/tests/Data/Models/AuthorCModel.php +++ b/tests/Data/Models/AuthorCModel.php @@ -1,8 +1,10 @@ -properties); + return \array_key_exists($offset, $this->properties); } /** - * @inheritdoc + * {@inheritdoc} */ public function offsetGet($offset) { @@ -80,7 +72,7 @@ public function offsetGet($offset) } /** - * @inheritdoc + * {@inheritdoc} */ public function offsetSet($offset, $value) { @@ -88,7 +80,7 @@ public function offsetSet($offset, $value) } /** - * @inheritdoc + * {@inheritdoc} */ public function offsetUnset($offset) { diff --git a/tests/Data/Models/AuthorIdentity.php b/tests/Data/Models/AuthorIdentity.php index af215ee..1e02801 100644 --- a/tests/Data/Models/AuthorIdentity.php +++ b/tests/Data/Models/AuthorIdentity.php @@ -1,8 +1,10 @@ -{self::ATTRIBUTE_ID} = $identity; + $comment->{self::ATTRIBUTE_ID} = $identity; $comment->{self::ATTRIBUTE_BODY} = $body; $comment->{self::LINK_AUTHOR} = $author; diff --git a/tests/Data/Models/CommentIdentity.php b/tests/Data/Models/CommentIdentity.php index 0550370..1980df8 100644 --- a/tests/Data/Models/CommentIdentity.php +++ b/tests/Data/Models/CommentIdentity.php @@ -1,8 +1,10 @@ -{self::ATTRIBUTE_ID} = $identity; + $post->{self::ATTRIBUTE_ID} = $identity; $post->{self::ATTRIBUTE_TITLE} = $title; - $post->{self::ATTRIBUTE_BODY} = $body; - $post->{self::LINK_AUTHOR} = $author; - $post->{self::LINK_COMMENTS} = $comments; + $post->{self::ATTRIBUTE_BODY} = $body; + $post->{self::LINK_AUTHOR} = $author; + $post->{self::LINK_COMMENTS} = $comments; return $post; } diff --git a/tests/Data/Models/Site.php b/tests/Data/Models/Site.php index fe50677..d1b4020 100644 --- a/tests/Data/Models/Site.php +++ b/tests/Data/Models/Site.php @@ -1,8 +1,10 @@ -{self::ATTRIBUTE_ID} = $identity; + $site->{self::ATTRIBUTE_ID} = $identity; $site->{self::ATTRIBUTE_NAME} = $name; - $posts === null ?: $site->{self::LINK_POSTS} = $posts; + null === $posts ?: $site->{self::LINK_POSTS} = $posts; return $site; } diff --git a/tests/Data/Schemas/AuthorCModelSchema.php b/tests/Data/Schemas/AuthorCModelSchema.php index bf3fc07..8112660 100644 --- a/tests/Data/Schemas/AuthorCModelSchema.php +++ b/tests/Data/Schemas/AuthorCModelSchema.php @@ -1,8 +1,10 @@ - $resource[AuthorCModel::ATTRIBUTE_FIRST_NAME], - AuthorCModel::ATTRIBUTE_LAST_NAME => $resource[AuthorCModel::ATTRIBUTE_LAST_NAME], + AuthorCModel::ATTRIBUTE_LAST_NAME => $resource[AuthorCModel::ATTRIBUTE_LAST_NAME], ]; } /** - * @inheritdoc + * {@inheritdoc} */ public function getRelationships($resource, ContextInterface $context): iterable { - assert($resource instanceof AuthorCModel); + \assert($resource instanceof AuthorCModel); - if (array_key_exists(AuthorCModel::LINK_COMMENTS, (array)$resource) === true) { + if (true === \array_key_exists(AuthorCModel::LINK_COMMENTS, (array) $resource)) { $description = [self::RELATIONSHIP_DATA => $resource[AuthorCModel::LINK_COMMENTS]]; } else { - $selfLink = $this->getRelationshipSelfLink($resource, AuthorCModel::LINK_COMMENTS); + $selfLink = $this->getRelationshipSelfLink($resource, AuthorCModel::LINK_COMMENTS); $description = [self::RELATIONSHIP_LINKS => [LinkInterface::SELF => $selfLink]]; } diff --git a/tests/Data/Schemas/AuthorSchema.php b/tests/Data/Schemas/AuthorSchema.php index 0d91267..e5d68a2 100644 --- a/tests/Data/Schemas/AuthorSchema.php +++ b/tests/Data/Schemas/AuthorSchema.php @@ -1,8 +1,10 @@ -{Author::ATTRIBUTE_ID}; - return $index === null ? $index : (string)$index; + return null === $index ? $index : (string) $index; } /** - * @inheritdoc + * {@inheritdoc} */ public function getAttributes($resource, ContextInterface $context): iterable { - assert($resource instanceof Author); + \assert($resource instanceof Author); return [ Author::ATTRIBUTE_FIRST_NAME => $resource->{Author::ATTRIBUTE_FIRST_NAME}, - Author::ATTRIBUTE_LAST_NAME => $resource->{Author::ATTRIBUTE_LAST_NAME}, + Author::ATTRIBUTE_LAST_NAME => $resource->{Author::ATTRIBUTE_LAST_NAME}, ]; } /** - * @inheritdoc + * {@inheritdoc} */ public function getRelationships($resource, ContextInterface $context): iterable { - assert($resource instanceof Author); + \assert($resource instanceof Author); // add test coverage for context param - assert($context->getPosition() !== null); - assert($context->getFieldSets() !== null); - assert($context->getIncludePaths() !== null); + \assert(null !== $context->getPosition()); + \assert(null !== $context->getFieldSets()); + \assert(null !== $context->getIncludePaths()); // test and cover with test that factory could be used from a Schema. - assert($this->getFactory()->createLink(true, 'test-example', false) !== null); + \assert(null !== $this->getFactory()->createLink(true, 'test-example', false)); - if (property_exists($resource, Author::LINK_COMMENTS) === true) { + if (true === \property_exists($resource, Author::LINK_COMMENTS)) { $description = [self::RELATIONSHIP_DATA => $resource->{Author::LINK_COMMENTS}]; } else { - $selfLink = $this->getRelationshipSelfLink($resource, Author::LINK_COMMENTS); + $selfLink = $this->getRelationshipSelfLink($resource, Author::LINK_COMMENTS); $description = [self::RELATIONSHIP_LINKS => [LinkInterface::SELF => $selfLink]]; } @@ -94,41 +91,41 @@ public function getRelationships($resource, ContextInterface $context): iterable } /** - * @inheritdoc + * {@inheritdoc} */ public function hasIdentifierMeta($resource): bool { - assert($resource instanceof Author); + \assert($resource instanceof Author); - return parent::hasIdentifierMeta($resource) || property_exists($resource, Author::IDENTIFIER_META); + return parent::hasIdentifierMeta($resource) || \property_exists($resource, Author::IDENTIFIER_META); } /** - * @inheritdoc + * {@inheritdoc} */ public function getIdentifierMeta($resource) { - assert($resource instanceof Author); + \assert($resource instanceof Author); return $resource->{Author::IDENTIFIER_META}; } /** - * @inheritdoc + * {@inheritdoc} */ public function hasResourceMeta($resource): bool { - assert($resource instanceof Author); + \assert($resource instanceof Author); - return parent::hasResourceMeta($resource) || property_exists($resource, Author::RESOURCE_META); + return parent::hasResourceMeta($resource) || \property_exists($resource, Author::RESOURCE_META); } /** - * @inheritdoc + * {@inheritdoc} */ public function getResourceMeta($resource) { - assert($resource instanceof Author); + \assert($resource instanceof Author); return $resource->{Author::RESOURCE_META}; } diff --git a/tests/Data/Schemas/CommentSchema.php b/tests/Data/Schemas/CommentSchema.php index 96fbcfb..4a82aef 100644 --- a/tests/Data/Schemas/CommentSchema.php +++ b/tests/Data/Schemas/CommentSchema.php @@ -1,8 +1,10 @@ -{Comment::ATTRIBUTE_ID}; - return $index === null ? $index : (string)$index; + return null === $index ? $index : (string) $index; } /** - * @inheritdoc + * {@inheritdoc} */ public function getAttributes($resource, ContextInterface $context): iterable { - assert($resource instanceof Comment); + \assert($resource instanceof Comment); return [ Comment::ATTRIBUTE_BODY => $resource->{Comment::ATTRIBUTE_BODY}, @@ -60,11 +58,11 @@ public function getAttributes($resource, ContextInterface $context): iterable } /** - * @inheritdoc + * {@inheritdoc} */ public function getRelationships($resource, ContextInterface $context): iterable { - assert($resource instanceof Comment); + \assert($resource instanceof Comment); // NOTE: The `fixing` thing is for testing purposes only. Not for production. return $this->fixDescriptions( diff --git a/tests/Data/Schemas/DevSchema.php b/tests/Data/Schemas/DevSchema.php index 7f6643c..3766a2e 100644 --- a/tests/Data/Schemas/DevSchema.php +++ b/tests/Data/Schemas/DevSchema.php @@ -1,8 +1,10 @@ -resourceLinksClosure) === null) { return parent::getLinks($resource); - } else { - return $linksClosure($resource); } + + return $linksClosure($resource); } - /** - * @param Closure $linksClosure - * - * @return void - */ public function setResourceLinksClosure(Closure $linksClosure): void { $this->resourceLinksClosure = $linksClosure; @@ -67,11 +60,9 @@ public function setResourceLinksClosure(Closure $linksClosure): void /** * Add value to relationship description. * - * @param string $name Relationship name. - * @param int $key Description key. - * @param mixed $value Value to add (might be array of links). - * - * @return void + * @param string $name relationship name + * @param int $key description key + * @param mixed $value value to add (might be array of links) */ public function addToRelationship(string $name, int $key, $value): void { @@ -81,10 +72,8 @@ public function addToRelationship(string $name, int $key, $value): void /** * Remove from relationship description. * - * @param string $name Relationship name. - * @param int $key Description key. - * - * @return void + * @param string $name relationship name + * @param int $key description key */ public function removeFromRelationship(string $name, int $key): void { @@ -94,20 +83,16 @@ public function removeFromRelationship(string $name, int $key): void /** * Remove entire relationship from description. * - * @param string $name Relationship name. - * - * @return void + * @param string $name relationship name */ public function removeRelationship(string $name): void { - assert(is_string($name)); + \assert(\is_string($name)); $this->relationshipToRemove[] = $name; } /** * @param mixed $resource - * - * @return string */ public function getSelfSubUrl($resource): string { @@ -116,8 +101,6 @@ public function getSelfSubUrl($resource): string /** * Hide `self` link in relationship. - * - * @param string $name */ public function hideSelfLinkInRelationship(string $name): void { @@ -126,11 +109,6 @@ public function hideSelfLinkInRelationship(string $name): void /** * Set custom `self` link in relationship. - * - * @param string $name - * @param LinkInterface $link - * - * @return void */ public function setSelfLinkInRelationship(string $name, LinkInterface $link): void { @@ -139,8 +117,6 @@ public function setSelfLinkInRelationship(string $name, LinkInterface $link): vo /** * Hide `related` link in relationship. - * - * @param string $name */ public function hideRelatedLinkInRelationship(string $name): void { @@ -149,20 +125,12 @@ public function hideRelatedLinkInRelationship(string $name): void /** * Set custom `related` link in relationship. - * - * @param string $name - * @param LinkInterface $link - * - * @return void */ public function setRelatedLinkInRelationship(string $name, LinkInterface $link): void { $this->addToRelationship($name, AuthorSchema::RELATIONSHIP_LINKS_RELATED, $link); } - /** - * @param string $name - */ public function hideDefaultLinksInRelationship(string $name): void { $this->hideSelfLinkInRelationship($name); @@ -175,7 +143,7 @@ public function hideDefaultLinksInRelationship(string $name): void public function hideResourceLinks(): void { $this->setResourceLinksClosure( - fn(): array => [] + fn (): array => [] ); } @@ -183,16 +151,13 @@ public function hideResourceLinks(): void * Add/remove values in input array. * * @param object $resource - * @param array $descriptions - * - * @return array */ protected function fixDescriptions($resource, array $descriptions): array { foreach ($this->addToRelationship as [$name, $key, $value]) { - if ($key === self::RELATIONSHIP_LINKS) { + if (self::RELATIONSHIP_LINKS === $key) { foreach ($value as $linkKey => $linkOrClosure) { - $link = $linkOrClosure instanceof Closure ? $linkOrClosure( + $link = $linkOrClosure instanceof Closure ? $linkOrClosure( $this, $resource ) : $linkOrClosure; diff --git a/tests/Data/Schemas/PostSchema.php b/tests/Data/Schemas/PostSchema.php index a2b66e6..b690948 100644 --- a/tests/Data/Schemas/PostSchema.php +++ b/tests/Data/Schemas/PostSchema.php @@ -1,8 +1,10 @@ -{Post::ATTRIBUTE_ID}; - return $index === null ? $index : (string)$index; + return null === $index ? $index : (string) $index; } /** - * @inheritdoc + * {@inheritdoc} */ public function getAttributes($resource, ContextInterface $context): iterable { - assert($resource instanceof Post); + \assert($resource instanceof Post); return [ Post::ATTRIBUTE_TITLE => $resource->{Post::ATTRIBUTE_TITLE}, - Post::ATTRIBUTE_BODY => $resource->{Post::ATTRIBUTE_BODY}, + Post::ATTRIBUTE_BODY => $resource->{Post::ATTRIBUTE_BODY}, ]; } /** - * @inheritdoc + * {@inheritdoc} */ public function getRelationships($resource, ContextInterface $context): iterable { - assert($resource instanceof Post); + \assert($resource instanceof Post); - if (property_exists($resource, Post::LINK_AUTHOR) === true) { + if (true === \property_exists($resource, Post::LINK_AUTHOR)) { $authorDescription = [self::RELATIONSHIP_DATA => $resource->{Post::LINK_AUTHOR}]; } else { - $selfLink = $this->getRelationshipSelfLink($resource, Post::LINK_AUTHOR); + $selfLink = $this->getRelationshipSelfLink($resource, Post::LINK_AUTHOR); $authorDescription = [self::RELATIONSHIP_LINKS => [LinkInterface::SELF => $selfLink]]; } - if (property_exists($resource, Post::LINK_COMMENTS) === true) { + if (true === \property_exists($resource, Post::LINK_COMMENTS)) { $commentsDescription = [self::RELATIONSHIP_DATA => $resource->{Post::LINK_COMMENTS}]; } else { - $selfLink = $this->getRelationshipSelfLink($resource, Post::LINK_COMMENTS); + $selfLink = $this->getRelationshipSelfLink($resource, Post::LINK_COMMENTS); $commentsDescription = [self::RELATIONSHIP_LINKS => [LinkInterface::SELF => $selfLink]]; } @@ -87,7 +84,7 @@ public function getRelationships($resource, ContextInterface $context): iterable return $this->fixDescriptions( $resource, [ - Post::LINK_AUTHOR => $authorDescription, + Post::LINK_AUTHOR => $authorDescription, Post::LINK_COMMENTS => $commentsDescription, ] ); diff --git a/tests/Data/Schemas/SiteSchema.php b/tests/Data/Schemas/SiteSchema.php index 40d9016..6c76b68 100644 --- a/tests/Data/Schemas/SiteSchema.php +++ b/tests/Data/Schemas/SiteSchema.php @@ -1,8 +1,10 @@ -{Site::ATTRIBUTE_ID}; - return $index === null ? $index : (string)$index; + return null === $index ? $index : (string) $index; } /** - * @inheritdoc + * {@inheritdoc} */ public function getAttributes($resource, ContextInterface $context): iterable { - assert($resource instanceof Site); + \assert($resource instanceof Site); return [ Site::ATTRIBUTE_NAME => $resource->{Site::ATTRIBUTE_NAME}, @@ -60,16 +59,16 @@ public function getAttributes($resource, ContextInterface $context): iterable } /** - * @inheritdoc + * {@inheritdoc} */ public function getRelationships($resource, ContextInterface $context): iterable { - assert($resource instanceof Site); + \assert($resource instanceof Site); - if (property_exists($resource, Site::LINK_POSTS) === true) { + if (true === \property_exists($resource, Site::LINK_POSTS)) { $description = [self::RELATIONSHIP_DATA => $resource->{Site::LINK_POSTS}]; } else { - $selfLink = $this->getRelationshipSelfLink($resource, Site::LINK_POSTS); + $selfLink = $this->getRelationshipSelfLink($resource, Site::LINK_POSTS); $description = [self::RELATIONSHIP_LINKS => [LinkInterface::SELF => $selfLink]]; } diff --git a/tests/Encoder/EncodeErrorsTest.php b/tests/Encoder/EncodeErrorsTest.php index f76c5fc..bdad348 100644 --- a/tests/Encoder/EncodeErrorsTest.php +++ b/tests/Encoder/EncodeErrorsTest.php @@ -1,8 +1,10 @@ -getError(); + $error = $this->getError(); $encoder = Encoder::instance(); - $actual = $encoder->encodeError($error); + $actual = $encoder->encodeError($error); $expected = <<getError(); + $error = $this->getError(); $encoder = Encoder::instance(); $actual = $encoder->encodeErrors([$error]); @@ -93,7 +92,7 @@ public function testEncodeErrorsArray(): void /** * Test encode error array. */ - public function testEncodeErrorsCollection(): void + public function test_encode_errors_collection(): void { $errors = new ErrorCollection(); $errors->add($this->getError()); @@ -127,11 +126,11 @@ public function testEncodeErrorsCollection(): void * * @see https://github.com/neomerx/json-api/issues/62 */ - public function testEncodeEmptyError(): void + public function test_encode_empty_error(): void { - $error = new Error(); + $error = new Error(); $encoder = Encoder::instance(); - $actual = $encoder->encodeError($error); + $actual = $encoder->encodeError($error); $expected = <<encodeErrors([]); @@ -165,15 +164,15 @@ public function testEncodeEmptyErrorArray(): void * * @see https://github.com/neomerx/json-api/issues/171 */ - public function testEncodeErrorWithMetaAndJsonApi(): void + public function test_encode_error_with_meta_and_json_api(): void { - $error = $this->getError(); + $error = $this->getError(); $encoder = Encoder::instance(); $actual = $encoder ->withJsonApiVersion(Encoder::JSON_API_VERSION) ->withJsonApiMeta(['some' => 'meta']) - ->withMeta(["copyright" => "Copyright 2015 Example Corp."]) + ->withMeta(['copyright' => 'Copyright 2015 Example Corp.']) ->encodeError($error); $expected = <<author = Author::instance(9, 'Dan', 'Gebhardt'); + $this->author = Author::instance(9, 'Dan', 'Gebhardt'); $this->comments = [ Comment::instance(5, 'First!', $this->author), Comment::instance(12, 'I like XML better', $this->author), ]; - $this->post = Post::instance( + $this->post = Post::instance( 1, 'JSON API paints my bikeshed!', 'Outside every fat man there was an even fatter man trying to close in', $this->author, $this->comments ); - $this->site = Site::instance(2, 'site name', [$this->post]); + $this->site = Site::instance(2, 'site name', [$this->post]); } /** * Test encode included objects. */ - public function testEncodeWithIncludedObjects(): void + public function test_encode_with_included_objects(): void { $this->author->setIdentifierMeta('id meta'); $actual = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => function ($factory) { $schema = new CommentSchema($factory); $schema->removeRelationship(Comment::LINK_AUTHOR); + return $schema; }, - Post::class => function ($factory) { + Post::class => function ($factory) { $schema = new PostSchema($factory); $schema->hideDefaultLinksInRelationship(Post::LINK_AUTHOR); $schema->hideDefaultLinksInRelationship(Post::LINK_COMMENTS); + return $schema; }, ] @@ -145,27 +146,30 @@ public function testEncodeWithIncludedObjects(): void /** * Test encode nested included objects with cyclic dependencies and sparse support. */ - public function testEncodeWithRecursiveIncludedObjects(): void + public function test_encode_with_recursive_included_objects(): void { $this->author->{Author::LINK_COMMENTS} = $this->comments; $actual = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => function ($factory) { $schema = new CommentSchema($factory); $schema->hideDefaultLinksInRelationship(Comment::LINK_AUTHOR); + return $schema; }, - Post::class => function ($factory) { + Post::class => function ($factory) { $schema = new PostSchema($factory); $schema->hideDefaultLinksInRelationship(Post::LINK_AUTHOR); $schema->hideDefaultLinksInRelationship(Post::LINK_COMMENTS); + return $schema; }, - Site::class => function ($factory) { + Site::class => function ($factory) { $schema = new SiteSchema($factory); $schema->hideDefaultLinksInRelationship(Site::LINK_POSTS); + return $schema; }, ] @@ -180,8 +184,8 @@ public function testEncodeWithRecursiveIncludedObjects(): void // include only these attributes and links (note we specify relationships for linkage, // otherwise those intermediate resources will not be included in the output) 'comments' => [Comment::ATTRIBUTE_BODY, Comment::LINK_AUTHOR], - 'posts' => [Post::LINK_COMMENTS], - 'sites' => [Site::LINK_POSTS], + 'posts' => [Post::LINK_COMMENTS], + 'sites' => [Site::LINK_POSTS], ] )->encodeData($this->site); @@ -253,9 +257,9 @@ public function testEncodeWithRecursiveIncludedObjects(): void /** * Test encode included objects with null and empty links. */ - public function testEncodeWithNullAndEmptyLinks(): void + public function test_encode_with_null_and_empty_links(): void { - $this->post->{Post::LINK_AUTHOR} = null; + $this->post->{Post::LINK_AUTHOR} = null; $this->post->{Post::LINK_COMMENTS} = []; $actual = Encoder::instance( @@ -265,11 +269,13 @@ public function testEncodeWithNullAndEmptyLinks(): void $schema->hideResourceLinks(); $schema->hideDefaultLinksInRelationship(Post::LINK_AUTHOR); $schema->hideDefaultLinksInRelationship(Post::LINK_COMMENTS); + return $schema; }, Site::class => function ($factory) { $schema = new SiteSchema($factory); $schema->hideDefaultLinksInRelationship(Site::LINK_POSTS); + return $schema; }, ] @@ -315,7 +321,7 @@ public function testEncodeWithNullAndEmptyLinks(): void /** * Test encode duplicate included objects with cyclic dependencies. */ - public function testEncodeDuplicatesWithCyclicDeps(): void + public function test_encode_duplicates_with_cyclic_deps(): void { $this->post->{Post::LINK_COMMENTS} = []; @@ -329,11 +335,13 @@ public function testEncodeDuplicatesWithCyclicDeps(): void $schema->hideResourceLinks(); $schema->hideDefaultLinksInRelationship(Post::LINK_AUTHOR); $schema->hideDefaultLinksInRelationship(Post::LINK_COMMENTS); + return $schema; }, Site::class => function ($factory) { $schema = new SiteSchema($factory); $schema->hideDefaultLinksInRelationship(Site::LINK_POSTS); + return $schema; }, ] @@ -382,22 +390,24 @@ public function testEncodeDuplicatesWithCyclicDeps(): void * Test link objects that should not be included but these objects link to others that should. * Parser should stop parsing even if deeper objects exist. */ - public function testEncodeLinkNonIncludableWithIncludableLinks(): void + public function test_encode_link_non_includable_with_includable_links(): void { $actual = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => CommentSchema::class, - Post::class => function ($factory) { + Post::class => function ($factory) { $schema = new PostSchema($factory); $schema->hideResourceLinks(); $schema->hideDefaultLinksInRelationship(Post::LINK_AUTHOR); $schema->hideDefaultLinksInRelationship(Post::LINK_COMMENTS); + return $schema; }, - Site::class => function ($factory) { + Site::class => function ($factory) { $schema = new SiteSchema($factory); $schema->hideDefaultLinksInRelationship(Site::LINK_POSTS); + return $schema; }, ] @@ -453,13 +463,13 @@ public function testEncodeLinkNonIncludableWithIncludableLinks(): void /** * Test encode included objects. */ - public function testEncodeWithLinkWithPagination(): void + public function test_encode_with_link_with_pagination(): void { $actual = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => CommentSchema::class, - Post::class => function ($factory) { + Post::class => function ($factory) { $schema = new PostSchema($factory); $schema->hideDefaultLinksInRelationship(Post::LINK_AUTHOR); $schema->hideRelatedLinkInRelationship(Post::LINK_COMMENTS); @@ -467,9 +477,10 @@ public function testEncodeWithLinkWithPagination(): void Post::LINK_COMMENTS, PostSchema::RELATIONSHIP_LINKS, [ - Link::FIRST => fn(PostSchema $schema, Post $post) => new Link(true, $schema->getSelfSubUrl($post) . '/comments/first', false), + Link::FIRST => fn (PostSchema $schema, Post $post) => new Link(true, $schema->getSelfSubUrl($post) . '/comments/first', false), ] ); + return $schema; }, ] @@ -513,31 +524,35 @@ public function testEncodeWithLinkWithPagination(): void * * Test for issue 35 */ - public function testEncodeDeepDuplicateHierarchies(): void + public function test_encode_deep_duplicate_hierarchies(): void { $actual = Encoder::instance( [ - Author::class => function ($factory) { + Author::class => function ($factory) { $schema = new AuthorSchema($factory); $schema->hideResourceLinks(); $schema->hideDefaultLinksInRelationship(Author::LINK_COMMENTS); + return $schema; }, Comment::class => function ($factory) { $schema = new CommentSchema($factory); $schema->hideDefaultLinksInRelationship(Comment::LINK_AUTHOR); + return $schema; }, - Post::class => function ($factory) { + Post::class => function ($factory) { $schema = new PostSchema($factory); $schema->hideResourceLinks(); $schema->hideDefaultLinksInRelationship(Post::LINK_AUTHOR); $schema->hideDefaultLinksInRelationship(Post::LINK_COMMENTS); + return $schema; }, - Site::class => function ($factory) { + Site::class => function ($factory) { $schema = new SiteSchema($factory); $schema->hideDefaultLinksInRelationship(Site::LINK_POSTS); + return $schema; }, ] @@ -653,32 +668,36 @@ public function testEncodeDeepDuplicateHierarchies(): void /** * Test encode nested included objects for polymorphic arrays. */ - public function testEncodeWithIncludedForPolymorphicArrays(): void + public function test_encode_with_included_for_polymorphic_arrays(): void { $this->author->{Author::LINK_COMMENTS} = $this->comments; $actual = Encoder::instance( [ - Author::class => function ($factory) { + Author::class => function ($factory) { $schema = new AuthorSchema($factory); $schema->hideDefaultLinksInRelationship(Author::LINK_COMMENTS); + return $schema; }, Comment::class => function ($factory) { $schema = new CommentSchema($factory); $schema->hideDefaultLinksInRelationship(Comment::LINK_AUTHOR); + return $schema; }, - Post::class => function ($factory) { + Post::class => function ($factory) { $schema = new PostSchema($factory); $schema->hideResourceLinks(); $schema->hideDefaultLinksInRelationship(Post::LINK_AUTHOR); $schema->hideDefaultLinksInRelationship(Post::LINK_COMMENTS); + return $schema; }, - Site::class => function ($factory) { + Site::class => function ($factory) { $schema = new SiteSchema($factory); $schema->hideDefaultLinksInRelationship(Site::LINK_POSTS); + return $schema; }, ] @@ -792,34 +811,38 @@ public function testEncodeWithIncludedForPolymorphicArrays(): void /** * Test encode relationship with polymorphic data. */ - public function testEncodePolymorphicRelationship(): void + public function test_encode_polymorphic_relationship(): void { // let's hack a little bit and place additional resource(s) into relationship - $this->author->{Author::LINK_COMMENTS} = array_merge([$this->site], $this->comments); + $this->author->{Author::LINK_COMMENTS} = \array_merge([$this->site], $this->comments); $actual = Encoder::instance( [ - Author::class => function ($factory) { + Author::class => function ($factory) { $schema = new AuthorSchema($factory); $schema->hideDefaultLinksInRelationship(Author::LINK_COMMENTS); + return $schema; }, Comment::class => function ($factory) { $schema = new CommentSchema($factory); $schema->hideDefaultLinksInRelationship(Comment::LINK_AUTHOR); + return $schema; }, - Post::class => function ($factory) { + Post::class => function ($factory) { $schema = new PostSchema($factory); $schema->hideResourceLinks(); $schema->hideDefaultLinksInRelationship(Post::LINK_AUTHOR); $schema->hideDefaultLinksInRelationship(Post::LINK_COMMENTS); + return $schema; }, - Site::class => function ($factory) { + Site::class => function ($factory) { $schema = new SiteSchema($factory); $schema->hideResourceLinks(); $schema->hideDefaultLinksInRelationship(Site::LINK_POSTS); + return $schema; }, ] @@ -910,10 +933,9 @@ public function testEncodePolymorphicRelationship(): void * * @see https://github.com/neomerx/json-api/issues/121 */ - public function testEncodeRelationshipsAsLinksDoNotFollowLinksWhenIncludePathSet(): void + public function test_encode_relationships_as_links_do_not_follow_links_when_include_path_set(): void { - unset($this->post->{Post::LINK_AUTHOR}); - unset($this->post->{Post::LINK_COMMENTS}); + unset($this->post->{Post::LINK_AUTHOR}, $this->post->{Post::LINK_COMMENTS}); $actual = Encoder::instance( [ @@ -921,6 +943,7 @@ public function testEncodeRelationshipsAsLinksDoNotFollowLinksWhenIncludePathSet $schema = new PostSchema($factory); $schema->hideDefaultLinksInRelationship(Post::LINK_AUTHOR); $schema->hideDefaultLinksInRelationship(Post::LINK_COMMENTS); + return $schema; }, ] @@ -963,27 +986,30 @@ public function testEncodeRelationshipsAsLinksDoNotFollowLinksWhenIncludePathSet * * @see https://github.com/neomerx/json-api/issues/121 */ - public function testEncodeRelationshipsAsLinks(): void + public function test_encode_relationships_as_links(): void { unset($this->author->{Author::LINK_COMMENTS}); $actual = Encoder::instance( [ - Author::class => function ($factory) { + Author::class => function ($factory) { $schema = new AuthorSchema($factory); $schema->hideResourceLinks(); $schema->hideDefaultLinksInRelationship(Author::LINK_COMMENTS); + return $schema; }, Comment::class => function ($factory) { $schema = new CommentSchema($factory); $schema->removeRelationship(Comment::LINK_AUTHOR); + return $schema; }, - Post::class => function ($factory) { + Post::class => function ($factory) { $schema = new PostSchema($factory); $schema->hideDefaultLinksInRelationship(Post::LINK_AUTHOR); $schema->hideDefaultLinksInRelationship(Post::LINK_COMMENTS); + return $schema; }, ] @@ -1040,14 +1066,14 @@ public function testEncodeRelationshipsAsLinks(): void * * @see https://github.com/neomerx/json-api/issues/238 */ - public function testIterableParameterForWithIncludedPaths(): void + public function test_iterable_parameter_for_with_included_paths(): void { $author = Author::instance(238, 'Susan', 'Smith'); - $post = Post::instance(11, 'Generators and Arrays', 'A tale of incompatible types', $author); + $post = Post::instance(11, 'Generators and Arrays', 'A tale of incompatible types', $author); $encoder = Encoder::instance([ Author::class => AuthorSchema::class, - Post::class => PostSchema::class, + Post::class => PostSchema::class, ]); $encoder = $encoder->withIncludedPaths($this->generateIncludeList()); @@ -1057,9 +1083,6 @@ public function testIterableParameterForWithIncludedPaths(): void self::assertJson($json); } - /** - * @return iterable - */ private function generateIncludeList(): iterable { foreach (['author'] as $item) { diff --git a/tests/Encoder/EncodeSimpleObjectsTest.php b/tests/Encoder/EncodeSimpleObjectsTest.php index 990ea2d..0969b0a 100644 --- a/tests/Encoder/EncodeSimpleObjectsTest.php +++ b/tests/Encoder/EncodeSimpleObjectsTest.php @@ -1,8 +1,10 @@ - function ($factory) { @@ -173,13 +172,13 @@ public function testEncodeObjectWithAttributesOnly(): void /** * Test encode identifier. */ - public function testEncodeIdentifier(): void + public function test_encode_identifier(): void { $encoder = Encoder::instance([]); $identity = (new AuthorIdentity('123'))->setIdentifierMeta('id meta'); - $actual = $encoder->encodeData($identity); + $actual = $encoder->encodeData($identity); $expected = <<encodeData([$identity]); + $actual = $encoder->encodeData([$identity]); $expected = <<{Author::ATTRIBUTE_ID} = null; - $encoder = Encoder::instance( + $encoder = Encoder::instance( [ Author::class => function ($factory) { $schema = new AuthorSchema($factory); @@ -250,9 +249,9 @@ function () { * * @see https://github.com/neomerx/json-api/issues/64 */ - public function testEncodeObjectWithAttributesAndCustomLinks(): void + public function test_encode_object_with_attributes_and_custom_links(): void { - $author = Author::instance(9, 'Dan', 'Gebhardt')->setResourceMeta('resource meta'); + $author = Author::instance(9, 'Dan', 'Gebhardt')->setResourceMeta('resource meta'); $encoder = Encoder::instance( [ Author::class => function ($factory) { @@ -297,9 +296,9 @@ function ($resource) { /** * Test encode simple object as resource identity. */ - public function testEncodeObjectAsResourceIdentity(): void + public function test_encode_object_as_resource_identity(): void { - $author = Author::instance(9, 'Dan', 'Gebhardt')->setIdentifierMeta('id meta'); + $author = Author::instance(9, 'Dan', 'Gebhardt')->setIdentifierMeta('id meta'); $encoder = Encoder::instance( [ Author::class => function ($factory) { @@ -327,9 +326,9 @@ public function testEncodeObjectAsResourceIdentity(): void /** * Test encode array of simple objects as resource identity. */ - public function testEncodeArrayAsResourceIdentity(): void + public function test_encode_array_as_resource_identity(): void { - $author = Author::instance(9, 'Dan', 'Gebhardt'); + $author = Author::instance(9, 'Dan', 'Gebhardt'); $encoder = Encoder::instance( [ Author::class => AuthorSchema::class, @@ -352,15 +351,15 @@ public function testEncodeArrayAsResourceIdentity(): void /** * Test encode simple object as resource identity with included resources. */ - public function testEncodeObjectAsResourceIdentityWithIncludes(): void + public function test_encode_object_as_resource_identity_with_includes(): void { - $comment = Comment::instance(1, 'One!'); - $author = Author::instance(9, 'Dan', 'Gebhardt', [$comment]); + $comment = Comment::instance(1, 'One!'); + $author = Author::instance(9, 'Dan', 'Gebhardt', [$comment]); $comment->{Comment::LINK_AUTHOR} = $author; $actual = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => CommentSchema::class, ] ) @@ -428,9 +427,9 @@ public function testEncodeObjectAsResourceIdentityWithIncludes(): void /** * Test encode plain identifiers. */ - public function testEncodeIdentifiers(): void + public function test_encode_identifiers(): void { - $author = new AuthorIdentity("123"); + $author = new AuthorIdentity('123'); $encoder = Encoder::instance([]); $actual = $encoder->encodeIdentifiers($author); @@ -461,7 +460,7 @@ public function testEncodeIdentifiers(): void /** * Test encode plain identifiers. */ - public function testEncodeNullIdentifier(): void + public function test_encode_null_identifier(): void { $encoder = Encoder::instance([]); @@ -477,9 +476,9 @@ public function testEncodeNullIdentifier(): void /** * Test encode simple object with attributes only in array. */ - public function testEncodeObjectWithAttributesOnlyInArray(): void + public function test_encode_object_with_attributes_only_in_array(): void { - $author = Author::instance(9, 'Dan', 'Gebhardt'); + $author = Author::instance(9, 'Dan', 'Gebhardt'); $encoder = Encoder::instance( [ Author::class => function ($factory) { @@ -514,9 +513,9 @@ public function testEncodeObjectWithAttributesOnlyInArray(): void /** * Test encode simple object with attributes only associative array. */ - public function testEncodeObjectWithAttributesOnlyInAssocArray(): void + public function test_encode_object_with_attributes_only_in_assoc_array(): void { - $author = Author::instance(9, 'Dan', 'Gebhardt'); + $author = Author::instance(9, 'Dan', 'Gebhardt'); $encoder = Encoder::instance( [ Author::class => function ($factory) { @@ -551,9 +550,9 @@ public function testEncodeObjectWithAttributesOnlyInAssocArray(): void /** * Test encode simple object in pretty format. */ - public function testEncodeObjectWithAttributesOnlyPrettyPrinted(): void + public function test_encode_object_with_attributes_only_pretty_printed(): void { - $author = Author::instance(9, 'Dan', 'Gebhardt'); + $author = Author::instance(9, 'Dan', 'Gebhardt'); $encoder = Encoder::instance( [ Author::class => function ($factory) { @@ -589,7 +588,7 @@ public function testEncodeObjectWithAttributesOnlyPrettyPrinted(): void /** * Test encode array of simple objects with attributes only. */ - public function testEncodeArrayOfObjectsWithAttributesOnly(): void + public function test_encode_array_of_objects_with_attributes_only(): void { $author1 = Author::instance(7, 'First', 'Last'); $author2 = Author::instance(9, 'Dan', 'Gebhardt'); @@ -640,20 +639,20 @@ public function testEncodeArrayOfObjectsWithAttributesOnly(): void /** * Test encode meta and top-level links for simple object. */ - public function testEncodeMetaAndtopLinksForSimpleObject(): void + public function test_encode_meta_andtop_links_for_simple_object(): void { - $author = Author::instance(9, 'Dan', 'Gebhardt'); - $links = [Link::SELF => new Link(true, '/people/9', false)]; + $author = Author::instance(9, 'Dan', 'Gebhardt'); + $links = [Link::SELF => new Link(true, '/people/9', false)]; $profile = [ new LinkWithAliases(false, 'http://example.com/profiles/flexible-pagination', [], false), new LinkWithAliases(false, 'http://example.com/profiles/resource-versioning', ['version' => 'v'], false), ]; - $meta = [ - "copyright" => "Copyright 2015 Example Corp.", - "authors" => [ - "Yehuda Katz", - "Steve Klabnik", - "Dan Gebhardt", + $meta = [ + 'copyright' => 'Copyright 2015 Example Corp.', + 'authors' => [ + 'Yehuda Katz', + 'Steve Klabnik', + 'Dan Gebhardt', ], ]; @@ -715,14 +714,14 @@ public function testEncodeMetaAndtopLinksForSimpleObject(): void /** * Test encode meta. */ - public function testEncodeMeta(): void + public function test_encode_meta(): void { $meta = [ - "copyright" => "Copyright 2015 Example Corp.", - "authors" => [ - "Yehuda Katz", - "Steve Klabnik", - "Dan Gebhardt", + 'copyright' => 'Copyright 2015 Example Corp.', + 'authors' => [ + 'Yehuda Katz', + 'Steve Klabnik', + 'Dan Gebhardt', ], ]; @@ -755,7 +754,7 @@ public function testEncodeMeta(): void /** * Test encoding with JSON API version. */ - public function testEncodeJsonApiVersion(): void + public function test_encode_json_api_version(): void { $actual = Encoder::instance() ->withJsonApiVersion(Encoder::JSON_API_VERSION)->withJsonApiMeta(['some' => 'meta']) @@ -776,14 +775,14 @@ public function testEncodeJsonApiVersion(): void /** * Test encode polymorphic array (resources of different types). */ - public function testEncodePolymorphicArray(): void + public function test_encode_polymorphic_array(): void { - $author = Author::instance(7, 'First', 'Last', []); - $site = Site::instance(9, 'Main Site', []); + $author = Author::instance(7, 'First', 'Last', []); + $site = Site::instance(9, 'Main Site', []); $encoder = Encoder::instance( [ Author::class => AuthorSchema::class, - Site::class => SiteSchema::class, + Site::class => SiteSchema::class, ] )->withUrlPrefix('http://example.com'); @@ -839,9 +838,9 @@ public function testEncodePolymorphicArray(): void /** * Test encode simple object with attributes only in ArrayAccess collection. */ - public function testEncodeObjectWithAttributesOnlyInArrayAccessCollection(): void + public function test_encode_object_with_attributes_only_in_array_access_collection(): void { - $author = Author::instance(9, 'Dan', 'Gebhardt'); + $author = Author::instance(9, 'Dan', 'Gebhardt'); $encoder = Encoder::instance( [ Author::class => function ($factory) { @@ -853,7 +852,7 @@ public function testEncodeObjectWithAttributesOnlyInArrayAccessCollection(): voi ] )->withUrlPrefix('http://example.com'); - $collection = new Collection(); + $collection = new Collection(); $collection[] = $author; $actual = $encoder->encodeData($collection); @@ -879,14 +878,14 @@ public function testEncodeObjectWithAttributesOnlyInArrayAccessCollection(): voi /** * Test encode with Schema instance. * - * @link https://github.com/neomerx/json-api/issues/168 + * @see https://github.com/neomerx/json-api/issues/168 */ - public function testEncodeWithSchmaInstance(): void + public function test_encode_with_schma_instance(): void { $authorSchema = new AuthorSchema(new Factory()); $authorSchema->removeRelationship(Author::LINK_COMMENTS); - $author = Author::instance(9, 'Dan', 'Gebhardt'); + $author = Author::instance(9, 'Dan', 'Gebhardt'); $encoder = Encoder::instance( [ Author::class => $authorSchema, @@ -916,11 +915,9 @@ public function testEncodeWithSchmaInstance(): void /** * Test encode for 2 relationships that have identical name beginnings. * - * @return void - * - * @link https://github.com/neomerx/json-api/issues/200 + * @see https://github.com/neomerx/json-api/issues/200 */ - public function testEncodingSimilarRelationships(): void + public function test_encoding_similar_relationships(): void { /** * It's odd to have a second comments relationship and the naming is also weird but... @@ -930,11 +927,11 @@ public function testEncodingSimilarRelationships(): void $comment1 = Comment::instance(1, 'One!'); $comment5 = Comment::instance(5, 'Five!'); - $author = Author::instance(9, 'Dan', 'Gebhardt', [$comment1]); + $author = Author::instance(9, 'Dan', 'Gebhardt', [$comment1]); $actual = Encoder::instance( [ - Author::class => function ($factory) use ($secondRelName, $comment5) { + Author::class => function ($factory) use ($secondRelName, $comment5) { $schema = new AuthorSchema($factory); // make the author have the comment only in that odd relationship @@ -942,7 +939,7 @@ public function testEncodingSimilarRelationships(): void $schema->addToRelationship( $secondRelName, AuthorSchema::RELATIONSHIP_DATA, - fn() => [$comment5] + fn () => [$comment5] ); // hide links @@ -1021,9 +1018,9 @@ public function testEncodingSimilarRelationships(): void * * @see https://github.com/neomerx/json-api/pull/214 */ - public function testEncodeArrayBasedObject(): void + public function test_encode_array_based_object(): void { - $author = new AuthorCModel(9, 'Dan', 'Gebhardt'); + $author = new AuthorCModel(9, 'Dan', 'Gebhardt'); $encoder = Encoder::instance( [ AuthorCModel::class => AuthorCModelSchema::class, @@ -1092,15 +1089,15 @@ public function testEncodeArrayBasedObject(): void * * @see https://github.com/neomerx/json-api/pull/235 */ - public function testEncodingIdentifierArrays(): void + public function test_encoding_identifier_arrays(): void { $commentId1 = new CommentIdentity('1'); $commentId2 = new CommentIdentity('2'); - $author = Author::instance(9, 'Dan', 'Gebhardt', [$commentId1, $commentId2]); + $author = Author::instance(9, 'Dan', 'Gebhardt', [$commentId1, $commentId2]); $actual = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => CommentSchema::class, ] )->withUrlPrefix('http://example.com')->withIncludedPaths([Author::LINK_COMMENTS])->encodeData($author); diff --git a/tests/Encoder/EncodeSparseAndFieldSetsTest.php b/tests/Encoder/EncodeSparseAndFieldSetsTest.php index 854bd91..ec30fd4 100644 --- a/tests/Encoder/EncodeSparseAndFieldSetsTest.php +++ b/tests/Encoder/EncodeSparseAndFieldSetsTest.php @@ -1,8 +1,10 @@ -author = Author::instance(9, 'Dan', 'Gebhardt'); + $this->author = Author::instance(9, 'Dan', 'Gebhardt'); $this->comments = [ Comment::instance(5, 'First!', $this->author), Comment::instance(12, 'I like XML better', $this->author), ]; - $this->post = Post::instance( + $this->post = Post::instance( 1, 'JSON API paints my bikeshed!', 'Outside every fat man there was an even fatter man trying to close in', $this->author, $this->comments ); - $this->site = Site::instance(2, 'site name', [$this->post]); + $this->site = Site::instance(2, 'site name', [$this->post]); } /** * Test encode nested included objects with cyclic dependencies and sparse support. */ - public function testEncodeWithRecursiveIncludedObjects(): void + public function test_encode_with_recursive_included_objects(): void { $this->author->{Author::LINK_COMMENTS} = $this->comments; @@ -160,7 +159,7 @@ public function testEncodeWithRecursiveIncludedObjects(): void /** * Test encode nested included objects with cyclic dependencies and sparse support. */ - public function testEncodeOnlyFieldSets(): void + public function test_encode_only_field_sets(): void { $this->author->{Author::LINK_COMMENTS} = $this->comments; @@ -169,8 +168,8 @@ public function testEncodeOnlyFieldSets(): void [ // note: no filter for 'comments' 'people' => [Author::ATTRIBUTE_LAST_NAME, Author::ATTRIBUTE_FIRST_NAME], - 'posts' => [Post::LINK_COMMENTS, Post::LINK_AUTHOR], - 'sites' => [Site::LINK_POSTS], + 'posts' => [Post::LINK_COMMENTS, Post::LINK_AUTHOR], + 'sites' => [Site::LINK_POSTS], ] )->withIncludedPaths( [ @@ -257,12 +256,9 @@ public function testEncodeOnlyFieldSets(): void /** * Test that include and field-set parameters work without having to - * explicitly add the values from include in the field set as well - * - * @access public - * @return void + * explicitly add the values from include in the field set as well. */ - public function testIncludeAndSparseFieldSets(): void + public function test_include_and_sparse_field_sets(): void { $actual = Encoder::instance($this->getSchemasWithoutDefaultLinksInRelationships()) ->withUrlPrefix('http://example.com') @@ -312,7 +308,7 @@ public function testIncludeAndSparseFieldSets(): void /** * Test meta closures are not executed in lazy relationships. */ - public function testMetaNotLoadedInLazyRelationships(): void + public function test_meta_not_loaded_in_lazy_relationships(): void { $throwExClosure = function () { throw new Exception(); @@ -323,6 +319,7 @@ public function testMetaNotLoadedInLazyRelationships(): void Author::class => function ($factory) use ($throwExClosure) { $schema = new AuthorSchema($factory); $schema->addToRelationship(Author::LINK_COMMENTS, AuthorSchema::RELATIONSHIP_META, $throwExClosure); + return $schema; }, ] @@ -357,7 +354,7 @@ public function testMetaNotLoadedInLazyRelationships(): void * * @see https://github.com/neomerx/json-api/issues/105 */ - public function testIncludeAndSparseFieldSetsInGreedyMode(): void + public function test_include_and_sparse_field_sets_in_greedy_mode(): void { $this->author->{Author::LINK_COMMENTS} = $this->comments; @@ -371,10 +368,10 @@ public function testIncludeAndSparseFieldSetsInGreedyMode(): void )->withFieldSets( [ // include only these attributes and links - 'sites' => [], // note relationship resources will NOT be in included - 'posts' => [Post::LINK_AUTHOR], // note relationship resources will be in included + 'sites' => [], // note relationship resources will NOT be in included + 'posts' => [Post::LINK_AUTHOR], // note relationship resources will be in included 'comments' => [], // note relationship resources will NOT be in included - 'people' => [Author::ATTRIBUTE_LAST_NAME, Author::LINK_COMMENTS], + 'people' => [Author::ATTRIBUTE_LAST_NAME, Author::LINK_COMMENTS], ] )->encodeData($this->site); @@ -409,12 +406,9 @@ public function testIncludeAndSparseFieldSetsInGreedyMode(): void self::assertJsonStringEqualsJsonString($expected, $actual); } - /** - * @return array - */ private function getSchemasWithoutDefaultLinksInRelationships(): array { - $authorSchema = function ($factory) { + $authorSchema = function ($factory) { $schema = new AuthorSchema($factory); $schema->hideResourceLinks(); $schema->hideDefaultLinksInRelationship(Author::LINK_COMMENTS); @@ -427,7 +421,7 @@ private function getSchemasWithoutDefaultLinksInRelationships(): array return $schema; }; - $postSchema = function ($factory) { + $postSchema = function ($factory) { $schema = new PostSchema($factory); $schema->hideResourceLinks(); $schema->hideDefaultLinksInRelationship(Post::LINK_AUTHOR); @@ -435,7 +429,7 @@ private function getSchemasWithoutDefaultLinksInRelationships(): array return $schema; }; - $siteSchema = function ($factory) { + $siteSchema = function ($factory) { $schema = new SiteSchema($factory); $schema->hideDefaultLinksInRelationship(Site::LINK_POSTS); @@ -443,10 +437,10 @@ private function getSchemasWithoutDefaultLinksInRelationships(): array }; return [ - Author::class => $authorSchema, + Author::class => $authorSchema, Comment::class => $commentSchema, - Post::class => $postSchema, - Site::class => $siteSchema, + Post::class => $postSchema, + Site::class => $siteSchema, ]; } } diff --git a/tests/Encoder/EncoderTest.php b/tests/Encoder/EncoderTest.php index 4497730..7765672 100644 --- a/tests/Encoder/EncoderTest.php +++ b/tests/Encoder/EncoderTest.php @@ -1,8 +1,10 @@ -expectException(InvalidArgumentException::class); @@ -49,21 +48,22 @@ public function testEncodeInvalidData(): void ] )->withUrlPrefix('http://example.com'); - /** @noinspection PhpParamsInspection */ + /* @noinspection PhpParamsInspection */ $encoder->encodeData('input must be an object or array of objects or iterator over objects'); } /** * Test encode array of simple objects with attributes only. */ - public function testEncodeArrayOfDuplicateObjectsWithAttributesOnly(): void + public function test_encode_array_of_duplicate_objects_with_attributes_only(): void { - $author = Author::instance(9, 'Dan', 'Gebhardt'); + $author = Author::instance(9, 'Dan', 'Gebhardt'); $encoder = Encoder::instance( [ Author::class => function ($factory) { $schema = new AuthorSchema($factory); $schema->removeRelationship(Author::LINK_COMMENTS); + return $schema; }, ] @@ -105,7 +105,7 @@ public function testEncodeArrayOfDuplicateObjectsWithAttributesOnly(): void /** * Test encode 2 duplicate resources with circular link to each other. */ - public function testEncodeDuplicatesWithCircularReferencesInData(): void + public function test_encode_duplicates_with_circular_references_in_data(): void { $author = Author::instance(9, 'Dan', 'Gebhardt'); @@ -172,16 +172,16 @@ public function testEncodeDuplicatesWithCircularReferencesInData(): void /** * Test encode 2 main resource duplicates and try to apply field set filter on relations. */ - public function testEncodeDuplicatesWithRelationFieldSetFilter(): void + public function test_encode_duplicates_with_relation_field_set_filter(): void { - $author = Author::instance(9, 'Dan', 'Gebhardt'); + $author = Author::instance(9, 'Dan', 'Gebhardt'); $comments = [ Comment::instance(5, 'First!', $author), Comment::instance(12, 'I like XML better', $author), ]; - $encoder = Encoder::instance( + $encoder = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => CommentSchema::class, ] )->withUrlPrefix('http://example.com')->withFieldSets( @@ -227,13 +227,13 @@ public function testEncodeDuplicatesWithRelationFieldSetFilter(): void /** * Test encode simple resource object links. */ - public function testEncodeSimpleLinks(): void + public function test_encode_simple_links(): void { $actual = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => CommentSchema::class, - Post::class => PostSchema::class, + Post::class => PostSchema::class, ] )->withUrlPrefix('http://example.com')->encodeData($this->getStandardPost()); @@ -277,13 +277,13 @@ public function testEncodeSimpleLinks(): void /** * Test encode resource object links as references. */ - public function testEncodeEmptyLinks(): void + public function test_encode_empty_links(): void { $actual = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => CommentSchema::class, - Post::class => function ($factory) { + Post::class => function ($factory) { $schema = new PostSchema($factory); $schema->addToRelationship(Post::LINK_AUTHOR, PostSchema::RELATIONSHIP_DATA, null); $schema->addToRelationship(Post::LINK_COMMENTS, PostSchema::RELATIONSHIP_DATA, []); @@ -322,13 +322,13 @@ public function testEncodeEmptyLinks(): void /** * Test encode with 'self' and 'related' URLs in main document and relationships. */ - public function testEncodeLinksInDocumentAndRelationships(): void + public function test_encode_links_in_document_and_relationships(): void { $actual = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => CommentSchema::class, - Post::class => PostSchema::class, + Post::class => PostSchema::class, ] )->withUrlPrefix('http://example.com')->encodeData($this->getStandardPost()); @@ -372,23 +372,23 @@ public function testEncodeLinksInDocumentAndRelationships(): void /** * Test encode with 'self' and 'related' URLs in main document and relationships. */ - public function testEncodeLinkWithMeta(): void + public function test_encode_link_with_meta(): void { $comments = [ Comment::instance(5, 'First!'), Comment::instance(12, 'I like XML better'), ]; - $author = Author::instance(9, 'Dan', 'Gebhardt', $comments); - $actual = Encoder::instance( + $author = Author::instance(9, 'Dan', 'Gebhardt', $comments); + $actual = Encoder::instance( [ - Author::class => function ($factory) { + Author::class => function ($factory) { $schema = new AuthorSchema($factory); $schema->hideRelatedLinkInRelationship(Author::LINK_COMMENTS); $schema->addToRelationship( Author::LINK_COMMENTS, AuthorSchema::RELATIONSHIP_LINKS, [ - LinkInterface::SELF => fn(AuthorSchema $schema, Author $author) => new Link( + LinkInterface::SELF => fn (AuthorSchema $schema, Author $author) => new Link( true, $schema->getSelfSubUrl($author) . '/relationships/comments', true, @@ -396,6 +396,7 @@ public function testEncodeLinkWithMeta(): void ), ] ); + return $schema; }, Comment::class => CommentSchema::class, @@ -437,16 +438,16 @@ public function testEncodeLinkWithMeta(): void /** * Test add links to empty relationship. */ - public function testAddLinksToEmptyRelationship(): void + public function test_add_links_to_empty_relationship(): void { $actual = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => CommentSchema::class, - Post::class => function ($factory) { + Post::class => function ($factory) { $schema = new PostSchema($factory); $schema->removeFromRelationship(Post::LINK_AUTHOR, PostSchema::RELATIONSHIP_DATA); - $selfLink = new Link(false, 'http://foo.boo/custom-self', false); + $selfLink = new Link(false, 'http://foo.boo/custom-self', false); $relatedLink = new Link(false, 'http://foo.boo/custom-related', false); $schema->setSelfLinkInRelationship(Post::LINK_AUTHOR, $selfLink); $schema->setRelatedLinkInRelationship(Post::LINK_AUTHOR, $relatedLink); @@ -460,7 +461,7 @@ public function testAddLinksToEmptyRelationship(): void Post::LINK_COMMENTS, PostSchema::RELATIONSHIP_LINKS, [ - 'boo' => fn(PostSchema $schema, Post $post) => new Link(true, $schema->getSelfSubUrl($post) . '/another/link', false), + 'boo' => fn (PostSchema $schema, Post $post) => new Link(true, $schema->getSelfSubUrl($post) . '/another/link', false), ] ); $schema->hideRelatedLinkInRelationship(Post::LINK_COMMENTS); @@ -506,13 +507,13 @@ public function testAddLinksToEmptyRelationship(): void /** * Test add meta to empty relationship. */ - public function testAddMetaToEmptyRelationship(): void + public function test_add_meta_to_empty_relationship(): void { $actual = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => CommentSchema::class, - Post::class => function ($factory) { + Post::class => function ($factory) { $schema = new PostSchema($factory); $schema->removeFromRelationship(Post::LINK_AUTHOR, PostSchema::RELATIONSHIP_DATA); $schema->hideDefaultLinksInRelationship(Post::LINK_AUTHOR); @@ -522,8 +523,9 @@ public function testAddMetaToEmptyRelationship(): void $schema->addToRelationship( Post::LINK_COMMENTS, PostSchema::RELATIONSHIP_META, - fn() => ['comments' => 'meta'] + fn () => ['comments' => 'meta'] ); + return $schema; }, ] @@ -558,13 +560,13 @@ public function testAddMetaToEmptyRelationship(): void /** * Test hide data section if it is omitted in Schema. */ - public function testHideDataSectionIfOmittedInSchema() + public function test_hide_data_section_if_omitted_in_schema() { $actual = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => CommentSchema::class, - Post::class => function ($factory) { + Post::class => function ($factory) { $schema = new PostSchema($factory); $schema->removeFromRelationship(Post::LINK_AUTHOR, PostSchema::RELATIONSHIP_DATA); $schema->hideSelfLinkInRelationship(Post::LINK_AUTHOR); @@ -578,7 +580,7 @@ public function testHideDataSectionIfOmittedInSchema() Post::LINK_COMMENTS, PostSchema::RELATIONSHIP_LINKS, [ - 'boo' => fn(PostSchema $schema, Post $post) => new Link(true, $schema->getSelfSubUrl($post) . '/another/link', false), + 'boo' => fn (PostSchema $schema, Post $post) => new Link(true, $schema->getSelfSubUrl($post) . '/another/link', false), ] ); $schema->hideRelatedLinkInRelationship(Post::LINK_COMMENTS); @@ -620,14 +622,15 @@ public function testHideDataSectionIfOmittedInSchema() /** * Test encode Traversable (through Iterator) collection of resource(s). */ - public function testEncodeTraversableObjectsWithAttributesOnly(): void + public function test_encode_traversable_objects_with_attributes_only(): void { - $author = Author::instance(9, 'Dan', 'Gebhardt'); + $author = Author::instance(9, 'Dan', 'Gebhardt'); $encoder = Encoder::instance( [ - Author::class => function ($factory) { + Author::class => function ($factory) { $schema = new AuthorSchema($factory); $schema->hideDefaultLinksInRelationship(Author::LINK_COMMENTS); + return $schema; }, Comment::class => CommentSchema::class, @@ -644,7 +647,7 @@ public function testEncodeTraversableObjectsWithAttributesOnly(): void // and iterator here $itemSet = new ArrayIterator(['what_if_its_not_zero_based_array' => $author]); - $actual = $encoder->encodeData($itemSet); + $actual = $encoder->encodeData($itemSet); $expected = << CommentSchema::class, - Post::class => function ($factory) { + Post::class => function ($factory) { $schema = new PostSchema($factory); $schema->removeRelationship(Post::LINK_AUTHOR); $schema->hideDefaultLinksInRelationship(Post::LINK_COMMENTS); + return $schema; }, ] @@ -721,9 +725,9 @@ public function testEncodeRelationshipWithSingleItem(): void /** * Test encode with relationship self Link. */ - public function testEncodeWithRelationshipSelfLink(): void + public function test_encode_with_relationship_self_link(): void { - $post = $this->getStandardPost(); + $post = $this->getStandardPost(); $actual = Encoder::instance( [ Post::class => PostSchema::class, @@ -744,9 +748,9 @@ public function testEncodeWithRelationshipSelfLink(): void /** * Test encode with relationship related Link. */ - public function testEncodeWithRelationshipRelatedLink(): void + public function test_encode_with_relationship_related_link(): void { - $post = $this->getStandardPost(); + $post = $this->getStandardPost(); $actual = Encoder::instance( [ Post::class => PostSchema::class, @@ -767,7 +771,7 @@ public function testEncodeWithRelationshipRelatedLink(): void /** * Test encode unrecognized resource (no registered Schema). */ - public function testEncodeUnrecognizedResourceAtRoot(): void + public function test_encode_unrecognized_resource_at_root(): void { $author = Author::instance(9, 'Dan', 'Gebhardt'); @@ -790,10 +794,10 @@ public function testEncodeUnrecognizedResourceAtRoot(): void /** * Test encode unrecognized resource (no registered Schema). */ - public function testEncodeUnrecognizedResourceInRelationship(): void + public function test_encode_unrecognized_resource_in_relationship(): void { $author = Author::instance(9, 'Dan', 'Gebhardt'); - $post = Post::instance(1, 'Title', 'Body', null, [Comment::instance(5, 'First!', $author)]); + $post = Post::instance(1, 'Title', 'Body', null, [Comment::instance(5, 'First!', $author)]); /** @var InvalidArgumentException $catch */ $catch = null; @@ -801,7 +805,7 @@ public function testEncodeUnrecognizedResourceInRelationship(): void Encoder::instance( [ Comment::class => CommentSchema::class, - Post::class => PostSchema::class, + Post::class => PostSchema::class, ] )->withUrlPrefix('http://example.com')->withIncludedPaths( [ @@ -821,12 +825,12 @@ public function testEncodeUnrecognizedResourceInRelationship(): void */ private function getStandardPost() { - $author = Author::instance(9, 'Dan', 'Gebhardt'); + $author = Author::instance(9, 'Dan', 'Gebhardt'); $comments = [ Comment::instance(5, 'First!'), Comment::instance(12, 'I like XML better'), ]; - $post = Post::instance( + $post = Post::instance( 1, 'JSON API paints my bikeshed!', 'Outside every fat man there was an even fatter man trying to close in', diff --git a/tests/Exceptions/JsonApiExceptionTest.php b/tests/Exceptions/JsonApiExceptionTest.php index 3d6f7fb..da91802 100644 --- a/tests/Exceptions/JsonApiExceptionTest.php +++ b/tests/Exceptions/JsonApiExceptionTest.php @@ -1,8 +1,10 @@ -collection = new ErrorCollection(); - $this->error = new Error('some-id', null, null, '404', 'some-code', 'some title', 'some details'); + $this->error = new Error('some-id', null, null, '404', 'some-code', 'some title', 'some details'); } /** - * @inheritdoc + * {@inheritdoc} */ - public function testCreateExceptionFromError(): void + public function test_create_exception_from_error(): void { $exception = new JsonApiException($this->error, 432); $this->assertEquals(432, $exception->getHttpCode()); @@ -55,9 +54,9 @@ public function testCreateExceptionFromError(): void } /** - * @inheritdoc + * {@inheritdoc} */ - public function testCreateExceptionFromErrorArray(): void + public function test_create_exception_from_error_array(): void { $exception = new JsonApiException([$this->error]); $this->assertEquals(JsonApiException::DEFAULT_HTTP_CODE, $exception->getHttpCode()); @@ -66,9 +65,9 @@ public function testCreateExceptionFromErrorArray(): void } /** - * @inheritdoc + * {@inheritdoc} */ - public function testCreateExceptionFromErrorCollection(): void + public function test_create_exception_from_error_collection(): void { $this->collection->add($this->error); $exception = new JsonApiException($this->collection); diff --git a/tests/Extensions/Issue154/CustomContainerInterface.php b/tests/Extensions/Issue154/CustomContainerInterface.php index 1c2afc0..ec6a209 100644 --- a/tests/Extensions/Issue154/CustomContainerInterface.php +++ b/tests/Extensions/Issue154/CustomContainerInterface.php @@ -1,8 +1,10 @@ -addSchema(Author::class, AuthorSchema::class); $author = Author::instance(9, 'Dan', 'Gebhardt'); diff --git a/tests/Extensions/Issue169/CustomEncoder.php b/tests/Extensions/Issue169/CustomEncoder.php index f766b75..a5129d6 100644 --- a/tests/Extensions/Issue169/CustomEncoder.php +++ b/tests/Extensions/Issue169/CustomEncoder.php @@ -1,8 +1,10 @@ -encodeIdentifiersToArray($data); } - /** - * @param ErrorInterface $error - * - * @return array - */ public function serializeError(ErrorInterface $error): array { return $this->encodeErrorToArray($error); @@ -69,8 +51,6 @@ public function serializeError(ErrorInterface $error): array /** * @param ErrorInterface[]|ErrorCollection $errors - * - * @return array */ public function serializeErrors($errors): array { @@ -79,11 +59,14 @@ public function serializeErrors($errors): array /** * @param array|object $meta - * - * @return array */ public function serializeMeta($meta): array { return $this->encodeMetaToArray($meta); } + + protected static function createFactory(): FactoryInterface + { + return new CustomFactory(); + } } diff --git a/tests/Extensions/Issue169/CustomFactory.php b/tests/Extensions/Issue169/CustomFactory.php index 5cd4b01..0b132d3 100644 --- a/tests/Extensions/Issue169/CustomFactory.php +++ b/tests/Extensions/Issue169/CustomFactory.php @@ -1,8 +1,10 @@ - function ($factory) { $schema = new AuthorSchema($factory); $schema->removeRelationship(Author::LINK_COMMENTS); + return $schema; }, ] @@ -51,13 +51,13 @@ public function testDataSerialization(): void $expected = [ 'data' => [ - 'type' => 'people', - 'id' => '9', + 'type' => 'people', + 'id' => '9', 'attributes' => [ 'first_name' => 'Dan', - 'last_name' => 'Gebhardt', + 'last_name' => 'Gebhardt', ], - 'links' => [ + 'links' => [ 'self' => '/people/9', ], ], @@ -71,7 +71,7 @@ public function testDataSerialization(): void * * @see https://github.com/neomerx/json-api/issues/169 */ - public function testIdentifiersSerialization(): void + public function test_identifiers_serialization(): void { $author = Author::instance(9, 'Dan', 'Gebhardt'); /** @var CustomEncoder $encoder */ @@ -86,7 +86,7 @@ public function testIdentifiersSerialization(): void $expected = [ 'data' => [ 'type' => 'people', - 'id' => '9', + 'id' => '9', ], ]; @@ -98,7 +98,7 @@ public function testIdentifiersSerialization(): void * * @see https://github.com/neomerx/json-api/issues/169 */ - public function testErrorSerialization(): void + public function test_error_serialization(): void { $error = new Error('some-id'); /** @var CustomEncoder $encoder */ @@ -113,7 +113,7 @@ public function testErrorSerialization(): void * * @see https://github.com/neomerx/json-api/issues/169 */ - public function testMetaSerialization(): void + public function test_meta_serialization(): void { $meta = ['some meta']; /** @var CustomEncoder $encoder */ diff --git a/tests/Extensions/Issue231/CustomEncoder.php b/tests/Extensions/Issue231/CustomEncoder.php index 8ea571d..9c66d6a 100644 --- a/tests/Extensions/Issue231/CustomEncoder.php +++ b/tests/Extensions/Issue231/CustomEncoder.php @@ -1,8 +1,10 @@ -cachedPathsResults) === true) { + if (true === \array_key_exists($path, $this->cachedPathsResults)) { return $this->cachedPathsResults[$path]; } $normalizedPaths = $this->getNormalizedPaths(); - $result = + $result = isset($normalizedPaths[$path]) || isset($normalizedPaths[static::PATH_WILDCARD_ALL]) || $this->doesMatchSubPath($path); @@ -51,20 +50,15 @@ public function isPathRequested(string $path): bool return $result; } - /** - * @param string $path - * - * @return bool - */ private function doesMatchSubPath(string $path): bool { $normalizedPaths = $this->getNormalizedPaths(); - $separator = DocumentInterface::PATH_SEPARATOR; + $separator = DocumentInterface::PATH_SEPARATOR; // check if any wildcard like a.*, a.b.* is requested $curPath = ''; foreach (\explode($separator, $path) as $part) { - $curPath .= $part . $separator; + $curPath .= $part . $separator; $wildcardPath = $curPath . static::PATH_WILDCARD_ALL; if (isset($normalizedPaths[$wildcardPath])) { return true; diff --git a/tests/Extensions/Issue231/IssueTest.php b/tests/Extensions/Issue231/IssueTest.php index 8ab42ef..d3414be 100644 --- a/tests/Extensions/Issue231/IssueTest.php +++ b/tests/Extensions/Issue231/IssueTest.php @@ -1,8 +1,10 @@ -prepareSchemas()) ->withUrlPrefix('http://example.com') @@ -49,7 +48,7 @@ public function testDataSerializationWithPartialWildcard(): void . DocumentInterface::PATH_SEPARATOR . Post::LINK_COMMENTS . DocumentInterface::PATH_SEPARATOR - . CustomEncoder::PATH_WILDCARD_ALL + . CustomEncoder::PATH_WILDCARD_ALL, ] ) ->encodeData($this->prepareDataToEncode()); @@ -141,7 +140,7 @@ public function testDataSerializationWithPartialWildcard(): void * * @see https://github.com/neomerx/json-api/issues/231 */ - public function testDataSerializationWithFullWildcard(): void + public function test_data_serialization_with_full_wildcard(): void { $actual = CustomEncoder::instance($this->prepareSchemas()) ->withUrlPrefix('http://example.com') @@ -244,12 +243,9 @@ public function testDataSerializationWithFullWildcard(): void self::assertJsonStringEqualsJsonString($expected, $actual); } - /** - * @return Site - */ private function prepareDataToEncode(): Site { - $author = Author::instance(9, 'Dan', 'Gebhardt'); + $author = Author::instance(9, 'Dan', 'Gebhardt'); $commentAuthor = Author::instance(42, 'Peter', 'Weller'); $comments = [ @@ -268,9 +264,6 @@ private function prepareDataToEncode(): Site return Site::instance(2, 'site name', [$post]); } - /** - * @return array - */ private function prepareSchemas(): array { return [ @@ -300,7 +293,7 @@ private function prepareSchemas(): array $schema->hideDefaultLinksInRelationship(Site::LINK_POSTS); return $schema; - } + }, ]; } } diff --git a/tests/Extensions/Issue236/BaseCustomSchema.php b/tests/Extensions/Issue236/BaseCustomSchema.php index 6f08083..20a2147 100644 --- a/tests/Extensions/Issue236/BaseCustomSchema.php +++ b/tests/Extensions/Issue236/BaseCustomSchema.php @@ -1,8 +1,10 @@ -{Author::ATTRIBUTE_ID}; + return (string) $resource->{Author::ATTRIBUTE_ID}; } /** - * @inheritdoc + * {@inheritdoc} */ public function getAttributes($resource, ContextInterface $context): iterable { @@ -53,12 +52,12 @@ public function getAttributes($resource, ContextInterface $context): iterable return [ Author::ATTRIBUTE_FIRST_NAME => $resource->{Author::ATTRIBUTE_FIRST_NAME}, - Author::ATTRIBUTE_LAST_NAME => $resource->{Author::ATTRIBUTE_LAST_NAME}, + Author::ATTRIBUTE_LAST_NAME => $resource->{Author::ATTRIBUTE_LAST_NAME}, ]; } /** - * @inheritdoc + * {@inheritdoc} */ public function getNonHorrificRelationships($resource, string $currentPath): iterable { @@ -70,16 +69,16 @@ public function getNonHorrificRelationships($resource, string $currentPath): ite return [ Author::LINK_COMMENTS => [ self::RELATIONSHIP_LINKS_RELATED => false, - self::RELATIONSHIP_HAS_DATA => false, - self::RELATIONSHIP_DATA => function (): void { + self::RELATIONSHIP_HAS_DATA => false, + self::RELATIONSHIP_DATA => function (): void { throw new \LogicException('I told you, I don\'t have any data.'); }, - self::RELATIONSHIP_META => [ - 'current_path' => $currentPath, - 'fields_filter' => $this->getSchemaFields()->getRequestedFields($this->getType()), + self::RELATIONSHIP_META => [ + 'current_path' => $currentPath, + 'fields_filter' => $this->getSchemaFields()->getRequestedFields($this->getType()), 'relationships_to_include' => $this->getSchemaFields()->getRequestedRelationships($currentPath), ], - ] + ], ]; } } diff --git a/tests/Extensions/Issue236/CustomCommentSchema.php b/tests/Extensions/Issue236/CustomCommentSchema.php index d0e101d..21434c5 100644 --- a/tests/Extensions/Issue236/CustomCommentSchema.php +++ b/tests/Extensions/Issue236/CustomCommentSchema.php @@ -1,8 +1,10 @@ -{Comment::ATTRIBUTE_ID}; + return (string) $resource->{Comment::ATTRIBUTE_ID}; } /** - * @inheritdoc + * {@inheritdoc} */ public function getAttributes($resource, ContextInterface $context): iterable { @@ -57,7 +56,7 @@ public function getAttributes($resource, ContextInterface $context): iterable } /** - * @inheritdoc + * {@inheritdoc} */ public function getNonHorrificRelationships($resource, string $currentPath): iterable { @@ -68,14 +67,14 @@ public function getNonHorrificRelationships($resource, string $currentPath): ite return [ Comment::LINK_AUTHOR => [ - self::RELATIONSHIP_DATA => $resource->{Comment::LINK_AUTHOR}, + self::RELATIONSHIP_DATA => $resource->{Comment::LINK_AUTHOR}, self::RELATIONSHIP_LINKS_RELATED => false, - self::RELATIONSHIP_META => [ - 'current_path' => $currentPath, - 'fields_filter' => $this->getSchemaFields()->getRequestedFields($this->getType()), + self::RELATIONSHIP_META => [ + 'current_path' => $currentPath, + 'fields_filter' => $this->getSchemaFields()->getRequestedFields($this->getType()), 'relationships_to_include' => $this->getSchemaFields()->getRequestedRelationships($currentPath), ], - ] + ], ]; } } diff --git a/tests/Extensions/Issue236/CustomEncoder.php b/tests/Extensions/Issue236/CustomEncoder.php index dda94c5..545b412 100644 --- a/tests/Extensions/Issue236/CustomEncoder.php +++ b/tests/Extensions/Issue236/CustomEncoder.php @@ -1,8 +1,10 @@ -factory = $factory; + $this->factory = $factory; $this->container = $container; - $this->data = $data; + $this->data = $data; $this->schema = $container->getSchema($data); @@ -74,16 +73,16 @@ public function __construct( } /** - * @inheritdoc + * {@inheritdoc} */ public function getRelationships(): iterable { - $currentPath = $this->getPosition()->getPath(); - $nextLevel = $this->getPosition()->getLevel() + 1; - $nextPathPrefix = empty($currentPath) === true ? '' : $currentPath . PositionInterface::PATH_SEPARATOR; + $currentPath = $this->getPosition()->getPath(); + $nextLevel = $this->getPosition()->getLevel() + 1; + $nextPathPrefix = true === empty($currentPath) ? '' : $currentPath . PositionInterface::PATH_SEPARATOR; foreach ($this->schema->getNonHorrificRelationships($this->data, $currentPath) as $name => $description) { - if (\array_key_exists(BaseCustomSchema::RELATIONSHIP_HAS_DATA, $description) === true && - $description[BaseCustomSchema::RELATIONSHIP_HAS_DATA] === false) { + if (true === \array_key_exists(BaseCustomSchema::RELATIONSHIP_HAS_DATA, $description) && + false === $description[BaseCustomSchema::RELATIONSHIP_HAS_DATA]) { unset($description[BaseCustomSchema::RELATIONSHIP_DATA]); } [$hasData, $relationshipData, $nextPosition] = $this->parseRelationshipData( @@ -100,7 +99,7 @@ public function getRelationships(): iterable [$hasLinks, $links] = $this->parseRelationshipLinks($this->schema, $this->data, $name, $description); $hasMeta = \array_key_exists(SchemaInterface::RELATIONSHIP_META, $description); - $meta = $hasMeta === true ? $description[SchemaInterface::RELATIONSHIP_META] : null; + $meta = true === $hasMeta ? $description[SchemaInterface::RELATIONSHIP_META] : null; $relationship = $this->factory->createRelationship( $nextPosition, diff --git a/tests/Extensions/Issue236/IssueTest.php b/tests/Extensions/Issue236/IssueTest.php index 17eeeec..8b795d5 100644 --- a/tests/Extensions/Issue236/IssueTest.php +++ b/tests/Extensions/Issue236/IssueTest.php @@ -1,8 +1,10 @@ -prepareSchemas($pathsToInclude, $fieldSetFilters)) @@ -100,30 +99,21 @@ public function testDataSerializationWithPartialWildcard(): void self::assertJsonStringEqualsJsonString($expected, $actual); } - /** - * @return Comment - */ private function prepareDataToEncode(): Comment { - $author = Author::instance(42, 'Peter', 'Weller'); + $author = Author::instance(42, 'Peter', 'Weller'); $comment = Comment::instance(5, 'First!', $author); return $comment; } - /** - * @param iterable $expectedIncludePaths - * @param iterable $expectedFieldSetFilters - * - * @return array - */ private function prepareSchemas(iterable $expectedIncludePaths, iterable $expectedFieldSetFilters): array { $schemaFields = new SchemaFields($expectedIncludePaths, $expectedFieldSetFilters); return [ - Author::class => fn($factory) => new CustomAuthorSchema($factory, $schemaFields), - Comment::class => fn($factory) => new CustomCommentSchema($factory, $schemaFields), + Author::class => fn ($factory) => new CustomAuthorSchema($factory, $schemaFields), + Comment::class => fn ($factory) => new CustomCommentSchema($factory, $schemaFields), ]; } } diff --git a/tests/Extensions/Issue236/SchemaFields.php b/tests/Extensions/Issue236/SchemaFields.php index da1c1ad..40e3428 100644 --- a/tests/Extensions/Issue236/SchemaFields.php +++ b/tests/Extensions/Issue236/SchemaFields.php @@ -1,8 +1,10 @@ -fastRelationships[$curPath][$relationship] = true; - $this->fastRelationshipLists[$curPath][] = $relationship; + $this->fastRelationshipLists[$curPath][] = $relationship; } foreach ($fieldSets as $type => $fieldList) { - foreach (explode(static::FIELD_SEPARATOR, $fieldList) as $field) { + foreach (\explode(static::FIELD_SEPARATOR, $fieldList) as $field) { $this->fastFields[$type][$field] = true; - $this->fastFieldLists[$type][] = $field; + $this->fastFieldLists[$type][] = $field; } } } - /** - * @param string $currentPath - * @param string $relationship - * - * @return bool - */ public function isRelationshipRequested(string $currentPath, string $relationship): bool { return isset($this->fastRelationships[$currentPath][$relationship]); } - /** - * @param string $currentPath - * - * @return array - */ public function getRequestedRelationships(string $currentPath): array { return $this->fastRelationshipLists[$currentPath] ?? []; } - /** - * @param string $type - * @param string $field - * - * @return bool - */ public function isFieldRequested(string $type, string $field): bool { - return array_key_exists($type, $this->fastFields) === false ? true : isset($this->fastFields[$type][$field]); + return false === \array_key_exists($type, $this->fastFields) ? true : isset($this->fastFields[$type][$field]); } - /** - * @param string $type - * - * @return array|null - */ public function getRequestedFields(string $type): ?array { return $this->fastFieldLists[$type] ?? null; diff --git a/tests/Extensions/Issue236/SchemaFieldsTrait.php b/tests/Extensions/Issue236/SchemaFieldsTrait.php index 86de172..8d58a8d 100644 --- a/tests/Extensions/Issue236/SchemaFieldsTrait.php +++ b/tests/Extensions/Issue236/SchemaFieldsTrait.php @@ -1,9 +1,11 @@ -schemaFields; } - /** - * @param SchemaFields $schemaFields - * - * @return void - */ public function setSchemaFields(SchemaFields $schemaFields): void { $this->schemaFields = $schemaFields; diff --git a/tests/Extensions/Issue47/CustomEncoder.php b/tests/Extensions/Issue47/CustomEncoder.php index fcd1652..ffb2a21 100644 --- a/tests/Extensions/Issue47/CustomEncoder.php +++ b/tests/Extensions/Issue47/CustomEncoder.php @@ -1,8 +1,10 @@ -hasFilter($type) === true) { + if (true === $this->hasFilter($type)) { $allowedFields = $this->getAllowedFields($type); - $fields = $this->iterableToArray($fields); + $fields = $this->iterableToArray($fields); $this->deepArrayFilter($fields, $allowedFields, ''); } @@ -41,34 +40,22 @@ protected function filterFields(string $type, iterable $fields): iterable yield from $fields; } - /** - * @param iterable $iterable - * - * @return array - */ private function iterableToArray(iterable $iterable): array { - if (is_array($iterable) === true) { + if (true === \is_array($iterable)) { return $iterable; - } else { - assert($iterable instanceof Traversable); - return iterator_to_array($iterable); } + \assert($iterable instanceof Traversable); + + return \iterator_to_array($iterable); } - /** - * @param array $array - * @param array $filters - * @param string $parentPath - * - * @return void - */ private function deepArrayFilter(array &$array, array $filters, string $parentPath): void { foreach ($array as $key => &$value) { - $filterKey = empty($parentPath) === true ? $key : $parentPath . '.' . $key; - if (is_array($value) === false) { - if (array_key_exists($filterKey, $filters) === false) { + $filterKey = true === empty($parentPath) ? $key : $parentPath . '.' . $key; + if (false === \is_array($value)) { + if (false === \array_key_exists($filterKey, $filters)) { unset($array[$key]); } } else { diff --git a/tests/Extensions/Issue47/IssueTest.php b/tests/Extensions/Issue47/IssueTest.php index e282d41..3b9899e 100644 --- a/tests/Extensions/Issue47/IssueTest.php +++ b/tests/Extensions/Issue47/IssueTest.php @@ -1,8 +1,10 @@ - 'hello@vivalacrowe.com', 'name' => 'Rob']); diff --git a/tests/Extensions/Issue47/User.php b/tests/Extensions/Issue47/User.php index 36d243e..9855169 100644 --- a/tests/Extensions/Issue47/User.php +++ b/tests/Extensions/Issue47/User.php @@ -1,9 +1,11 @@ -identity = $identity; - $this->name = $name; + $this->identity = $identity; + $this->name = $name; $this->contactDetails = $contactDetails; } } diff --git a/tests/Extensions/Issue47/UserBaseSchema.php b/tests/Extensions/Issue47/UserBaseSchema.php index f1c02f3..471f6d5 100644 --- a/tests/Extensions/Issue47/UserBaseSchema.php +++ b/tests/Extensions/Issue47/UserBaseSchema.php @@ -1,8 +1,10 @@ -identity; } /** - * @inheritdoc + * {@inheritdoc} */ public function getAttributes($user, ContextInterface $context): iterable { - assert($user instanceof User); + \assert($user instanceof User); return [ 'username' => $user->name, - 'private' => $user->contactDetails, + 'private' => $user->contactDetails, ]; } /** - * @inheritdoc + * {@inheritdoc} */ public function getRelationships($resource, ContextInterface $context): iterable { diff --git a/tests/Extensions/Issue67/CustomEncoder.php b/tests/Extensions/Issue67/CustomEncoder.php index 4f5c88e..8f0368f 100644 --- a/tests/Extensions/Issue67/CustomEncoder.php +++ b/tests/Extensions/Issue67/CustomEncoder.php @@ -1,8 +1,10 @@ -assertEquals(CustomEncoder::class, get_class($childEncoder)); + $this->assertEquals(CustomEncoder::class, \get_class($childEncoder)); } } diff --git a/tests/Extensions/Issue81/CommentSchema.php b/tests/Extensions/Issue81/CommentSchema.php index c71c0ac..237aefb 100644 --- a/tests/Extensions/Issue81/CommentSchema.php +++ b/tests/Extensions/Issue81/CommentSchema.php @@ -1,8 +1,10 @@ -{Comment::LINK_AUTHOR}; - $authorId = (string)$author->{Author::ATTRIBUTE_ID}; + $author = $comment->{Comment::LINK_AUTHOR}; + $authorId = (string) $author->{Author::ATTRIBUTE_ID}; $authorIdentity = new AuthorIdentity($authorId); - $hasMeta = property_exists($author, Author::IDENTIFIER_META); - if ($hasMeta === true) { + $hasMeta = \property_exists($author, Author::IDENTIFIER_META); + if (true === $hasMeta) { $authorIdentity->setIdentifierMeta($author->{Author::IDENTIFIER_META}); } diff --git a/tests/Extensions/Issue81/IssueTest.php b/tests/Extensions/Issue81/IssueTest.php index c01e28d..9f40317 100644 --- a/tests/Extensions/Issue81/IssueTest.php +++ b/tests/Extensions/Issue81/IssueTest.php @@ -1,8 +1,10 @@ -setIdentifierMeta('id meta'); - $comment = Comment::instance(123, 'Comment body', $author); + $author = Author::instance(321, 'John', 'Dow')->setIdentifierMeta('id meta'); + $comment = Comment::instance(123, 'Comment body', $author); $author->{Author::LINK_COMMENTS} = [$comment]; $actual = Encoder::instance( diff --git a/tests/Extensions/Issue82/AuthorSchema.php b/tests/Extensions/Issue82/AuthorSchema.php index 38806d2..f7bdbab 100644 --- a/tests/Extensions/Issue82/AuthorSchema.php +++ b/tests/Extensions/Issue82/AuthorSchema.php @@ -1,8 +1,10 @@ -author_id; + return (string) $author->author_id; } /** - * @inheritdoc + * {@inheritdoc} */ public function getAttributes($author, ContextInterface $context): iterable { return [ 'first-name' => $author->first_name, - 'last-name' => $author->last_name, + 'last-name' => $author->last_name, ]; } /** - * @inheritdoc + * {@inheritdoc} */ public function getRelationships($author, ContextInterface $context): iterable { return [ 'comments' => [ - self::RELATIONSHIP_LINKS_SELF => false, + self::RELATIONSHIP_LINKS_SELF => false, self::RELATIONSHIP_LINKS_RELATED => true, // Data could be included as well diff --git a/tests/Extensions/Issue82/IssueTest.php b/tests/Extensions/Issue82/IssueTest.php index bc9c829..b53f3b8 100644 --- a/tests/Extensions/Issue82/IssueTest.php +++ b/tests/Extensions/Issue82/IssueTest.php @@ -1,8 +1,10 @@ - AuthorSchema::class, diff --git a/tests/Extensions/Issue91/Category.php b/tests/Extensions/Issue91/Category.php index 91fe5a5..b150e35 100644 --- a/tests/Extensions/Issue91/Category.php +++ b/tests/Extensions/Issue91/Category.php @@ -1,9 +1,11 @@ -index = $index; + $this->index = $index; $this->description = $description; - $this->parent = $parent; + $this->parent = $parent; } } diff --git a/tests/Extensions/Issue91/CategorySchema.php b/tests/Extensions/Issue91/CategorySchema.php index 237f10d..9749e77 100644 --- a/tests/Extensions/Issue91/CategorySchema.php +++ b/tests/Extensions/Issue91/CategorySchema.php @@ -1,8 +1,10 @@ -index; + return (string) $resource->index; } /** - * @inheritdoc + * {@inheritdoc} */ public function getAttributes($resource, ContextInterface $context): iterable { - /** @var Category $resource */ + /* @var Category $resource */ return [ 'description' => $resource->description, ]; } /** - * @inheritdoc + * {@inheritdoc} */ public function getRelationships($resource, ContextInterface $context): iterable { - /** @var Category $resource */ + /* @var Category $resource */ return [ 'parent' => [self::RELATIONSHIP_DATA => $resource->parent], ]; } /** - * @inheritdoc + * {@inheritdoc} */ public function isAddSelfLinkInRelationshipByDefault(string $relationshipName): bool { @@ -75,7 +74,7 @@ public function isAddSelfLinkInRelationshipByDefault(string $relationshipName): } /** - * @inheritdoc + * {@inheritdoc} */ public function isAddRelatedLinkInRelationshipByDefault(string $relationshipName): bool { diff --git a/tests/Extensions/Issue91/IssueTest.php b/tests/Extensions/Issue91/IssueTest.php index c456fcb..200c5ff 100644 --- a/tests/Extensions/Issue91/IssueTest.php +++ b/tests/Extensions/Issue91/IssueTest.php @@ -1,8 +1,10 @@ -createHierarchy(); @@ -138,12 +137,12 @@ public function testEncodeHierarchy(): void */ private function createHierarchy() { - $main = new Category(1, 'Main'); + $main = new Category(1, 'Main'); $laptop = new Category(2, 'Laptop', $main); - $pc = new Category(3, 'PC', $main); + $pc = new Category(3, 'PC', $main); $screen = new Category(4, 'Screen', $laptop); - $big = new Category(5, 'Big', $screen); - $small = new Category(6, 'Small', $screen); + $big = new Category(5, 'Big', $screen); + $small = new Category(6, 'Small', $screen); return [$main, $laptop, $pc, $screen, $big, $small]; } diff --git a/tests/Http/Headers/AcceptHeaderTest.php b/tests/Http/Headers/AcceptHeaderTest.php index 31e8b61..4d664ae 100644 --- a/tests/Http/Headers/AcceptHeaderTest.php +++ b/tests/Http/Headers/AcceptHeaderTest.php @@ -1,8 +1,10 @@ - 'param'], 0.5), @@ -42,7 +39,7 @@ public function testCompare1(): void new AcceptMediaType(2, '*', '*'), ]; - usort($types, AcceptMediaType::getCompare()); + \usort($types, AcceptMediaType::getCompare()); $this->checkSorting( [ @@ -57,13 +54,13 @@ public function testCompare1(): void self::assertEquals('*', $types[0]->getSubType()); self::assertEquals('type/*', $types[0]->getMediaType()); self::assertEquals(1, $types[0]->getQuality()); - self::assertEquals(null, $types[0]->getParameters()); + self::assertNull($types[0]->getParameters()); self::assertEquals('*', $types[1]->getType()); self::assertEquals('*', $types[1]->getSubType()); self::assertEquals('*/*', $types[1]->getMediaType()); self::assertEquals(1, $types[1]->getQuality()); - self::assertEquals(null, $types[1]->getParameters()); + self::assertNull($types[1]->getParameters()); self::assertEquals('foo', $types[2]->getType()); self::assertEquals('bar.baz', $types[2]->getSubType()); @@ -74,17 +71,15 @@ public function testCompare1(): void /** * Test compare. - * - * @return void */ - public function testCompareByQuality1(): void + public function test_compare_by_quality1(): void { $types = [ new AcceptMediaType(0, 'foo', 'bar', [], 0.5), new AcceptMediaType(1, 'boo', 'baz', [], 0.6), ]; - usort($types, AcceptMediaType::getCompare()); + \usort($types, AcceptMediaType::getCompare()); $this->checkSorting( [ @@ -109,17 +104,15 @@ public function testCompareByQuality1(): void /** * Test compare. - * - * @return void */ - public function testCompareByQuality2(): void + public function test_compare_by_quality2(): void { $types = [ new AcceptMediaType(0, 'foo', 'bar', [], 0.5001), new AcceptMediaType(1, 'boo', 'baz', [], 0.5009), ]; - usort($types, AcceptMediaType::getCompare()); + \usort($types, AcceptMediaType::getCompare()); $this->checkSorting( [ @@ -132,18 +125,16 @@ public function testCompareByQuality2(): void /** * Test compare. - * - * @return void */ - public function testCompareBySubType(): void + public function test_compare_by_sub_type(): void { $types = [ new AcceptMediaType(0, 'foo', '*'), new AcceptMediaType(1, 'boo', 'baz'), ]; - /** @var MediaTypeInterface[] $types */ - usort($types, AcceptMediaType::getCompare()); + /* @var MediaTypeInterface[] $types */ + \usort($types, AcceptMediaType::getCompare()); $this->checkSorting( [ @@ -168,18 +159,16 @@ public function testCompareBySubType(): void /** * Test compare. - * - * @return void */ - public function testCompareByParams(): void + public function test_compare_by_params(): void { $types = [ new AcceptMediaType(0, 'foo', 'bar'), new AcceptMediaType(1, 'boo', 'baz', ['param' => 'value']), ]; - /** @var MediaTypeInterface[] $types */ - usort($types, AcceptMediaType::getCompare()); + /* @var MediaTypeInterface[] $types */ + \usort($types, AcceptMediaType::getCompare()); $this->checkSorting( [ @@ -204,17 +193,15 @@ public function testCompareByParams(): void /** * Test compare. - * - * @return void */ - public function testCompareByPosition(): void + public function test_compare_by_position(): void { $types = [ new AcceptMediaType(0, 'foo', 'bar', [], 0.5), new AcceptMediaType(1, 'boo', 'baz', [], 0.5), ]; - usort($types, AcceptMediaType::getCompare()); + \usort($types, AcceptMediaType::getCompare()); $this->checkSorting( [ @@ -239,10 +226,8 @@ public function testCompareByPosition(): void /** * Test invalid parameters. - * - * @return void */ - public function testInvalidParameters1(): void + public function test_invalid_parameters1(): void { $this->expectException(InvalidArgumentException::class); @@ -251,10 +236,8 @@ public function testInvalidParameters1(): void /** * Test invalid parameters. - * - * @return void */ - public function testInvalidParameters2(): void + public function test_invalid_parameters2(): void { $this->expectException(InvalidArgumentException::class); @@ -264,15 +247,15 @@ public function testInvalidParameters2(): void /** * Test sample from RFC. */ - public function testParseHeaderRfcSample1(): void + public function test_parse_header_rfc_sample1(): void { $types = [ new AcceptMediaType(0, 'audio', '*', null, 0.2), new AcceptMediaType(1, 'audio', 'basic'), ]; - /** @var AcceptMediaTypeInterface[] $types */ - usort($types, AcceptMediaType::getCompare()); + /* @var AcceptMediaTypeInterface[] $types */ + \usort($types, AcceptMediaType::getCompare()); $this->checkSorting( [ @@ -286,7 +269,7 @@ public function testParseHeaderRfcSample1(): void /** * Test sample from RFC. */ - public function testParseHeaderRfcSample2(): void + public function test_parse_header_rfc_sample2(): void { $types = [ new AcceptMediaType(0, 'text', 'plain', null, 0.5), @@ -295,8 +278,8 @@ public function testParseHeaderRfcSample2(): void new AcceptMediaType(3, 'text', 'x-c'), ]; - /** @var AcceptMediaTypeInterface[] $types */ - usort($types, AcceptMediaType::getCompare()); + /* @var AcceptMediaTypeInterface[] $types */ + \usort($types, AcceptMediaType::getCompare()); $this->checkSorting( [ @@ -312,7 +295,7 @@ public function testParseHeaderRfcSample2(): void /** * Test sample from RFC. */ - public function testParseHeaderRfcSample3(): void + public function test_parse_header_rfc_sample3(): void { $types = [ new AcceptMediaType(0, 'text', '*'), @@ -321,8 +304,8 @@ public function testParseHeaderRfcSample3(): void new AcceptMediaType(3, '*', '*'), ]; - /** @var AcceptMediaTypeInterface[] $types */ - usort($types, AcceptMediaType::getCompare()); + /* @var AcceptMediaTypeInterface[] $types */ + \usort($types, AcceptMediaType::getCompare()); $this->checkSorting( [ @@ -340,7 +323,7 @@ public function testParseHeaderRfcSample3(): void /** * Test sample from RFC. */ - public function testParseHeaderRfcSample4(): void + public function test_parse_header_rfc_sample4(): void { $types = [ new AcceptMediaType(0, 'text', '*', null, 0.3), @@ -350,8 +333,8 @@ public function testParseHeaderRfcSample4(): void new AcceptMediaType(4, '*', '*', null, 0.5), ]; - /** @var AcceptMediaTypeInterface[] $types */ - usort($types, AcceptMediaType::getCompare()); + /* @var AcceptMediaTypeInterface[] $types */ + \usort($types, AcceptMediaType::getCompare()); $this->checkSorting( [ @@ -372,12 +355,10 @@ public function testParseHeaderRfcSample4(): void /** * @param string[] $sorted * @param MediaTypeInterface[] $mediaTypes - * - * @return void */ private function checkSorting(array $sorted, array $mediaTypes): void { - self::assertEquals($count = count($mediaTypes), count($sorted)); + self::assertEquals($count = \count($mediaTypes), \count($sorted)); for ($idx = 0; $idx < $count; ++$idx) { self::assertEquals($mediaTypes[$idx]->getMediaType(), $sorted[$idx]); diff --git a/tests/Http/Headers/HeaderParametersParserTest.php b/tests/Http/Headers/HeaderParametersParserTest.php index 5257059..48937b4 100644 --- a/tests/Http/Headers/HeaderParametersParserTest.php +++ b/tests/Http/Headers/HeaderParametersParserTest.php @@ -1,8 +1,10 @@ -parser->parseContentTypeHeader(self::MEDIA_TYPE); @@ -71,7 +70,7 @@ public function testParseHeadersNoParams1(): void /** * Test parse headers. */ - public function testParseHeadersNoParams2(): void + public function test_parse_headers_no_params2(): void { /** @var MediaTypeInterface $contentType */ $contentType = $this->parser->parseContentTypeHeader(self::MEDIA_TYPE); @@ -92,7 +91,7 @@ public function testParseHeadersNoParams2(): void /** * Test parse headers. */ - public function testParseHeadersWithParamsNoExtraParams(): void + public function test_parse_headers_with_params_no_extra_params(): void { $contentType = $this->parser->parseContentTypeHeader(self::MEDIA_TYPE . ';ext="ext1,ext2"'); self::assertEquals(self::MEDIA_TYPE, $contentType->getMediaType()); @@ -110,13 +109,13 @@ public function testParseHeadersWithParamsNoExtraParams(): void /** * Test parse headers. */ - public function testParseHeadersWithParamsWithExtraParams(): void + public function test_parse_headers_with_params_with_extra_params(): void { /** @var AcceptMediaTypeInterface $accept */ $contentType = $this->parser->parseContentTypeHeader( self::MEDIA_TYPE . ' ; boo = foo; ext="ext1,ext2"; foo = boo ' ); - $accept = $this->first( + $accept = $this->first( $this->parser->parseAcceptHeader( self::MEDIA_TYPE . ' ; boo = foo; ext=ext1; foo = boo' ) @@ -137,7 +136,7 @@ public function testParseHeadersWithParamsWithExtraParams(): void /** * Test parse empty header. */ - public function testParseEmptyHeader1(): void + public function test_parse_empty_header1(): void { $this->expectException(InvalidArgumentException::class); @@ -147,7 +146,7 @@ public function testParseEmptyHeader1(): void /** * Test parse empty header. */ - public function testParseEmptyHeader2(): void + public function test_parse_empty_header2(): void { $this->expectException(InvalidArgumentException::class); @@ -157,7 +156,7 @@ public function testParseEmptyHeader2(): void /** * Test parse invalid headers. */ - public function testParseInvalidHeaders1(): void + public function test_parse_invalid_headers1(): void { $this->expectException(InvalidArgumentException::class); @@ -167,7 +166,7 @@ public function testParseInvalidHeaders1(): void /** * Test parse invalid headers. */ - public function testParseInvalidHeaders2(): void + public function test_parse_invalid_headers2(): void { $this->expectException(InvalidArgumentException::class); @@ -175,52 +174,52 @@ public function testParseInvalidHeaders2(): void } /** - * Test rfc2616 #3.9 (3 meaningful digits for quality) + * Test rfc2616 #3.9 (3 meaningful digits for quality). */ - public function testParserHeaderRfc2616P3p9Part1(): void + public function test_parser_header_rfc2616_p3p9_part1(): void { $input = 'type1/*;q=0.5001, type2/*;q=0.5009'; - $types = $this->iterableToArray($this->parser->parseAcceptHeader($input)); + $types = $this->iterableToArray($this->parser->parseAcceptHeader($input)); $params = [ $types[0]->getMediaType() => $types[0]->getQuality(), $types[1]->getMediaType() => $types[1]->getQuality(), ]; - self::assertCount(2, array_intersect(['type1/*' => 0.5, 'type2/*' => 0.5], $params)); + self::assertCount(2, \array_intersect(['type1/*' => 0.5, 'type2/*' => 0.5], $params)); } /** - * Test rfc2616 #3.9 (3 meaningful digits for quality) + * Test rfc2616 #3.9 (3 meaningful digits for quality). */ - public function testParserHeaderRfc2616P3p9Part2(): void + public function test_parser_header_rfc2616_p3p9_part2(): void { $input = 'type1/*;q=0.501, type2/*;q=0.509'; - $types = $this->iterableToArray($this->parser->parseAcceptHeader($input)); + $types = $this->iterableToArray($this->parser->parseAcceptHeader($input)); $params = [ $types[0]->getMediaType() => $types[0]->getQuality(), $types[1]->getMediaType() => $types[1]->getQuality(), ]; - self::assertCount(2, array_intersect(['type1/*' => 0.501, 'type2/*' => 0.509], $params)); + self::assertCount(2, \array_intersect(['type1/*' => 0.501, 'type2/*' => 0.509], $params)); } /** * Test parsing multiple params. */ - public function testParserHeaderWithMultipleParameters(): void + public function test_parser_header_with_multiple_parameters(): void { $input = ' foo/bar.baz;media=param;q=0.5;ext="ext1,ext2", type/*'; /** @var AcceptMediaTypeInterface[] $types */ - $types = $this->iterableToArray($this->parser->parseAcceptHeader($input)); + $types = $this->iterableToArray($this->parser->parseAcceptHeader($input)); $params = [ $types[0]->getMediaType() => $types[0]->getParameters(), $types[1]->getMediaType() => $types[1]->getParameters(), ]; - asort($params); + \asort($params); self::assertEquals(['type/*' => null, 'foo/bar.baz' => ['media' => 'param']], $params); } @@ -228,14 +227,14 @@ public function testParserHeaderWithMultipleParameters(): void /** * Test sample from RFC. */ - public function testParseHeaderRfcSample1(): void + public function test_parse_header_rfc_sample1(): void { $input = 'audio/*; q=0.2, audio/basic'; /** @var AcceptMediaTypeInterface[] $types */ $types = $this->iterableToArray($this->parser->parseAcceptHeader($input)); - self::assertEquals(2, count($types)); + self::assertCount(2, $types); self::assertEquals('audio/*', $types[0]->getMediaType()); self::assertEquals(0.2, $types[0]->getQuality()); self::assertEquals(0, $types[0]->getPosition()); @@ -247,14 +246,14 @@ public function testParseHeaderRfcSample1(): void /** * Test sample from RFC. */ - public function testParseHeaderRfcSample2(): void + public function test_parse_header_rfc_sample2(): void { $input = 'text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c'; /** @var AcceptMediaTypeInterface[] $types */ $types = $this->iterableToArray($this->parser->parseAcceptHeader($input)); - self::assertEquals(4, count($types)); + self::assertCount(4, $types); self::assertEquals('text/plain', $types[0]->getMediaType()); self::assertEquals(0.5, $types[0]->getQuality()); self::assertEquals('text/html', $types[1]->getMediaType()); @@ -268,45 +267,45 @@ public function testParseHeaderRfcSample2(): void /** * Test sample from RFC. */ - public function testParseHeaderRfcSample3(): void + public function test_parse_header_rfc_sample3(): void { $input = 'text/*, text/html, text/html;level=1, */*'; /** @var AcceptMediaTypeInterface[] $types */ $types = $this->iterableToArray($this->parser->parseAcceptHeader($input)); - self::assertEquals(4, count($types)); + self::assertCount(4, $types); self::assertEquals('text/*', $types[0]->getMediaType()); self::assertEquals(1.0, $types[0]->getQuality()); self::assertEquals('text/html', $types[1]->getMediaType()); - self::assertEquals(null, $types[0]->getParameters()); + self::assertNull($types[0]->getParameters()); self::assertEquals(1.0, $types[1]->getQuality()); - self::assertEquals(null, $types[1]->getParameters()); + self::assertNull($types[1]->getParameters()); self::assertEquals('text/html', $types[2]->getMediaType()); self::assertEquals(1.0, $types[2]->getQuality()); self::assertEquals(['level' => '1'], $types[2]->getParameters()); self::assertEquals('*/*', $types[3]->getMediaType()); self::assertEquals(1.0, $types[3]->getQuality()); - self::assertEquals(null, $types[3]->getParameters()); + self::assertNull($types[3]->getParameters()); } /** * Test sample from RFC. */ - public function testParseHeaderRfcSample4(): void + public function test_parse_header_rfc_sample4(): void { $input = 'text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5'; /** @var AcceptMediaTypeInterface[] $types */ $types = $this->iterableToArray($this->parser->parseAcceptHeader($input)); - self::assertEquals(5, count($types)); + self::assertCount(5, $types); self::assertEquals('text/*', $types[0]->getMediaType()); self::assertEquals(0.3, $types[0]->getQuality()); - self::assertEquals(null, $types[0]->getParameters()); + self::assertNull($types[0]->getParameters()); self::assertEquals('text/html', $types[1]->getMediaType()); self::assertEquals(0.7, $types[1]->getQuality()); - self::assertEquals(null, $types[1]->getParameters()); + self::assertNull($types[1]->getParameters()); self::assertEquals('text/html', $types[2]->getMediaType()); self::assertEquals(1.0, $types[2]->getQuality()); self::assertEquals(['level' => '1'], $types[2]->getParameters()); @@ -315,13 +314,13 @@ public function testParseHeaderRfcSample4(): void self::assertEquals(['level' => '2'], $types[3]->getParameters()); self::assertEquals('*/*', $types[4]->getMediaType()); self::assertEquals(0.5, $types[4]->getQuality()); - self::assertEquals(null, $types[4]->getParameters()); + self::assertNull($types[4]->getParameters()); } /** * Test invalid header. */ - public function testInvalidHeader1(): void + public function test_invalid_header1(): void { $this->expectException(InvalidArgumentException::class); @@ -331,7 +330,7 @@ public function testInvalidHeader1(): void /** * Test invalid header. */ - public function testInvalidHeader2(): void + public function test_invalid_header2(): void { $this->expectException(InvalidArgumentException::class); @@ -341,7 +340,7 @@ public function testInvalidHeader2(): void /** * @see https://github.com/neomerx/json-api/issues/193 */ - public function testInvalidHeader3(): void + public function test_invalid_header3(): void { $this->expectException(InvalidArgumentException::class); @@ -351,7 +350,7 @@ public function testInvalidHeader3(): void /** * Test invalid parse parameters. */ - public function testInvalidParseParams1(): void + public function test_invalid_parse_params1(): void { $this->expectException(InvalidArgumentException::class); @@ -361,7 +360,7 @@ public function testInvalidParseParams1(): void /** * Test invalid parse parameters. */ - public function testInvalidParseParams2(): void + public function test_invalid_parse_params2(): void { $this->expectException(InvalidArgumentException::class); @@ -371,7 +370,7 @@ public function testInvalidParseParams2(): void /** * Test parse parameters. */ - public function testParseAcceptHeaderWithJsonApiProfile(): void + public function test_parse_accept_header_with_json_api_profile(): void { /** @var AcceptMediaTypeInterface $accept */ $accept = $this->first( @@ -384,8 +383,6 @@ public function testParseAcceptHeaderWithJsonApiProfile(): void } /** - * @param iterable $iterable - * * @return mixed */ private function first(iterable $iterable) @@ -397,11 +394,6 @@ private function first(iterable $iterable) throw new InvalidArgumentException(); } - /** - * @param iterable $iterable - * - * @return array - */ private function iterableToArray(iterable $iterable): array { $result = []; diff --git a/tests/Http/Headers/MediaTypeTest.php b/tests/Http/Headers/MediaTypeTest.php index b0619b7..9462a58 100644 --- a/tests/Http/Headers/MediaTypeTest.php +++ b/tests/Http/Headers/MediaTypeTest.php @@ -1,8 +1,10 @@ -expectException(InvalidArgumentException::class); @@ -41,10 +38,8 @@ public function testInvalidConstructorParams1(): void /** * Test invalid constructor parameters. - * - * @return void */ - public function testInvalidConstructorParams2(): void + public function test_invalid_constructor_params2(): void { $this->expectException(InvalidArgumentException::class); @@ -53,10 +48,8 @@ public function testInvalidConstructorParams2(): void /** * Test full media type name combine. - * - * @return void */ - public function testGetMediaType(): void + public function test_get_media_type(): void { $type = new MediaType('text', 'html', ['charset' => 'utf-8']); @@ -64,11 +57,9 @@ public function testGetMediaType(): void } /** - * Test compare media types (case insensitive) - * - * @return void + * Test compare media types (case insensitive). */ - public function testCompareMediaTypes(): void + public function test_compare_media_types(): void { $type1 = new MediaType('text', 'html', ['charset' => 'utf-8']); $type2 = new MediaType('Text', 'HTML', ['Charset' => 'utf-8']); @@ -85,11 +76,9 @@ public function testCompareMediaTypes(): void } /** - * Test compare media types (case sensitive) - * - * @return void + * Test compare media types (case sensitive). */ - public function testCompareMediaTypes2(): void + public function test_compare_media_types2(): void { $type1 = new MediaType('text', 'html', ['case-sensitive-value' => 'whatever']); $type2 = new MediaType('text', 'html', ['case-sensitive-value' => 'WHATEVER']); @@ -100,11 +89,9 @@ public function testCompareMediaTypes2(): void } /** - * Test compare media types - * - * @return void + * Test compare media types. */ - public function testCompareMediaTypesWithoutParameters(): void + public function test_compare_media_types_without_parameters(): void { $type1 = new MediaType('text', 'html'); $type2 = new MediaType('Text', 'HTML'); @@ -113,11 +100,9 @@ public function testCompareMediaTypesWithoutParameters(): void } /** - * Test compare media types - * - * @return void + * Test compare media types. */ - public function testMatchMediaTypes(): void + public function test_match_media_types(): void { $type1 = new MediaType('text', 'html', ['charset' => 'utf-8']); $type2 = new MediaType('Text', 'HTML', ['Charset' => 'utf-8']); @@ -130,11 +115,9 @@ public function testMatchMediaTypes(): void } /** - * Test compare media types - * - * @return void + * Test compare media types. */ - public function testMatchMediaTypesWithoutParameters(): void + public function test_match_media_types_without_parameters(): void { $type1 = new MediaType('text', 'html'); $type2 = new MediaType('Text', 'HTML'); @@ -143,13 +126,11 @@ public function testMatchMediaTypesWithoutParameters(): void } /** - * Test compare media types - * - * @return void + * Test compare media types. * * @see https://github.com/neomerx/json-api/issues/221 */ - public function testMatchMediaTypesWithoutParameters2(): void + public function test_match_media_types_without_parameters2(): void { // match by mask diff --git a/tests/Http/Query/BaseQueryParserTest.php b/tests/Http/Query/BaseQueryParserTest.php index 847cc51..94dd4a9 100644 --- a/tests/Http/Query/BaseQueryParserTest.php +++ b/tests/Http/Query/BaseQueryParserTest.php @@ -1,8 +1,10 @@ - 'comments, comments.author', @@ -60,7 +59,7 @@ public function testIncludes(): void self::assertEquals( [ - 'comments' => ['comments'], + 'comments' => ['comments'], 'comments.author' => ['comments', 'author'], ], $this->iterableToArray($parser->getIncludes()) @@ -70,7 +69,7 @@ public function testIncludes(): void /** * Test query. */ - public function testIncludePaths(): void + public function test_include_paths(): void { $queryParameters = [ BaseQueryParser::PARAM_INCLUDE => 'comments, comments.author', @@ -90,7 +89,7 @@ public function testIncludePaths(): void /** * That's a special case to test possible issues with `empty` function which thinks "0" is an empty string. */ - public function testIncludesForStringWithZeroes1(): void + public function test_includes_for_string_with_zeroes1(): void { $queryParameters = [ BaseQueryParser::PARAM_INCLUDE => '0', @@ -109,7 +108,7 @@ public function testIncludesForStringWithZeroes1(): void /** * That's a special case to test possible issues with `empty` function which thinks "0" is an empty string. */ - public function testIncludesForStringWithZeroes2(): void + public function test_includes_for_string_with_zeroes2(): void { $queryParameters = [ BaseQueryParser::PARAM_INCLUDE => '0,1', @@ -129,12 +128,12 @@ public function testIncludesForStringWithZeroes2(): void /** * Test query. */ - public function testFields(): void + public function test_fields(): void { $queryParameters = [ BaseQueryParser::PARAM_FIELDS => [ 'articles' => 'title, body ', - 'people' => 'name', + 'people' => 'name', ], ]; @@ -143,7 +142,7 @@ public function testFields(): void self::assertEquals( [ 'articles' => ['title', 'body'], - 'people' => ['name'], + 'people' => ['name'], ], $this->iterableToArray($parser->getFields()) ); @@ -152,7 +151,7 @@ public function testFields(): void /** * Test query. */ - public function testSorts(): void + public function test_sorts(): void { $queryParameters = [ BaseQueryParser::PARAM_SORT => '-created,title,+updated', @@ -163,7 +162,7 @@ public function testSorts(): void self::assertEquals( [ 'created' => false, - 'title' => true, + 'title' => true, 'updated' => true, ], $this->iterableToArray($parser->getSorts()) @@ -173,7 +172,7 @@ public function testSorts(): void /** * Test query. */ - public function testInvalidIncludesEmptyValue(): void + public function test_invalid_includes_empty_value(): void { $this->expectException(JsonApiException::class); @@ -187,7 +186,7 @@ public function testInvalidIncludesEmptyValue(): void /** * Test query. */ - public function testInvalidIncludesNotString1(): void + public function test_invalid_includes_not_string1(): void { $this->expectException(JsonApiException::class); @@ -201,7 +200,7 @@ public function testInvalidIncludesNotString1(): void /** * Test query. */ - public function testInvalidIncludesNotString2(): void + public function test_invalid_includes_not_string2(): void { $this->expectException(JsonApiException::class); @@ -215,7 +214,7 @@ public function testInvalidIncludesNotString2(): void /** * Test query. */ - public function testInvalidIncludesEmptyString1(): void + public function test_invalid_includes_empty_string1(): void { $this->expectException(JsonApiException::class); @@ -229,7 +228,7 @@ public function testInvalidIncludesEmptyString1(): void /** * Test query. */ - public function testInvalidIncludesEmptyString2(): void + public function test_invalid_includes_empty_string2(): void { $this->expectException(JsonApiException::class); @@ -243,7 +242,7 @@ public function testInvalidIncludesEmptyString2(): void /** * Test query. */ - public function testInvalidFields(): void + public function test_invalid_fields(): void { $this->expectException(JsonApiException::class); @@ -257,31 +256,28 @@ public function testInvalidFields(): void /** * Shows how to integrate base query parser with EncodingParameters. * - * @return void - * * @see https://github.com/neomerx/json-api/issues/198 */ - public function testIntegrationWithEncodingParameters(): void + public function test_integration_with_encoding_parameters(): void { $profileUrl1 = 'http://example1.com/foo'; $profileUrl2 = 'http://example2.com/boo'; $queryParameters = [ - BaseQueryParser::PARAM_FIELDS => [ + BaseQueryParser::PARAM_FIELDS => [ 'comments' => Comment::LINK_AUTHOR . ', ' . Comment::ATTRIBUTE_BODY . ' ', - 'people' => Author::ATTRIBUTE_FIRST_NAME, + 'people' => Author::ATTRIBUTE_FIRST_NAME, ], - BaseQueryParser::PARAM_SORT => '-created,title,+updated', + BaseQueryParser::PARAM_SORT => '-created,title,+updated', BaseQueryParser::PARAM_INCLUDE => Comment::LINK_AUTHOR . ', ' . Comment::LINK_AUTHOR . '.' . Author::LINK_COMMENTS, - BaseQueryParser::PARAM_PROFILE => urlencode(implode(' ', [$profileUrl1, $profileUrl2])), + BaseQueryParser::PARAM_PROFILE => \urlencode(\implode(' ', [$profileUrl1, $profileUrl2])), ]; // It is expected that classes that encapsulate/extend BaseQueryParser would add features // such filters/pagination parsing, validation, etc. Though for simplicity we omit adding // them here and check how it integrates with EncodingParameters. - $parser = new class ($queryParameters) extends BaseQueryParser - { + $parser = new class($queryParameters) extends BaseQueryParser { private ?array $fields = null; private ?array $sorts = null; @@ -290,59 +286,42 @@ public function testIntegrationWithEncodingParameters(): void private ?array $profile = null; - /** - * @return array - */ public function getFields(): array { - if ($this->fields === null) { + if (null === $this->fields) { $this->fields = $this->iterableToArray(parent::getFields()); } return $this->fields; } - /** - * @return array - */ public function getSorts(): array { - if ($this->sorts === null) { + if (null === $this->sorts) { $this->sorts = $this->iterableToArray(parent::getSorts()); } return $this->sorts; } - /** - * @return array - */ public function getProfileUrls(): array { - if ($this->profile === null) { + if (null === $this->profile) { $this->profile = $this->iterableToArray(parent::getProfileUrls()); } return $this->profile; } - /** - * @return array - */ public function getIncludes(): array { - if ($this->includes === null) { - $this->includes = array_keys($this->iterableToArray(parent::getIncludes())); + if (null === $this->includes) { + $this->includes = \array_keys($this->iterableToArray(parent::getIncludes())); } return $this->includes; } - /** - * @param iterable $iterable - * - * @return array - */ private function iterableToArray(iterable $iterable): array { $result = []; @@ -359,14 +338,14 @@ private function iterableToArray(iterable $iterable): array self::assertSame( [ 'comments' => [Comment::LINK_AUTHOR, Comment::ATTRIBUTE_BODY], - 'people' => [Author::ATTRIBUTE_FIRST_NAME], + 'people' => [Author::ATTRIBUTE_FIRST_NAME], ], $parser->getFields() ); self::assertSame( [ 'created' => false, - 'title' => true, + 'title' => true, 'updated' => true, ], $parser->getSorts() @@ -391,8 +370,8 @@ private function iterableToArray(iterable $iterable): array // // firstly setup some data - $author = Author::instance(9, 'Dan', 'Gebhardt'); - $comments = [ + $author = Author::instance(9, 'Dan', 'Gebhardt'); + $comments = [ Comment::instance(5, 'First!', $author), Comment::instance(12, 'I like XML better', $author), ]; @@ -401,7 +380,7 @@ private function iterableToArray(iterable $iterable): array // and encode with params taken from the parser $actual = Encoder::instance( [ - Author::class => AuthorSchema::class, + Author::class => AuthorSchema::class, Comment::class => CommentSchema::class, ] ) @@ -468,21 +447,11 @@ private function iterableToArray(iterable $iterable): array self::assertJsonStringEqualsJsonString($expected, $actual); } - /** - * @param array $queryParameters - * - * @return BaseQueryParserInterface - */ private function createParser(array $queryParameters): BaseQueryParserInterface { return new BaseQueryParser($queryParameters); } - /** - * @param iterable $iterable - * - * @return array - */ private function iterableToArray(iterable $iterable): array { $result = []; diff --git a/tests/Http/ResponsesTest.php b/tests/Http/ResponsesTest.php index e2f1596..65c2979 100644 --- a/tests/Http/ResponsesTest.php +++ b/tests/Http/ResponsesTest.php @@ -1,8 +1,10 @@ -mock = Mockery::mock(BaseResponses::class)->makePartial()->shouldAllowMockingProtectedMethods(); + $this->mock = Mockery::mock(BaseResponses::class)->makePartial()->shouldAllowMockingProtectedMethods(); $this->responses = $this->mock; } /** * Test code response has no content-type header. */ - public function testCodeResponseHasNoContentTypeHeader(): void + public function test_code_response_has_no_content_type_header(): void { $expectedHeaders = []; $this->willBeCalledCreateResponse(null, 123, $expectedHeaders, 'some response'); @@ -62,7 +60,7 @@ public function testCodeResponseHasNoContentTypeHeader(): void /** * Test response. */ - public function testContentResponse1(): void + public function test_content_response1(): void { $data = new stdClass(); $this->willBeCalledGetMediaType('some', 'type'); @@ -75,7 +73,7 @@ public function testContentResponse1(): void /** * Test content response, with custom headers. */ - public function testContentResponse2(): void + public function test_content_response2(): void { $data = new stdClass(); $this->willBeCalledGetMediaType('some', 'type'); @@ -97,7 +95,7 @@ public function testContentResponse2(): void /** * Test response. */ - public function testCreatedResponse1(): void + public function test_created_response1(): void { $resource = new stdClass(); $location = 'http://server.tld/resource-type/123'; @@ -105,16 +103,16 @@ public function testCreatedResponse1(): void $this->willBeCalledEncoderForData($resource, 'some json api'); $headers = [ BaseResponses::HEADER_CONTENT_TYPE => 'some/type', - BaseResponses::HEADER_LOCATION => $location, + BaseResponses::HEADER_LOCATION => $location, ]; $this->willBeCalledCreateResponse('some json api', BaseResponses::HTTP_CREATED, $headers, 'some response'); self::assertEquals('some response', $this->responses->getCreatedResponse($resource, $location)); } /** - * Test response, with custom headers + * Test response, with custom headers. */ - public function testCreatedResponse2(): void + public function test_created_response2(): void { $resource = new stdClass(); $location = 'http://server.tld'; @@ -122,8 +120,8 @@ public function testCreatedResponse2(): void $this->willBeCalledEncoderForData($resource, 'some json api'); $headers = [ BaseResponses::HEADER_CONTENT_TYPE => 'some/type', - BaseResponses::HEADER_LOCATION => $location, - 'X-Custom' => 'Custom-Header', + BaseResponses::HEADER_LOCATION => $location, + 'X-Custom' => 'Custom-Header', ]; $this->willBeCalledCreateResponse('some json api', BaseResponses::HTTP_CREATED, $headers, 'some response'); self::assertEquals( @@ -141,7 +139,7 @@ public function testCreatedResponse2(): void /** * Test response. */ - public function testMetaResponse1(): void + public function test_meta_response1(): void { $meta = new stdClass(); $this->willBeCalledGetMediaType('some', 'type'); @@ -152,9 +150,9 @@ public function testMetaResponse1(): void } /** - * Test response, with custom headers + * Test response, with custom headers. */ - public function testMetaResponse2(): void + public function test_meta_response2(): void { $meta = new stdClass(); $this->willBeCalledGetMediaType('some', 'type'); @@ -176,7 +174,7 @@ public function testMetaResponse2(): void /** * Test identifiers response. */ - public function testIdentifiersResponse1(): void + public function test_identifiers_response1(): void { $data = new stdClass(); $this->willBeCalledGetMediaType('some', 'type'); @@ -189,7 +187,7 @@ public function testIdentifiersResponse1(): void /** * Test identifiers response, with custom headers. */ - public function testIdentifiersResponse2(): void + public function test_identifiers_response2(): void { $data = new stdClass(); $this->willBeCalledGetMediaType('some', 'type'); @@ -211,7 +209,7 @@ public function testIdentifiersResponse2(): void /** * Test response. */ - public function testErrorResponse1(): void + public function test_error_response1(): void { $error = new Error(); $this->willBeCalledGetMediaType('some', 'type'); @@ -224,7 +222,7 @@ public function testErrorResponse1(): void /** * Test response. */ - public function testErrorResponse2(): void + public function test_error_response2(): void { $errors = [new Error()]; $this->willBeCalledGetMediaType('some', 'type'); @@ -237,7 +235,7 @@ public function testErrorResponse2(): void /** * Test response. */ - public function testErrorResponse3(): void + public function test_error_response3(): void { $errors = new ErrorCollection(); $errors->add(new Error()); @@ -251,7 +249,7 @@ public function testErrorResponse3(): void /** * Test response, with custom headers. */ - public function testErrorResponse4(): void + public function test_error_response4(): void { $error = new Error(); $this->willBeCalledGetMediaType('some', 'type'); @@ -270,59 +268,41 @@ public function testErrorResponse4(): void ); } - /** - * @param string $type - * @param string $subType - * @param array|null $parameters - * - * @return void - */ private function willBeCalledGetMediaType(string $type, string $subType, array $parameters = null): void { $mediaType = new MediaType($type, $subType, $parameters); - /** @noinspection PhpMethodParametersCountMismatchInspection */ + /* @noinspection PhpMethodParametersCountMismatchInspection */ $this->mock->shouldReceive('getMediaType')->once()->withNoArgs()->andReturn($mediaType); } /** - * @param null|string $content - * @param int $httpCode - * @param array $headers - * @param mixed $response - * - * @return void + * @param mixed $response */ private function willBeCalledCreateResponse(?string $content, int $httpCode, array $headers, $response): void { - /** @noinspection PhpMethodParametersCountMismatchInspection */ + /* @noinspection PhpMethodParametersCountMismatchInspection */ $this->mock->shouldReceive('createResponse')->once() ->withArgs([$content, $httpCode, $headers])->andReturn($response); } - /** - * @return MockInterface - */ private function willBeCalledGetEncoder(): MockInterface { $encoderMock = Mockery::mock(EncoderInterface::class); - /** @noinspection PhpMethodParametersCountMismatchInspection */ + /* @noinspection PhpMethodParametersCountMismatchInspection */ $this->mock->shouldReceive('getEncoder')->once()->withNoArgs()->andReturn($encoderMock); return $encoderMock; } /** - * @param mixed $data - * @param string $result - * - * @return void + * @param mixed $data */ private function willBeCalledEncoderForData($data, string $result): void { $encoderMock = $this->willBeCalledGetEncoder(); - /** @noinspection PhpMethodParametersCountMismatchInspection */ + /* @noinspection PhpMethodParametersCountMismatchInspection */ $encoderMock->shouldReceive('encodeData') ->once() ->withArgs([$data]) @@ -330,30 +310,24 @@ private function willBeCalledEncoderForData($data, string $result): void } /** - * @param mixed $meta - * @param string $result - * - * @return void + * @param mixed $meta */ private function willBeCalledEncoderForMeta($meta, string $result): void { $encoderMock = $this->willBeCalledGetEncoder(); - /** @noinspection PhpMethodParametersCountMismatchInspection */ + /* @noinspection PhpMethodParametersCountMismatchInspection */ $encoderMock->shouldReceive('encodeMeta')->once()->with($meta)->andReturn($result); } /** - * @param mixed $data - * @param string $result - * - * @return void + * @param mixed $data */ private function willBeCalledEncoderForIdentifiers($data, string $result): void { $encoderMock = $this->willBeCalledGetEncoder(); - /** @noinspection PhpMethodParametersCountMismatchInspection */ + /* @noinspection PhpMethodParametersCountMismatchInspection */ $encoderMock->shouldReceive('encodeIdentifiers') ->once() ->withArgs([$data]) @@ -361,30 +335,21 @@ private function willBeCalledEncoderForIdentifiers($data, string $result): void } /** - * @param mixed $error - * @param string $result - * - * @return void + * @param mixed $error */ private function willBeCalledEncoderForError($error, string $result): void { $encoderMock = $this->willBeCalledGetEncoder(); - /** @noinspection PhpMethodParametersCountMismatchInspection */ + /* @noinspection PhpMethodParametersCountMismatchInspection */ $encoderMock->shouldReceive('encodeError')->once()->with($error)->andReturn($result); } - /** - * @param iterable $errors - * @param string $result - * - * @return void - */ private function willBeCalledEncoderForErrors(iterable $errors, string $result): void { $encoderMock = $this->willBeCalledGetEncoder(); - /** @noinspection PhpMethodParametersCountMismatchInspection */ + /* @noinspection PhpMethodParametersCountMismatchInspection */ $encoderMock->shouldReceive('encodeErrors')->once()->with($errors)->andReturn($result); } } diff --git a/tests/I18n/MessagesTest.php b/tests/I18n/MessagesTest.php index 4297186..ae7e1b4 100644 --- a/tests/I18n/MessagesTest.php +++ b/tests/I18n/MessagesTest.php @@ -1,8 +1,10 @@ -createRelationshipData(RelationshipDataIsCollection::class, []); @@ -53,7 +52,7 @@ public function testIsCollection(): void /** * Test relationship data. */ - public function testIsIdentifier(): void + public function test_is_identifier(): void { $data = $this->createRelationshipData( RelationshipDataIsIdentifier::class, @@ -72,7 +71,7 @@ public function testIsIdentifier(): void /** * Test relationship data. */ - public function testIsNull(): void + public function test_is_null(): void { $data = $this->createRelationshipData( RelationshipDataIsNull::class, @@ -92,7 +91,7 @@ public function testIsNull(): void /** * Test relationship data. */ - public function testIsResource(): void + public function test_is_resource(): void { $data = $this->createRelationshipData( RelationshipDataIsResource::class, @@ -109,17 +108,14 @@ public function testIsResource(): void } /** - * @param string $className - * @param mixed $specificParam - * - * @return RelationshipDataInterface + * @param mixed $specificParam */ private function createRelationshipData(string $className, $specificParam): RelationshipDataInterface { - $factory = $this->createFactory(); + $factory = $this->createFactory(); $container = $factory->createSchemaContainer([]); - $context = $factory->createParserContext([], []); - $position = $factory->createPosition( + $context = $factory->createParserContext([], []); + $position = $factory->createPosition( ParserInterface::ROOT_LEVEL, ParserInterface::ROOT_PATH, null, @@ -131,19 +127,13 @@ private function createRelationshipData(string $className, $specificParam): Rela return $data; } - /** - * @param RelationshipDataInterface $data - * @param string $method - * - * @return void - */ private function assertMethodThrowsLogicException(RelationshipDataInterface $data, string $method): void { - $this->assertTrue(method_exists($data, $method)); + $this->assertTrue(\method_exists($data, $method)); $wasThrown = false; try { - call_user_func([$data, $method]); + \call_user_func([$data, $method]); } catch (LogicException $exception) { $wasThrown = true; } diff --git a/tests/Sample/EncodeTest.php b/tests/Sample/EncodeTest.php index 5d0ba8b..2992259 100644 --- a/tests/Sample/EncodeTest.php +++ b/tests/Sample/EncodeTest.php @@ -1,8 +1,10 @@ -samples->getBasicExample(); + $actual = $this->samples->getBasicExample(); $expected = <<samples->getIncludedObjectsExample(); + $actual = $this->samples->getIncludedObjectsExample(); $expected = <<samples->getSparseAndFieldSetsExample(); + $actual = $this->samples->getSparseAndFieldSetsExample(); $expected = <<samples->getTopLevelMetaAndLinksExample(); + $actual = $this->samples->getTopLevelMetaAndLinksExample(); $expected = <<samples->getDynamicSchemaExample(); + $actual = $this->samples->getDynamicSchemaExample(); $expected = <<samples->runPerformanceTestForSmallNestedResources(10)[0]); } @@ -326,7 +325,7 @@ public function testPerformanceTestForSmallNestedResources(): void /** * Test performance sample. */ - public function testPerformanceTestForBigCollection(): void + public function test_performance_test_for_big_collection(): void { self::assertGreaterThan(0, $this->samples->runPerformanceTestForBigCollection(10)[0]); } diff --git a/tests/Schema/ErrorCollectionTest.php b/tests/Schema/ErrorCollectionTest.php index 8062a8e..8899d9a 100644 --- a/tests/Schema/ErrorCollectionTest.php +++ b/tests/Schema/ErrorCollectionTest.php @@ -1,8 +1,10 @@ -collection = new ErrorCollection(); } - public function testBasicCollectionMethods(): void + public function test_basic_collection_methods(): void { $this->assertCount(0, $this->collection); $title1 = 'some title 1'; @@ -81,134 +80,134 @@ public function testBasicCollectionMethods(): void $this->assertInstanceOf(ErrorInterface::class, $error); } - $serialized = $this->collection->serialize(); + $serialized = $this->collection->serialize(); $anotherCollection = new ErrorCollection(); $anotherCollection->unserialize($serialized); $this->assertEquals($this->collection, $anotherCollection); $this->assertCount(2, $this->collection); - unset($this->collection[0]); - unset($this->collection[1]); + unset($this->collection[0], $this->collection[1]); + $this->assertCount(0, $this->collection); } /** * Test adding error. */ - public function testAddDataError(): void + public function test_add_data_error(): void { $this->collection->addDataError('some title'); $this->assertNotEmpty($this->collection); $this->assertEquals([ - ErrorInterface::SOURCE_POINTER => self::DATA_PATH + ErrorInterface::SOURCE_POINTER => self::DATA_PATH, ], $this->collection[0]->getSource()); } /** * Test adding error. */ - public function testAddDataTypeError(): void + public function test_add_data_type_error(): void { $this->collection->addDataTypeError('some title'); $this->assertNotEmpty($this->collection); $this->assertEquals([ - ErrorInterface::SOURCE_POINTER => self::DATA_TYPE_PATH + ErrorInterface::SOURCE_POINTER => self::DATA_TYPE_PATH, ], $this->collection[0]->getSource()); } /** * Test adding error. */ - public function testAddDataIdError(): void + public function test_add_data_id_error(): void { $this->collection->addDataIdError('some title'); $this->assertNotEmpty($this->collection); $this->assertEquals([ - ErrorInterface::SOURCE_POINTER => self::DATA_ID_PATH + ErrorInterface::SOURCE_POINTER => self::DATA_ID_PATH, ], $this->collection[0]->getSource()); } /** * Test adding error. */ - public function testAddAttributesError(): void + public function test_add_attributes_error(): void { $this->collection->addAttributesError('some title'); $this->assertNotEmpty($this->collection); $this->assertEquals([ - ErrorInterface::SOURCE_POINTER => self::ATTR_PATH + ErrorInterface::SOURCE_POINTER => self::ATTR_PATH, ], $this->collection[0]->getSource()); } /** * Test adding error. */ - public function testAddDataAttributeError(): void + public function test_add_data_attribute_error(): void { $this->collection->addDataAttributeError('name', 'some title'); $this->assertNotEmpty($this->collection); $this->assertEquals([ - ErrorInterface::SOURCE_POINTER => self::ATTR_PATH . '/name' + ErrorInterface::SOURCE_POINTER => self::ATTR_PATH . '/name', ], $this->collection[0]->getSource()); } /** * Test adding error. */ - public function testAddRelationshipsError(): void + public function test_add_relationships_error(): void { $this->collection->addRelationshipsError('some title'); $this->assertNotEmpty($this->collection); $this->assertEquals([ - ErrorInterface::SOURCE_POINTER => self::RELS_PATH + ErrorInterface::SOURCE_POINTER => self::RELS_PATH, ], $this->collection[0]->getSource()); } /** * Test adding error. */ - public function testAddRelationshipError(): void + public function test_add_relationship_error(): void { $this->collection->addRelationshipError('name', 'some title'); $this->assertNotEmpty($this->collection); $this->assertEquals([ - ErrorInterface::SOURCE_POINTER => self::RELS_PATH . '/name' + ErrorInterface::SOURCE_POINTER => self::RELS_PATH . '/name', ], $this->collection[0]->getSource()); } /** * Test adding error. */ - public function testAddRelationshipTypeError(): void + public function test_add_relationship_type_error(): void { $this->collection->addRelationshipTypeError('name', 'some title'); $this->assertNotEmpty($this->collection); $this->assertEquals([ - ErrorInterface::SOURCE_POINTER => self::RELS_PATH . '/name' . self::DATA_TYPE_PATH + ErrorInterface::SOURCE_POINTER => self::RELS_PATH . '/name' . self::DATA_TYPE_PATH, ], $this->collection[0]->getSource()); } /** * Test adding error. */ - public function testAddRelationshipIdError(): void + public function test_add_relationship_id_error(): void { $this->collection->addRelationshipIdError('name', 'some title'); $this->assertNotEmpty($this->collection); $this->assertEquals([ - ErrorInterface::SOURCE_POINTER => self::RELS_PATH . '/name' . self::DATA_ID_PATH + ErrorInterface::SOURCE_POINTER => self::RELS_PATH . '/name' . self::DATA_ID_PATH, ], $this->collection[0]->getSource()); } /** * Test adding error. */ - public function testAddQueryParameterError(): void + public function test_add_query_parameter_error(): void { $this->collection->addQueryParameterError('name', 'some title'); $this->assertNotEmpty($this->collection); $this->assertEquals([ - ErrorInterface::SOURCE_PARAMETER => 'name' + ErrorInterface::SOURCE_PARAMETER => 'name', ], $this->collection[0]->getSource()); } } diff --git a/tests/Schema/SchemaContainerTest.php b/tests/Schema/SchemaContainerTest.php index 63d9fe2..2b3f970 100644 --- a/tests/Schema/SchemaContainerTest.php +++ b/tests/Schema/SchemaContainerTest.php @@ -1,8 +1,10 @@ -createFactory(); + $factory = $this->createFactory(); $commentSchema = new CommentSchema($factory); - $postSchema = new PostSchema($factory); - $container = $factory->createSchemaContainer([ - Author::class => AuthorSchema::class, + $postSchema = new PostSchema($factory); + $container = $factory->createSchemaContainer([ + Author::class => AuthorSchema::class, Comment::class => $commentSchema, - Post::class => fn(): SchemaInterface => $postSchema, + Post::class => fn (): SchemaInterface => $postSchema, ]); - $author = $this->createAuthor(); + $author = $this->createAuthor(); $comment = $this->createComment(); - $post = $this->createPost(); + $post = $this->createPost(); self::assertTrue($container->hasSchema($author)); self::assertNotNull($container->getSchema($author)); @@ -64,7 +63,7 @@ public function testRegisterAndGet(): void /** * Test invalid model class. */ - public function testInvalidModelClass(): void + public function test_invalid_model_class(): void { $this->expectException(InvalidArgumentException::class); @@ -76,7 +75,7 @@ public function testInvalidModelClass(): void /** * Test invalid schema class. */ - public function testInvalidSchemaClass(): void + public function test_invalid_schema_class(): void { $this->expectException(InvalidArgumentException::class); @@ -88,13 +87,13 @@ public function testInvalidSchemaClass(): void /** * Test model cannot have more than one schema. */ - public function testModelCannotHaveTwoSchemas(): void + public function test_model_cannot_have_two_schemas(): void { $this->expectException(InvalidArgumentException::class); - $container = $this->createFactory()->createSchemaContainer([Author::class => AuthorSchema::class]); + $container = $this->createFactory()->createSchemaContainer([Author::class => AuthorSchema::class]); - assert($container instanceof SchemaContainer); + \assert($container instanceof SchemaContainer); $container->register(Author::class, CommentSchema::class); } @@ -102,7 +101,7 @@ public function testModelCannotHaveTwoSchemas(): void /** * Test default schema do not provide identifier meta. */ - public function testDefaultSchemaDoNotProvideIdentifierMeta(): void + public function test_default_schema_do_not_provide_identifier_meta(): void { $this->expectException(LogicException::class); @@ -114,7 +113,7 @@ public function testDefaultSchemaDoNotProvideIdentifierMeta(): void /** * Test default schema do not provide resource meta. */ - public function testDefaultSchemaDoNotProvideResourceMeta(): void + public function test_default_schema_do_not_provide_resource_meta(): void { $this->expectException(LogicException::class); @@ -123,25 +122,16 @@ public function testDefaultSchemaDoNotProvideResourceMeta(): void $schema->getResourceMeta($this->createComment()); } - /** - * @return Author - */ private function createAuthor(): Author { return Author::instance(1, 'FirstName', 'LastName'); } - /** - * @return Comment - */ private function createComment(): Comment { return Comment::instance(321, 'Comment body'); } - /** - * @return Post - */ private function createPost(): Post { return Post::instance(321, 'Post Title', 'Post body');