diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 3de729ec..d36d87d6 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -1,6 +1,7 @@ name: lint on: pull_request: + types: [opened, synchronize, reopened, ready_for_review] paths: - "**.php" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index cd83e0a2..128e8494 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,6 +1,7 @@ name: test on: pull_request: + types: [opened, synchronize, reopened, ready_for_review] paths: - "**.php" diff --git a/README.md b/README.md index 1c19e579..591bba7e 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ If you used v1 of this library, see [UPGRADE_1_TO_2.md](/UPGRADE_1_TO_2.md) on h ```php use alsvanzelf\jsonapi\ResourceDocument; -$document = new ResourceDocument($type='user', $id=42); +$document = new ResourceDocument(type: 'user', id: 42); $document->add('name', 'Zaphod Beeblebrox'); $document->add('heads', 2); $document->sendResponse(); diff --git a/examples/collection.php b/examples/collection.php index 6f714831..cdd5a38c 100644 --- a/examples/collection.php +++ b/examples/collection.php @@ -16,7 +16,7 @@ $collection = []; foreach ($users as $user) { - $resource = ResourceObject::fromObject($user, $type='user', $user->id); + $resource = ResourceObject::fromObject($user, type: 'user', id: $user->id); if ($user->id == 42) { $ship = new ResourceObject('ship', 5); diff --git a/examples/collection_canonical.php b/examples/collection_canonical.php index b9fad86c..a29cb295 100644 --- a/examples/collection_canonical.php +++ b/examples/collection_canonical.php @@ -54,7 +54,7 @@ } $document->setSelfLink('http://example.com/articles'); -$document->setPaginationLinks($previous=null, $next='http://example.com/articles?page[offset]=2', $first=null, $last='http://example.com/articles?page[offset]=10'); +$document->setPaginationLinks(previousHref: null, nextHref: 'http://example.com/articles?page[offset]=2', firstHref: null, lastHref: 'http://example.com/articles?page[offset]=10'); $document->unsetJsonapiObject(); /** diff --git a/examples/cursor_pagination_profile.php b/examples/cursor_pagination_profile.php index 065a4d3d..5ad180fb 100644 --- a/examples/cursor_pagination_profile.php +++ b/examples/cursor_pagination_profile.php @@ -25,8 +25,8 @@ $document = CollectionDocument::fromResources($user1, $user2, $user42); $document->applyProfile($profile); -$profile->setCount($document, $exactTotal=3, $bestGuessTotal=10); -$profile->setLinksFirstPage($document, $currentUrl='/users?sort=42&page[size]=10', $lastCursor='zaphod'); +$profile->setCount($document, exactTotal: 3, bestGuessTotal: 10); +$profile->setLinksFirstPage($document, baseOrCurrentUrl: '/users?sort=42&page[size]=10', lastCursor: 'zaphod'); /** * get the json diff --git a/examples/errors_all_options.php b/examples/errors_all_options.php index 3e71b2f7..0174599f 100644 --- a/examples/errors_all_options.php +++ b/examples/errors_all_options.php @@ -11,37 +11,37 @@ * setting all options */ -$errorHumanApi = new ErrorObject($genericCode='Invalid input', $genericTitle='Too much options', $specificDetails='Please, choose a bit less. Consult your ...', $specificAboutLink='https://www.example.com/explanation.html', $genericTypeLink='https://www.example.com/documentation.html'); +$errorHumanApi = new ErrorObject(genericCode: 'Invalid input', genericTitle: 'Too much options', specificDetails: 'Please, choose a bit less. Consult your ...', specificAboutLink: 'https://www.example.com/explanation.html', genericTypeLink: 'https://www.example.com/documentation.html'); $errorSpecApi = new ErrorObject(); // mark the cause of the error -$errorSpecApi->blameJsonPointer($pointer='/data/attributes/title'); -$errorSpecApi->blameQueryParameter($parameter='filter'); -$errorSpecApi->blameHeader($headerName='X-Foo'); +$errorSpecApi->blameJsonPointer(pointer: '/data/attributes/title'); +$errorSpecApi->blameQueryParameter(parameter: 'filter'); +$errorSpecApi->blameHeader(headerName: 'X-Foo'); // an identifier useful for helpdesk purposes -$errorSpecApi->setUniqueIdentifier($id=42); +$errorSpecApi->setUniqueIdentifier(id: 42); // add meta data as you would on a normal json response -$errorSpecApi->addMeta($key='foo', $value='bar'); +$errorSpecApi->addMeta(key: 'foo', value: 'bar'); // or as object $metaObject = new \stdClass(); $metaObject->property = 'value'; -$errorSpecApi->addMeta($key='object', $metaObject); +$errorSpecApi->addMeta(key: 'object', value: $metaObject); // the http status code // @note it is better to set this on the jsonapi\errors object .. // .. as only a single one can be consumed by the browser -$errorSpecApi->setHttpStatusCode($httpStatusCode=404); +$errorSpecApi->setHttpStatusCode(httpStatusCode: 404); // if not set during construction, set them here -$errorSpecApi->setApplicationCode($genericCode='Invalid input'); -$errorSpecApi->setHumanTitle($genericTitle='Too much options'); -$errorSpecApi->setHumanDetails($specificDetails='Please, choose a bit less. Consult your ...'); -$errorSpecApi->setAboutLink($specificAboutLink='https://www.example.com/explanation.html', ['foo'=>'bar']); -$errorSpecApi->setTypeLink($genericTypeLink='https://www.example.com/documentation.html', ['foo'=>'bar']); +$errorSpecApi->setApplicationCode(genericCode: 'Invalid input'); +$errorSpecApi->setHumanTitle(genericTitle: 'Too much options'); +$errorSpecApi->setHumanDetails(specificDetails: 'Please, choose a bit less. Consult your ...'); +$errorSpecApi->setAboutLink(href: 'https://www.example.com/explanation.html', meta: ['foo'=>'bar']); +$errorSpecApi->setTypeLink(href: 'https://www.example.com/documentation.html', meta: ['foo'=>'bar']); /** * prepare multiple error objects for the errors response @@ -68,7 +68,7 @@ $document->addErrorObject($errorSpecApi); $document->addErrorObject($anotherError); $document->addException($someException); -$document->add($genericCode='Authentication error', $genericTitle='Not logged in'); +$document->add(genericCode: 'Authentication error', genericTitle: 'Not logged in'); $document->addLink('redirect', '/login', ['label'=>'Log in']); $document->setHttpStatusCode(400); diff --git a/examples/extension.php b/examples/extension.php index 42f87e6e..3ecf4ddb 100644 --- a/examples/extension.php +++ b/examples/extension.php @@ -30,7 +30,7 @@ * get the json */ -$contentType = Converter::prepareContentType(ContentTypeEnum::Official, [$extension], []); +$contentType = Converter::prepareContentType(ContentTypeEnum::Official, extensions: [$extension], profiles: []); echo 'Content-Type: '.$contentType.''.PHP_EOL; $options = [ diff --git a/examples/output.php b/examples/output.php index f6726e8d..1cb9d4ab 100644 --- a/examples/output.php +++ b/examples/output.php @@ -16,7 +16,7 @@ echo '

Get the array

'; echo '
$document->toArray();
'; -echo '
'.var_export($document->toArray(), true).'
'; +echo '
'.var_export($document->toArray(), return: true).'
'; /** * get the json @@ -25,7 +25,7 @@ $options = ['prettyPrint' => true]; echo '

Get the json

'; echo '
$document->toJson();
'; -echo '
'.var_export($document->toJson($options), true).'
'; +echo '
'.var_export($document->toJson($options), return: true).'
'; /** * use own json_encode @@ -33,8 +33,8 @@ $options = ['prettyPrint' => true]; echo '

Use own json_encode()

'; -echo '
json_encode($document, JSON_PRETTY_PRINT);
'; -echo '
'.var_export(json_encode($document, JSON_PRETTY_PRINT), true).'
'; +echo '
json_encode($document, flags: JSON_PRETTY_PRINT);
'; +echo '
'.var_export(json_encode($document, flags: JSON_PRETTY_PRINT), return: true).'
'; /** * get custom json (for a non-spec array) @@ -51,7 +51,7 @@ echo '$options = [\'array\' => $customArray];'.PHP_EOL; echo '$document->toJson($options);'.PHP_EOL; echo ''; -echo '
'.var_export($document->toJson($options), true).'
'; +echo '
'.var_export($document->toJson($options), return: true).'
'; /** * get jsonp with callback @@ -63,7 +63,7 @@ echo '$options = [\'jsonpCallback\' => \'callback\'];'.PHP_EOL; echo '$document->toJson($options);'.PHP_EOL; echo ''; -echo '
'.var_export($document->toJson($options), true).'
'; +echo '
'.var_export($document->toJson($options), return: true).'
'; /** * send json response diff --git a/examples/profile.php b/examples/profile.php index 82458551..5bce8471 100644 --- a/examples/profile.php +++ b/examples/profile.php @@ -32,7 +32,7 @@ * get the json */ -$contentType = Converter::prepareContentType(ContentTypeEnum::Official, [], [$profile]); +$contentType = Converter::prepareContentType(ContentTypeEnum::Official, extensions: [], profiles: [$profile]); echo 'Content-Type: '.$contentType.''.PHP_EOL; $options = [ diff --git a/examples/relationship_to_one_document.php b/examples/relationship_to_one_document.php index 7dfc6ebe..a715ea64 100644 --- a/examples/relationship_to_one_document.php +++ b/examples/relationship_to_one_document.php @@ -13,7 +13,7 @@ $relationshipDocument = new ResourceDocument('author', 12); -$relationshipDocument->setSelfLink('/articles/1/relationship/author', $meta=[], $level=DocumentLevelEnum::Root); +$relationshipDocument->setSelfLink('/articles/1/relationship/author', level: DocumentLevelEnum::Root); $relationshipDocument->addLink('related', '/articles/1/author'); /** diff --git a/examples/relationships.php b/examples/relationships.php index 6755f34d..73db5dc8 100644 --- a/examples/relationships.php +++ b/examples/relationships.php @@ -42,13 +42,13 @@ */ $options = ['includeContainedResources' => false]; -$document->addRelationship('excluded-ship', $ship2Resource, $links=[], $meta=[], $options); +$document->addRelationship('excluded-ship', $ship2Resource, options: $options); /** * to-many relationship, one-by-one */ -$relationshipObject = new RelationshipObject($type=RelationshipTypeEnum::ToMany); +$relationshipObject = new RelationshipObject(type: RelationshipTypeEnum::ToMany); $relationshipObject->addResource($friend1Resource); $relationshipObject->addResource($friend2Resource); @@ -68,7 +68,7 @@ * to-many relationship, different types */ -$relationshipObject = new RelationshipObject($type=RelationshipTypeEnum::ToMany); +$relationshipObject = new RelationshipObject(type: RelationshipTypeEnum::ToMany); $relationshipObject->addResource($ship1Resource); $relationshipObject->addResource($dockResource); @@ -78,10 +78,10 @@ * custom */ $jsonapi = new ResourceDocument('user', 1); -$custom_relation = [ +$customRelation = [ 'data' => ['cus' => 'tom'], ]; -$jsonapi->addRelationship('custom', $custom_relation); +$jsonapi->addRelationship('custom', $customRelation); /** * sending the response diff --git a/examples/resource_human_api.php b/examples/resource_human_api.php index b9ae514d..64fdc576 100644 --- a/examples/resource_human_api.php +++ b/examples/resource_human_api.php @@ -22,12 +22,12 @@ * objects are converted into arrays using their public keys */ -$document = ResourceDocument::fromObject($user1, $type='user', $user1->id); +$document = ResourceDocument::fromObject($user1, type: 'user', id: $user1->id); $document->add('location', $user1->getCurrentLocation()); $document->addLink('homepage', 'https://jsonapi.org'); $document->addMeta('difference', 'is in the code to generate this'); -$relation = ResourceDocument::fromObject($user42, $type='user', $user42->id); +$relation = ResourceDocument::fromObject($user42, type: 'user', id: $user42->id); $document->addRelationship('friend', $relation); /** diff --git a/examples/resource_links.php b/examples/resource_links.php index a79e1f82..6d9e8860 100644 --- a/examples/resource_links.php +++ b/examples/resource_links.php @@ -13,15 +13,15 @@ * add links in different ways to a resource * self links are adding both at root and in data levels */ -$document = ResourceDocument::fromObject($userEntity, $type='user', $userEntity->id); +$document = ResourceDocument::fromObject($userEntity, type: 'user', id: $userEntity->id); $selfResourceMeta = ['level' => DocumentLevelEnum::Resource->name]; $partnerMeta = ['level' => DocumentLevelEnum::Resource->name]; $redirectMeta = ['level' => DocumentLevelEnum::Root->name]; $document->setSelfLink('/user/42', $selfResourceMeta); -$document->addLink('partner', '/user/1', $partnerMeta, $level=DocumentLevelEnum::Resource); -$document->addLink('redirect', '/login', $redirectMeta, $level=DocumentLevelEnum::Root); +$document->addLink('partner', '/user/1', $partnerMeta, level: DocumentLevelEnum::Resource); +$document->addLink('redirect', '/login', $redirectMeta, level: DocumentLevelEnum::Root); /** * sending the response diff --git a/examples/resource_nested_relations.php b/examples/resource_nested_relations.php index e182a48b..b94b07e2 100644 --- a/examples/resource_nested_relations.php +++ b/examples/resource_nested_relations.php @@ -28,7 +28,7 @@ * building up the json response */ -$document = ResourceDocument::fromObject($userEntity, $type='user', $userEntity->id); +$document = ResourceDocument::fromObject($userEntity, type: 'user', id: $userEntity->id); $document->addRelationship('ship', $ship); /** diff --git a/rector.php b/rector.php index de660fc6..bba93d87 100644 --- a/rector.php +++ b/rector.php @@ -4,6 +4,7 @@ use Rector\Config\RectorConfig; use Rector\Php70\Rector\StmtsAwareInterface\IfIssetToCoalescingRector; +use Rector\TypeDeclaration\Rector\Class_\AddTestsVoidReturnTypeWhereNoReturnRector; use Rector\TypeDeclaration\Rector\StmtsAwareInterface\DeclareStrictTypesRector; // @see https://github.com/rectorphp/rector/blob/main/docs/rector_rules_overview.md for more rules @@ -16,6 +17,7 @@ ]) ->withRules([ DeclareStrictTypesRector::class, + AddTestsVoidReturnTypeWhereNoReturnRector::class, ]) ->withSkip([ // better explicit readability diff --git a/src/CollectionDocument.php b/src/CollectionDocument.php index 29f3d435..d3663039 100644 --- a/src/CollectionDocument.php +++ b/src/CollectionDocument.php @@ -38,8 +38,8 @@ class CollectionDocument extends DataDocument implements PaginableInterface, Res * * adds included resources if found inside the resource's relationships, use {@see ->addResource()} to change that behavior */ - public static function fromResources(ResourceInterface ...$resources): self { - $collectionDocument = new self(); + public static function fromResources(ResourceInterface ...$resources): static { + $collectionDocument = new static(); foreach ($resources as $resource) { $collectionDocument->addResource($resource); @@ -98,7 +98,7 @@ public function addResource(ResourceInterface $resource, array $options=[]): voi throw new InputException('does not make sense to add empty resources to a collection'); } - $options = array_merge(self::$defaults, $options); + $options = [...self::$defaults, ...$options]; $this->validator->claimUsedResourceIdentifier($resource); diff --git a/src/Document.php b/src/Document.php index e95a4cc4..0c2dfcdd 100644 --- a/src/Document.php +++ b/src/Document.php @@ -27,6 +27,10 @@ use alsvanzelf\jsonapi\objects\MetaObject; /** + * @phpstan-consistent-constructor + * warn when an extending constructor changes the arguments + * that might break the class since we use `new static()` + * * @see ResourceDocument, CollectionDocument, ErrorsDocument or MetaDocument */ abstract class Document implements DocumentInterface, \JsonSerializable, HasLinksInterface, HasMetaInterface, HasExtensionMembersInterface { @@ -48,7 +52,7 @@ abstract class Document implements DocumentInterface, \JsonSerializable, HasLink /** * encode to json with these default options */ - 'encodeOptions' => JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE, + 'encodeOptions' => JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR, /** * encode to human-readable json, useful when debugging @@ -132,7 +136,7 @@ public function setSelfLink(string $href, array $meta=[], DocumentLevelEnum $lev * @param array $meta if given a LinkObject is added, otherwise a link string is added */ public function setDescribedByLink(string $href, array $meta=[]): void { - $this->addLink('describedby', $href, $meta, $level=DocumentLevelEnum::Root); + $this->addLink('describedby', $href, $meta, DocumentLevelEnum::Root); } /** @@ -140,25 +144,28 @@ public function setDescribedByLink(string $href, array $meta=[]): void { * @throws InputException if the $level is DocumentLevelEnum::Resource */ public function addMeta(string $key, mixed $value, DocumentLevelEnum $level=DocumentLevelEnum::Root): void { - if ($level === DocumentLevelEnum::Root) { - if (isset($this->meta) === false) { - $this->setMetaObject(new MetaObject()); - } + switch ($level) { + case DocumentLevelEnum::Root: + if (isset($this->meta) === false) { + $this->setMetaObject(new MetaObject()); + } + + $this->meta->add($key, $value); + break; - $this->meta->add($key, $value); - } - elseif ($level === DocumentLevelEnum::Jsonapi) { - if (isset($this->jsonapi) === false) { - $this->setJsonapiObject(new JsonapiObject()); - } + case DocumentLevelEnum::Jsonapi: + if (isset($this->jsonapi) === false) { + $this->setJsonapiObject(new JsonapiObject()); + } + + $this->jsonapi->addMeta($key, $value); + break; - $this->jsonapi->addMeta($key, $value); - } - elseif ($level === DocumentLevelEnum::Resource) { - throw new InputException('level "resource" can only be set on a ResourceDocument'); - } - else { - throw new InputException('unknown level "'.$level->value.'"'); + case DocumentLevelEnum::Resource: + throw new InputException('level "resource" can only be set on a ResourceDocument'); + + default: + throw new InputException('unknown level "'.$level->value.'"'); } } @@ -234,10 +241,10 @@ public function toArray(): array { $array = []; if ($this->hasAtMembers()) { - $array = array_merge($array, $this->getAtMembers()); + $array = [...$array, ...$this->getAtMembers()]; } if ($this->hasExtensionMembers()) { - $array = array_merge($array, $this->getExtensionMembers()); + $array = [...$array, ...$this->getExtensionMembers()]; } if (isset($this->jsonapi) && $this->jsonapi->isEmpty() === false) { @@ -253,8 +260,11 @@ public function toArray(): array { return $array; } + /** + * @throws \JsonException + */ public function toJson(array $options=[]): string { - $options = array_merge(self::$defaults, $options); + $options = [...self::$defaults, ...$options]; $array = $options['array'] ?? $this->toArray(); @@ -263,9 +273,6 @@ public function toJson(array $options=[]): string { } $json = json_encode($array, $options['encodeOptions']); - if ($json === false) { - throw new Exception('failed to generate json: '.json_last_error_msg()); - } if ($options['jsonpCallback'] !== null) { $json = $options['jsonpCallback'].'('.$json.')'; @@ -275,7 +282,7 @@ public function toJson(array $options=[]): string { } public function sendResponse(array $options=[]): void { - $options = array_merge(self::$defaults, $options); + $options = [...self::$defaults, ...$options]; if ($this->httpStatusCode === 204) { http_response_code($this->httpStatusCode); diff --git a/src/ErrorsDocument.php b/src/ErrorsDocument.php index 3e905b44..546fbab1 100644 --- a/src/ErrorsDocument.php +++ b/src/ErrorsDocument.php @@ -44,10 +44,10 @@ public function __construct(?ErrorObject $errorObject=null) { /** * @param PHPStanTypeAlias_InternalOptions $options {@see ErrorsDocument::$defaults} */ - public static function fromException(\Throwable $exception, array $options=[]): self { - $options = array_merge(self::$defaults, $options); + public static function fromException(\Throwable $exception, array $options=[]): static { + $options = [...self::$defaults, ...$options]; - $errorsDocument = new self(); + $errorsDocument = new static(); $errorsDocument->addException($exception, $options); return $errorsDocument; @@ -61,7 +61,7 @@ public static function fromException(\Throwable $exception, array $options=[]): * @param PHPStanTypeAlias_InternalOptions $options {@see ErrorsDocument::$defaults} */ public function addException(\Throwable $exception, array $options=[]): void { - $options = array_merge(self::$defaults, $options); + $options = [...self::$defaults, ...$options]; $this->addErrorObject(ErrorObject::fromException($exception, $options)); diff --git a/src/MetaDocument.php b/src/MetaDocument.php index 22a18160..585daf95 100644 --- a/src/MetaDocument.php +++ b/src/MetaDocument.php @@ -21,8 +21,8 @@ class MetaDocument extends Document { /** * @param array $meta */ - public static function fromArray(array $meta): self { - $metaDocument = new self(); + public static function fromArray(array $meta): static { + $metaDocument = new static(); $metaDocument->setMetaObject(MetaObject::fromArray($meta)); return $metaDocument; @@ -31,10 +31,10 @@ public static function fromArray(array $meta): self { /** * @param object $meta */ - public static function fromObject(object $meta): self { + public static function fromObject(object $meta): static { $array = Converter::objectToArray($meta); - return self::fromArray($array); + return static::fromArray($array); } /** diff --git a/src/ResourceDocument.php b/src/ResourceDocument.php index e4da6f13..17bfda7d 100644 --- a/src/ResourceDocument.php +++ b/src/ResourceDocument.php @@ -58,8 +58,8 @@ public static function fromArray( ?string $type=null, string|int|null $id=null, array $options=[], - ): self { - $resourceDocument = new self(); + ): static { + $resourceDocument = new static(); $resourceDocument->setPrimaryResource(ResourceObject::fromArray($attributes, $type, $id, $options), $options); return $resourceDocument; @@ -73,10 +73,10 @@ public static function fromObject( ?string $type=null, string|int|null $id=null, array $options=[], - ): self { + ): static { $array = Converter::objectToArray($attributes); - return self::fromArray($array, $type, $id, $options); + return static::fromArray($array, $type, $id, $options); } /** @@ -114,7 +114,7 @@ public function addRelationship( throw new Exception('the resource is an identifier-only object'); } - $options = array_merge(self::$defaults, $options); + $options = [...self::$defaults, ...$options]; $relationshipObject = $this->resource->addRelationship($key, $relation, $links, $meta); @@ -133,12 +133,11 @@ public function addLink(string $key, ?string $href, array $meta=[], DocumentLeve throw new Exception('the resource is an identifier-only object'); } - if ($level === DocumentLevelEnum::Resource) { - $this->resource->addLink($key, $href, $meta); - } - else { - parent::addLink($key, $href, $meta, $level); - } + match ($level) { + DocumentLevelEnum::Resource => $this->resource->addLink($key, $href, $meta), + DocumentLevelEnum::Jsonapi, + DocumentLevelEnum::Root => parent::addLink($key, $href, $meta, $level), + }; } /** @@ -151,21 +150,19 @@ public function setSelfLink(string $href, array $meta=[], DocumentLevelEnum $lev throw new Exception('the resource is an identifier-only object'); } - if ($level === DocumentLevelEnum::Resource) { - $this->resource->setSelfLink($href, $meta); - } - else { - parent::setSelfLink($href, $meta, $level); - } + match ($level) { + DocumentLevelEnum::Resource => $this->resource->setSelfLink($href, $meta), + DocumentLevelEnum::Jsonapi, + DocumentLevelEnum::Root => parent::setSelfLink($href, $meta, $level), + }; } public function addMeta(string $key, mixed $value, DocumentLevelEnum $level=DocumentLevelEnum::Root): void { - if ($level === DocumentLevelEnum::Resource) { - $this->resource->addMeta($key, $value); - } - else { - parent::addMeta($key, $value, $level); - } + match ($level) { + DocumentLevelEnum::Resource => $this->resource->addMeta($key, $value), + DocumentLevelEnum::Jsonapi, + DocumentLevelEnum::Root => parent::addMeta($key, $value, $level), + }; } /** @@ -213,7 +210,7 @@ public function addRelationshipObject(string $key, RelationshipObject $relations throw new Exception('the resource is an identifier-only object'); } - $options = array_merge(self::$defaults, $options); + $options = [...self::$defaults, ...$options]; $this->resource->addRelationshipObject($key, $relationshipObject); @@ -234,7 +231,7 @@ public function setRelationshipsObject(RelationshipsObject $relationshipsObject, throw new Exception('the resource is an identifier-only object'); } - $options = array_merge(self::$defaults, $options); + $options = [...self::$defaults, ...$options]; $this->resource->setRelationshipsObject($relationshipsObject); @@ -263,7 +260,7 @@ public function setPrimaryResource(ResourceInterface $resource, array $options=[ /** @var ResourceIdentifierObject|ResourceObject $resource */ - $options = array_merge(self::$defaults, $options); + $options = [...self::$defaults, ...$options]; $this->resource = $resource; diff --git a/src/extensions/AtomicOperationsDocument.php b/src/extensions/AtomicOperationsDocument.php index 99ad54ad..93355890 100644 --- a/src/extensions/AtomicOperationsDocument.php +++ b/src/extensions/AtomicOperationsDocument.php @@ -33,7 +33,7 @@ public function __construct() { * @param ResourceInterface[] ...$resources */ public function addResults(ResourceInterface ...$resources): void { - $this->results = array_merge($this->results, $resources); + $this->results = [...$this->results, ...$resources]; } /** diff --git a/src/helpers/RequestParser.php b/src/helpers/RequestParser.php index 3348821c..0863c306 100644 --- a/src/helpers/RequestParser.php +++ b/src/helpers/RequestParser.php @@ -9,6 +9,11 @@ use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ServerRequestInterface; +/** + * @phpstan-consistent-constructor + * warn when an extending constructor changes the arguments + * that might break the class since we use `new static()` + */ class RequestParser { /** @var PHPStanTypeAlias_InternalOptions */ protected static array $defaults = [ @@ -29,6 +34,8 @@ class RequestParser { * @param string $selfLink the uri used to make this request {@see getSelfLink()} * @param array> $queryParameters all query parameters defined by the specification * @param array $document the request jsonapi document + * + * @throws \JsonException if $document's content type is json but it can't be json decoded */ public function __construct( private readonly string $selfLink='', @@ -36,7 +43,7 @@ public function __construct( private readonly array $document=[], ) {} - public static function fromSuperglobals(): self { + public static function fromSuperglobals(): static { $selfLink = ''; if (isset($_SERVER['REQUEST_SCHEME']) && isset($_SERVER['HTTP_HOST']) && isset($_SERVER['REQUEST_URI'])) { $selfLink = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; @@ -49,19 +56,22 @@ public static function fromSuperglobals(): self { $documentIsJsonapi = (str_contains((string) $_SERVER['CONTENT_TYPE'], ContentTypeEnum::Official->value)); $documentIsJson = (str_contains((string) $_SERVER['CONTENT_TYPE'], ContentTypeEnum::Debug->value)); - if ($documentIsJsonapi || $documentIsJson) { - $document = json_decode(file_get_contents('php://input'), true); - - if ($document === null) { - $document = []; - } + $document = file_get_contents('php://input'); + if ($document === '') { + $document = []; + } + elseif ($documentIsJsonapi || $documentIsJson) { + $document = json_decode($document, associative: true, flags: JSON_THROW_ON_ERROR); } } - return new self($selfLink, $queryParameters, $document); + return new static($selfLink, $queryParameters, $document); } - public static function fromPsrRequest(ServerRequestInterface|RequestInterface $request): self { + /** + * @throws \JsonException if the requests' document can't be json decoded + */ + public static function fromPsrRequest(ServerRequestInterface|RequestInterface $request): static { $selfLink = (string) $request->getUri(); if ($request instanceof ServerRequestInterface) { @@ -76,14 +86,10 @@ public static function fromPsrRequest(ServerRequestInterface|RequestInterface $r $document = []; } else { - $document = json_decode($request->getBody()->getContents(), true); - - if ($document === null) { - $document = []; - } + $document = json_decode($request->getBody()->getContents(), associative: true, flags: JSON_THROW_ON_ERROR); } - return new self($selfLink, $queryParameters, $document); + return new static($selfLink, $queryParameters, $document); } /** @@ -115,7 +121,7 @@ public function getIncludePaths(array $options=[]): array { $includePaths = explode(',', (string) $this->queryParameters['include']); - $options = array_merge(self::$defaults, $options); + $options = [...self::$defaults, ...$options]; if ($options['useNestedIncludePaths'] === false) { return $includePaths; } @@ -176,7 +182,7 @@ public function getSortFields(array $options=[]): array { $fields = explode(',', (string) $this->queryParameters['sort']); - $options = array_merge(self::$defaults, $options); + $options = [...self::$defaults, ...$options]; if ($options['useAnnotatedSortFields'] === false) { return $fields; } diff --git a/src/helpers/Validator.php b/src/helpers/Validator.php index 0639a9c3..d1010b61 100644 --- a/src/helpers/Validator.php +++ b/src/helpers/Validator.php @@ -38,7 +38,7 @@ class Validator { * @throws DuplicateException */ public function claimUsedFields(array $fieldNames, ObjectContainerEnum $objectContainer, array $options=[]): void { - $options = array_merge(self::$defaults, $options); + $options = [...self::$defaults, ...$options]; foreach ($fieldNames as $fieldName) { if (isset($this->usedFields[$fieldName]) === false) { diff --git a/src/objects/AttributesObject.php b/src/objects/AttributesObject.php index fe10420c..86600ffe 100644 --- a/src/objects/AttributesObject.php +++ b/src/objects/AttributesObject.php @@ -8,6 +8,11 @@ use alsvanzelf\jsonapi\helpers\Validator; use alsvanzelf\jsonapi\objects\AbstractObject; +/** + * @phpstan-consistent-constructor + * warn when an extending constructor changes the arguments + * that might break the class since we use `new static()` + */ class AttributesObject extends AbstractObject { /** @var array */ protected array $attributes = []; @@ -20,10 +25,10 @@ class AttributesObject extends AbstractObject { * @note if an `id` is set inside $attributes, it is removed from there * it is common to find it inside, and not doing so will cause an exception */ - public static function fromArray(array $attributes): self { + public static function fromArray(array $attributes): static { unset($attributes['id']); - $attributesObject = new self(); + $attributesObject = new static(); foreach ($attributes as $key => $value) { $attributesObject->add($key, $value); @@ -32,10 +37,10 @@ public static function fromArray(array $attributes): self { return $attributesObject; } - public static function fromObject(object $attributes): self { + public static function fromObject(object $attributes): static { $array = Converter::objectToArray($attributes); - return self::fromArray($array); + return static::fromArray($array); } /** @@ -87,12 +92,12 @@ public function toArray(): array { $array = []; if ($this->hasAtMembers()) { - $array = array_merge($array, $this->getAtMembers()); + $array = [...$array, ...$this->getAtMembers()]; } if ($this->hasExtensionMembers()) { - $array = array_merge($array, $this->getExtensionMembers()); + $array = [...$array, ...$this->getExtensionMembers()]; } - return array_merge($array, $this->attributes); + return [...$array, ...$this->attributes]; } } diff --git a/src/objects/ErrorObject.php b/src/objects/ErrorObject.php index 26e6ce73..cd47138c 100644 --- a/src/objects/ErrorObject.php +++ b/src/objects/ErrorObject.php @@ -13,6 +13,11 @@ use alsvanzelf\jsonapi\interfaces\HasMetaInterface; use alsvanzelf\jsonapi\objects\AbstractObject; +/** + * @phpstan-consistent-constructor + * warn when an extending constructor changes the arguments + * that might break the class since we use `new static()` + */ class ErrorObject extends AbstractObject implements HasLinksInterface, HasMetaInterface { use HttpStatusCodeManager; use LinksManager; @@ -68,13 +73,13 @@ public function __construct( /** * @param PHPStanTypeAlias_InternalOptions $options {@see ErrorObject::$defaults} */ - public static function fromException(\Throwable $exception, array $options=[]): self { - $options = array_merge(self::$defaults, $options); + public static function fromException(\Throwable $exception, array $options=[]): static { + $options = [...self::$defaults, ...$options]; - $errorObject = new self(); + $errorObject = new static(); $className = $exception::class; - if (strpos($className, '\\')) { + if (str_contains($className, '\\')) { $exploded = explode('\\', $className); $className = end($exploded); } @@ -285,10 +290,10 @@ public function toArray(): array { $array = []; if ($this->hasAtMembers()) { - $array = array_merge($array, $this->getAtMembers()); + $array = [...$array, ...$this->getAtMembers()]; } if ($this->hasExtensionMembers()) { - $array = array_merge($array, $this->getExtensionMembers()); + $array = [...$array, ...$this->getExtensionMembers()]; } if (isset($this->id)) { $array['id'] = $this->id; diff --git a/src/objects/JsonapiObject.php b/src/objects/JsonapiObject.php index f54d1aba..1ee51977 100644 --- a/src/objects/JsonapiObject.php +++ b/src/objects/JsonapiObject.php @@ -89,10 +89,10 @@ public function toArray(): array { $array = []; if ($this->hasAtMembers()) { - $array = array_merge($array, $this->getAtMembers()); + $array = [...$array, ...$this->getAtMembers()]; } if ($this->hasExtensionMembers()) { - $array = array_merge($array, $this->getExtensionMembers()); + $array = [...$array, ...$this->getExtensionMembers()]; } if (isset($this->version)) { $array['version'] = $this->version->value; diff --git a/src/objects/LinkObject.php b/src/objects/LinkObject.php index 0c483bef..5a13d2fb 100644 --- a/src/objects/LinkObject.php +++ b/src/objects/LinkObject.php @@ -43,7 +43,7 @@ public function addLanguage(string $language): void { $this->setHreflang($language); } else { - $this->setHreflang(...array_merge($this->hreflang, [$language])); + $this->setHreflang(...[...$this->hreflang, $language]); } } @@ -133,10 +133,10 @@ public function toArray(): array { $array = []; if ($this->hasAtMembers()) { - $array = array_merge($array, $this->getAtMembers()); + $array = [...$array, ...$this->getAtMembers()]; } if ($this->hasExtensionMembers()) { - $array = array_merge($array, $this->getExtensionMembers()); + $array = [...$array, ...$this->getExtensionMembers()]; } if (isset($this->href)) { diff --git a/src/objects/LinksObject.php b/src/objects/LinksObject.php index 65385ef7..3485f309 100644 --- a/src/objects/LinksObject.php +++ b/src/objects/LinksObject.php @@ -10,6 +10,11 @@ use alsvanzelf\jsonapi\objects\AbstractObject; use alsvanzelf\jsonapi\objects\LinkObject; +/** + * @phpstan-consistent-constructor + * warn when an extending constructor changes the arguments + * that might break the class since we use `new static()` + */ class LinksObject extends AbstractObject { /** @var array */ protected array $links = []; @@ -22,7 +27,7 @@ class LinksObject extends AbstractObject { * @param array $links key-value with values being href strings */ public static function fromArray(array $links): LinksObject { - $linksObject = new self(); + $linksObject = new static(); foreach ($links as $key => $href) { $linksObject->add($key, $href); @@ -34,7 +39,7 @@ public static function fromArray(array $links): LinksObject { public static function fromObject(object $links): LinksObject { $array = Converter::objectToArray($links); - return self::fromArray($array); + return static::fromArray($array); } /** @@ -101,10 +106,10 @@ public function toArray(): array { $array = []; if ($this->hasAtMembers()) { - $array = array_merge($array, $this->getAtMembers()); + $array = [...$array, ...$this->getAtMembers()]; } if ($this->hasExtensionMembers()) { - $array = array_merge($array, $this->getExtensionMembers()); + $array = [...$array, ...$this->getExtensionMembers()]; } foreach ($this->links as $key => $link) { diff --git a/src/objects/MetaObject.php b/src/objects/MetaObject.php index e52c5847..bc51c9e9 100644 --- a/src/objects/MetaObject.php +++ b/src/objects/MetaObject.php @@ -8,6 +8,11 @@ use alsvanzelf\jsonapi\helpers\Validator; use alsvanzelf\jsonapi\objects\AbstractObject; +/** + * @phpstan-consistent-constructor + * warn when an extending constructor changes the arguments + * that might break the class since we use `new static()` + */ class MetaObject extends AbstractObject { /** @var array */ protected array $meta = []; @@ -19,8 +24,8 @@ class MetaObject extends AbstractObject { /** * @param array $meta */ - public static function fromArray(array $meta): self { - $metaObject = new self(); + public static function fromArray(array $meta): static { + $metaObject = new static(); foreach ($meta as $key => $value) { $metaObject->add($key, $value); @@ -29,10 +34,10 @@ public static function fromArray(array $meta): self { return $metaObject; } - public static function fromObject(object $meta): self { + public static function fromObject(object $meta): static { $array = Converter::objectToArray($meta); - return self::fromArray($array); + return static::fromArray($array); } /** @@ -71,12 +76,12 @@ public function toArray(): array { $array = []; if ($this->hasAtMembers()) { - $array = array_merge($array, $this->getAtMembers()); + $array = [...$array, ...$this->getAtMembers()]; } if ($this->hasExtensionMembers()) { - $array = array_merge($array, $this->getExtensionMembers()); + $array = [...$array, ...$this->getExtensionMembers()]; } - return array_merge($array, $this->meta); + return [...$array, ...$this->meta]; } } diff --git a/src/objects/RelationshipObject.php b/src/objects/RelationshipObject.php index 2a4af1a0..e44ece9a 100644 --- a/src/objects/RelationshipObject.php +++ b/src/objects/RelationshipObject.php @@ -18,6 +18,11 @@ use alsvanzelf\jsonapi\objects\MetaObject; use alsvanzelf\jsonapi\objects\ResourceObject; +/** + * @phpstan-consistent-constructor + * warn when an extending constructor changes the arguments + * that might break the class since we use `new static()` + */ class RelationshipObject extends AbstractObject implements PaginableInterface, RecursiveResourceContainerInterface, HasLinksInterface, HasMetaInterface { use LinksManager; @@ -47,22 +52,22 @@ public static function fromAnything( array|CollectionDocument|ResourceInterface|null $relation, array $links=[], array $meta=[], - ): self { + ): static { if (is_array($relation)) { $relation = CollectionDocument::fromResources(...$relation); } if ($relation instanceof ResourceInterface) { - $relationshipObject = self::fromResource($relation, $links, $meta); + $relationshipObject = static::fromResource($relation, $links, $meta); } elseif ($relation instanceof CollectionDocument) { - $relationshipObject = self::fromCollectionDocument($relation, $links, $meta); + $relationshipObject = static::fromCollectionDocument($relation, $links, $meta); } elseif ($relation === null) { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); } else { - throw new InputException('unknown format of relation "'.gettype($relation).'"'); + throw new InputException('unknown format of relation "'.get_debug_type($relation).'"'); } return $relationshipObject; @@ -77,8 +82,8 @@ public static function fromResource( array $links=[], array $meta=[], RelationshipTypeEnum $type=RelationshipTypeEnum::ToOne, - ): self { - $relationshipObject = new self($type); + ): static { + $relationshipObject = new static($type); match ($type) { RelationshipTypeEnum::ToOne => $relationshipObject->setResource($resource), @@ -99,8 +104,8 @@ public static function fromResource( * @param array $links * @param array $meta */ - public static function fromCollectionDocument(CollectionDocument $collectionDocument, array $links=[], array $meta=[]): self { - $relationshipObject = new self(RelationshipTypeEnum::ToMany); + public static function fromCollectionDocument(CollectionDocument $collectionDocument, array $links=[], array $meta=[]): static { + $relationshipObject = new static(RelationshipTypeEnum::ToMany); foreach ($collectionDocument->getContainedResources() as $resource) { $relationshipObject->addResource($resource); @@ -233,12 +238,14 @@ public function hasResource(ResourceInterface $otherResource): bool { */ public function isEmpty(): bool { - if ($this->type === RelationshipTypeEnum::ToOne && isset($this->resource)) { - return false; - } - if ($this->type === RelationshipTypeEnum::ToMany && $this->resources !== []) { + $resourceIsNotEmpty = match ($this->type) { + RelationshipTypeEnum::ToOne => isset($this->resource), + RelationshipTypeEnum::ToMany => $this->resources !== [], + }; + if ($resourceIsNotEmpty) { return false; } + if ($this->hasLinks()) { return false; } @@ -259,27 +266,32 @@ public function toArray(): array { $array = []; if ($this->hasAtMembers()) { - $array = array_merge($array, $this->getAtMembers()); + $array = [...$array, ...$this->getAtMembers()]; } if ($this->hasExtensionMembers()) { - $array = array_merge($array, $this->getExtensionMembers()); + $array = [...$array, ...$this->getExtensionMembers()]; } if ($this->hasLinks()) { $array['links'] = $this->links->toArray(); } - if ($this->type === RelationshipTypeEnum::ToOne) { - $array['data'] = null; - if (isset($this->resource)) { - $array['data'] = $this->resource->getResource($identifierOnly=true)->toArray(); - } - } - if ($this->type === RelationshipTypeEnum::ToMany) { - $array['data'] = []; - foreach ($this->resources as $resource) { - $array['data'][] = $resource->getResource($identifierOnly=true)->toArray(); - } + + switch ($this->type) { + case RelationshipTypeEnum::ToOne: + $array['data'] = null; + if (isset($this->resource)) { + $array['data'] = $this->resource->getResource(identifierOnly: true)->toArray(); + } + break; + + case RelationshipTypeEnum::ToMany: + $array['data'] = []; + foreach ($this->resources as $resource) { + $array['data'][] = $resource->getResource(identifierOnly: true)->toArray(); + } + break; } + if (isset($this->meta) && $this->meta->isEmpty() === false) { $array['meta'] = $this->meta->toArray(); } @@ -296,7 +308,11 @@ public function getNestedContainedResourceObjects(): array { return []; } - $resources = ($this->type === RelationshipTypeEnum::ToOne) ? [$this->resource] : $this->resources; + $resources = match ($this->type) { + RelationshipTypeEnum::ToOne => [$this->resource], + RelationshipTypeEnum::ToMany => $this->resources, + }; + $resourceObjects = []; foreach ($resources as $resource) { @@ -312,7 +328,7 @@ public function getNestedContainedResourceObjects(): array { } $resourceObjects[] = $resourceObject; - $resourceObjects = array_merge($resourceObjects, $resourceObject->getNestedContainedResourceObjects()); + $resourceObjects = [...$resourceObjects, ...$resourceObject->getNestedContainedResourceObjects()]; } return $resourceObjects; diff --git a/src/objects/RelationshipsObject.php b/src/objects/RelationshipsObject.php index 54edd3e0..537f909c 100644 --- a/src/objects/RelationshipsObject.php +++ b/src/objects/RelationshipsObject.php @@ -92,10 +92,10 @@ public function toArray(): array { $array = []; if ($this->hasAtMembers()) { - $array = array_merge($array, $this->getAtMembers()); + $array = [...$array, ...$this->getAtMembers()]; } if ($this->hasExtensionMembers()) { - $array = array_merge($array, $this->getExtensionMembers()); + $array = [...$array, ...$this->getExtensionMembers()]; } foreach ($this->relationships as $key => $relationshipObject) { @@ -113,7 +113,7 @@ public function getNestedContainedResourceObjects(): array { $resourceObjects = []; foreach ($this->relationships as $relationship) { - $resourceObjects = array_merge($resourceObjects, $relationship->getNestedContainedResourceObjects()); + $resourceObjects = [...$resourceObjects, ...$relationship->getNestedContainedResourceObjects()]; } return $resourceObjects; diff --git a/src/objects/ResourceIdentifierObject.php b/src/objects/ResourceIdentifierObject.php index 22d35e9b..5f09cd4d 100644 --- a/src/objects/ResourceIdentifierObject.php +++ b/src/objects/ResourceIdentifierObject.php @@ -14,6 +14,11 @@ use alsvanzelf\jsonapi\objects\AbstractObject; use alsvanzelf\jsonapi\objects\MetaObject; +/** + * @phpstan-consistent-constructor + * warn when an extending constructor changes the arguments + * that might break the class since we use `new static()` + */ class ResourceIdentifierObject extends AbstractObject implements HasMetaInterface, ResourceInterface { protected string $type; protected string $id; @@ -37,9 +42,9 @@ public function __construct(?string $type=null, string|int|null $id=null) { } // always mark as used, as these keys are reserved - $this->validator->claimUsedFields($fieldNames=['type'], ObjectContainerEnum::Type); - $this->validator->claimUsedFields($fieldNames=['id'], ObjectContainerEnum::Id); - $this->validator->claimUsedFields($fieldNames=['lid'], ObjectContainerEnum::Lid); + $this->validator->claimUsedFields(['type'], ObjectContainerEnum::Type); + $this->validator->claimUsedFields(['id'], ObjectContainerEnum::Id); + $this->validator->claimUsedFields(['lid'], ObjectContainerEnum::Lid); } /** @@ -105,12 +110,12 @@ public function setMetaObject(MetaObject $metaObject): void { * * @throws InputException if the $resourceoObject's type or id is not set yet */ - public static function fromResourceObject(ResourceObject $resourceObject): self { + public static function fromResourceObject(ResourceObject $resourceObject): static { if ($resourceObject->hasIdentification() === false) { throw new InputException('resource has no identification yet<'); } - $resourceIdentifierObject = new self($resourceObject->type, $resourceObject->primaryId()); + $resourceIdentifierObject = new static($resourceObject->type, $resourceObject->primaryId()); if (isset($resourceObject->meta)) { $resourceIdentifierObject->setMetaObject($resourceObject->meta); @@ -200,10 +205,10 @@ public function toArray(): array { } if ($this->hasAtMembers()) { - $array = array_merge($array, $this->getAtMembers()); + $array = [...$array, ...$this->getAtMembers()]; } if ($this->hasExtensionMembers()) { - $array = array_merge($array, $this->getExtensionMembers()); + $array = [...$array, ...$this->getExtensionMembers()]; } if (isset($this->meta) && $this->meta->isEmpty() === false) { diff --git a/src/objects/ResourceObject.php b/src/objects/ResourceObject.php index 67a4478e..8f115f59 100644 --- a/src/objects/ResourceObject.php +++ b/src/objects/ResourceObject.php @@ -45,7 +45,7 @@ class ResourceObject extends ResourceIdentifierObject implements HasAttributesIn * @param array $attributes * @param PHPStanTypeAlias_InternalOptions $options {@see ResourceObject::$defaults} */ - public static function fromArray(array $attributes, ?string $type=null, string|int|null $id=null, array $options=[]): self { + public static function fromArray(array $attributes, ?string $type=null, string|int|null $id=null, array $options=[]): static { if (isset($attributes['id'])) { if ($id === null) { $id = $attributes['id']; @@ -54,7 +54,7 @@ public static function fromArray(array $attributes, ?string $type=null, string|i unset($attributes['id']); } - $resourceObject = new self($type, $id); + $resourceObject = new static($type, $id); $resourceObject->setAttributesObject(AttributesObject::fromArray($attributes), $options); return $resourceObject; @@ -63,10 +63,10 @@ public static function fromArray(array $attributes, ?string $type=null, string|i /** * @param PHPStanTypeAlias_InternalOptions $options {@see ResourceObject::$defaults} */ - public static function fromObject(object $attributes, ?string $type=null, string|int|null $id=null, array $options=[]): self { + public static function fromObject(object $attributes, ?string $type=null, string|int|null $id=null, array $options=[]): static { $array = Converter::objectToArray($attributes); - return self::fromArray($array, $type, $id, $options); + return static::fromArray($array, $type, $id, $options); } /** @@ -75,7 +75,7 @@ public static function fromObject(object $attributes, ?string $type=null, string * @param PHPStanTypeAlias_InternalOptions $options {@see ResourceObject::$defaults} */ public function add(string $key, mixed $value, array $options=[]): void { - $options = array_merge(self::$defaults, $options); + $options = [...self::$defaults, ...$options]; if (isset($this->attributes) === false) { $this->attributes = new AttributesObject(); diff --git a/src/profiles/CursorPaginationProfile.php b/src/profiles/CursorPaginationProfile.php index aabf16dd..75825210 100644 --- a/src/profiles/CursorPaginationProfile.php +++ b/src/profiles/CursorPaginationProfile.php @@ -165,7 +165,7 @@ public function setItemMeta(ResourceInterface & HasMetaInterface $resource, stri ]; if ($resource instanceof ResourceDocument) { - $resource->addMeta('page', $metadata, $level=DocumentLevelEnum::Resource); + $resource->addMeta('page', $metadata, DocumentLevelEnum::Resource); } else { $resource->addMeta('page', $metadata); @@ -240,7 +240,7 @@ public function getMaxPageSizeExceededErrorObject(int $maxSize, ?string $generic $errorObject->setTypeLink('https://jsonapi.org/profiles/ethanresnick/cursor-pagination/max-size-exceeded'); $errorObject->blameQueryParameter('page[size]'); $errorObject->setHttpStatusCode(400); - $errorObject->addMeta('page', $value=['maxSize' => $maxSize]); + $errorObject->addMeta('page', ['maxSize' => $maxSize]); if ($genericTitle !== null) { $errorObject->setHumanExplanation($genericTitle, $specificDetails); diff --git a/tests/CollectionDocumentTest.php b/tests/CollectionDocumentTest.php index 97ce3e86..b05004ab 100644 --- a/tests/CollectionDocumentTest.php +++ b/tests/CollectionDocumentTest.php @@ -11,16 +11,16 @@ use alsvanzelf\jsonapi\objects\ResourceObject; class CollectionDocumentTest extends TestCase { - public function testConstructor_NoResources() { + public function testConstructor_NoResources(): void { $document = new CollectionDocument(); $array = $document->toArray(); - $this->assertArrayHasKey('data', $array); - $this->assertSame([], $array['data']); + parent::assertArrayHasKey('data', $array); + parent::assertSame([], $array['data']); } - public function testAdd_WithIdentifiers() { + public function testAdd_WithIdentifiers(): void { $document = new CollectionDocument(); $document->add('user', 1); @@ -28,26 +28,26 @@ public function testAdd_WithIdentifiers() { $array = $document->toArray(); - $this->assertArrayHasKey('data', $array); - $this->assertArrayNotHasKey('included', $array); - $this->assertCount(2, $array['data']); - - $this->assertCount(2, $array['data'][0]); - $this->assertArrayHasKey('type', $array['data'][0]); - $this->assertArrayHasKey('id', $array['data'][0]); - $this->assertArrayNotHasKey('attributes', $array['data'][0]); - $this->assertSame('user', $array['data'][0]['type']); - $this->assertSame('1', $array['data'][0]['id']); - - $this->assertCount(2, $array['data'][1]); - $this->assertArrayHasKey('type', $array['data'][1]); - $this->assertArrayHasKey('id', $array['data'][1]); - $this->assertArrayNotHasKey('attributes', $array['data'][1]); - $this->assertSame('user', $array['data'][1]['type']); - $this->assertSame('42', $array['data'][1]['id']); + parent::assertArrayHasKey('data', $array); + parent::assertArrayNotHasKey('included', $array); + parent::assertCount(2, $array['data']); + + parent::assertCount(2, $array['data'][0]); + parent::assertArrayHasKey('type', $array['data'][0]); + parent::assertArrayHasKey('id', $array['data'][0]); + parent::assertArrayNotHasKey('attributes', $array['data'][0]); + parent::assertSame('user', $array['data'][0]['type']); + parent::assertSame('1', $array['data'][0]['id']); + + parent::assertCount(2, $array['data'][1]); + parent::assertArrayHasKey('type', $array['data'][1]); + parent::assertArrayHasKey('id', $array['data'][1]); + parent::assertArrayNotHasKey('attributes', $array['data'][1]); + parent::assertSame('user', $array['data'][1]['type']); + parent::assertSame('42', $array['data'][1]['id']); } - public function testAdd_WithAttributes() { + public function testAdd_WithAttributes(): void { $document = new CollectionDocument(); $document->add('user', 1, ['name' => 'foo']); @@ -55,32 +55,32 @@ public function testAdd_WithAttributes() { $array = $document->toArray(); - $this->assertArrayHasKey('data', $array); - $this->assertArrayNotHasKey('included', $array); - $this->assertCount(2, $array['data']); + parent::assertArrayHasKey('data', $array); + parent::assertArrayNotHasKey('included', $array); + parent::assertCount(2, $array['data']); $firstResource = $array['data'][0]; - $this->assertCount(3, $firstResource); - $this->assertArrayHasKey('type', $firstResource); - $this->assertArrayHasKey('id', $firstResource); - $this->assertArrayHasKey('attributes', $firstResource); - $this->assertSame('user', $firstResource['type']); - $this->assertSame('1', $firstResource['id']); - $this->assertArrayHasKey('name', $firstResource['attributes']); - $this->assertSame('foo', $firstResource['attributes']['name']); + parent::assertCount(3, $firstResource); + parent::assertArrayHasKey('type', $firstResource); + parent::assertArrayHasKey('id', $firstResource); + parent::assertArrayHasKey('attributes', $firstResource); + parent::assertSame('user', $firstResource['type']); + parent::assertSame('1', $firstResource['id']); + parent::assertArrayHasKey('name', $firstResource['attributes']); + parent::assertSame('foo', $firstResource['attributes']['name']); $secondResource = $array['data'][1]; - $this->assertCount(3, $secondResource); - $this->assertArrayHasKey('type', $secondResource); - $this->assertArrayHasKey('id', $secondResource); - $this->assertArrayHasKey('attributes', $secondResource); - $this->assertSame('user', $secondResource['type']); - $this->assertSame('42', $secondResource['id']); - $this->assertArrayHasKey('name', $secondResource['attributes']); - $this->assertSame('bar', $secondResource['attributes']['name']); + parent::assertCount(3, $secondResource); + parent::assertArrayHasKey('type', $secondResource); + parent::assertArrayHasKey('id', $secondResource); + parent::assertArrayHasKey('attributes', $secondResource); + parent::assertSame('user', $secondResource['type']); + parent::assertSame('42', $secondResource['id']); + parent::assertArrayHasKey('name', $secondResource['attributes']); + parent::assertSame('bar', $secondResource['attributes']['name']); } - public function testSetPaginationLinks_HappyPath() { + public function testSetPaginationLinks_HappyPath(): void { $document = new CollectionDocument(); $baseUrl = 'https://jsonapi.org/?page='; @@ -88,20 +88,20 @@ public function testSetPaginationLinks_HappyPath() { $array = $document->toArray(); - $this->assertArrayHasKey('links', $array); - $this->assertCount(4, $array['links']); - $this->assertArrayHasKey('prev', $array['links']); - $this->assertArrayHasKey('next', $array['links']); - $this->assertArrayHasKey('first', $array['links']); - $this->assertArrayHasKey('last', $array['links']); - $this->assertSame($baseUrl.'prev', $array['links']['prev']); - $this->assertSame($baseUrl.'next', $array['links']['next']); - $this->assertSame($baseUrl.'first', $array['links']['first']); - $this->assertSame($baseUrl.'last', $array['links']['last']); + parent::assertArrayHasKey('links', $array); + parent::assertCount(4, $array['links']); + parent::assertArrayHasKey('prev', $array['links']); + parent::assertArrayHasKey('next', $array['links']); + parent::assertArrayHasKey('first', $array['links']); + parent::assertArrayHasKey('last', $array['links']); + parent::assertSame($baseUrl.'prev', $array['links']['prev']); + parent::assertSame($baseUrl.'next', $array['links']['next']); + parent::assertSame($baseUrl.'first', $array['links']['first']); + parent::assertSame($baseUrl.'last', $array['links']['last']); } #[DataProvider('dataProviderSetPaginationLinks_IndividualLinks')] - public function testSetPaginationLinks_IndividualLinks($key, $previous, $next, $first, $last) { + public function testSetPaginationLinks_IndividualLinks($key, $previous, $next, $first, $last): void { $document = new CollectionDocument(); $document->setPaginationLinks($previous, $next, $first, $last); @@ -109,13 +109,13 @@ public function testSetPaginationLinks_IndividualLinks($key, $previous, $next, $ $array = $document->toArray(); if ($key === null) { - $this->assertArrayNotHasKey('links', $array); + parent::assertArrayNotHasKey('links', $array); } else { - $this->assertArrayHasKey('links', $array); - $this->assertCount(1, $array['links']); - $this->assertArrayHasKey($key, $array['links']); - $this->assertSame('https://jsonapi.org', $array['links'][$key]); + parent::assertArrayHasKey('links', $array); + parent::assertCount(1, $array['links']); + parent::assertArrayHasKey($key, $array['links']); + parent::assertSame('https://jsonapi.org', $array['links'][$key]); } } @@ -129,19 +129,19 @@ public static function dataProviderSetPaginationLinks_IndividualLinks() { ]; } - public function testAddResource_HappyPath() { + public function testAddResource_HappyPath(): void { $document = new CollectionDocument(); $document->addResource(new ResourceObject('user', 42)); $array = $document->toArray(); - $this->assertCount(1, $array['data']); - $this->assertSame('user', $array['data'][0]['type']); - $this->assertSame('42', $array['data'][0]['id']); - $this->assertArrayNotHasKey('attributes', $array['data'][0]); + parent::assertCount(1, $array['data']); + parent::assertSame('user', $array['data'][0]['type']); + parent::assertSame('42', $array['data'][0]['id']); + parent::assertArrayNotHasKey('attributes', $array['data'][0]); } - public function testAddResource_WithIncluded() { + public function testAddResource_WithIncluded(): void { $relatedResourceObject = new ResourceObject('user', 24); $relatedResourceObject->add('foo', 'bar'); @@ -153,16 +153,16 @@ public function testAddResource_WithIncluded() { $array = $document->toArray(); - $this->assertArrayHasKey('data', $array); - $this->assertArrayHasKey('included', $array); - $this->assertArrayHasKey('relationships', $array['data'][0]); - $this->assertArrayHasKey('attributes', $array['included'][0]); - $this->assertSame('42', $array['data'][0]['id']); - $this->assertSame('24', $array['data'][0]['relationships']['foo']['data']['id']); - $this->assertSame('24', $array['included'][0]['id']); + parent::assertArrayHasKey('data', $array); + parent::assertArrayHasKey('included', $array); + parent::assertArrayHasKey('relationships', $array['data'][0]); + parent::assertArrayHasKey('attributes', $array['included'][0]); + parent::assertSame('42', $array['data'][0]['id']); + parent::assertSame('24', $array['data'][0]['relationships']['foo']['data']['id']); + parent::assertSame('24', $array['included'][0]['id']); } - public function testAddResource_DoNotIncludeContainedResources() { + public function testAddResource_DoNotIncludeContainedResources(): void { $relatedResourceObject = new ResourceObject('user', 24); $relatedResourceObject->add('foo', 'bar'); @@ -176,14 +176,14 @@ public function testAddResource_DoNotIncludeContainedResources() { $array = $document->toArray(); - $this->assertArrayHasKey('data', $array); - $this->assertArrayNotHasKey('included', $array); - $this->assertArrayHasKey('relationships', $array['data'][0]); - $this->assertSame('42', $array['data'][0]['id']); - $this->assertSame('24', $array['data'][0]['relationships']['foo']['data']['id']); + parent::assertArrayHasKey('data', $array); + parent::assertArrayNotHasKey('included', $array); + parent::assertArrayHasKey('relationships', $array['data'][0]); + parent::assertSame('42', $array['data'][0]['id']); + parent::assertSame('24', $array['data'][0]['relationships']['foo']['data']['id']); } - public function testAddResource_RequiresIdentification() { + public function testAddResource_RequiresIdentification(): void { $document = new CollectionDocument(); $this->expectException(InputException::class); @@ -191,7 +191,7 @@ public function testAddResource_RequiresIdentification() { $document->addResource(new ResourceObject()); } - public function testAddResource_RequiresFullIdentification() { + public function testAddResource_RequiresFullIdentification(): void { $document = new CollectionDocument(); $this->expectException(InputException::class); @@ -199,27 +199,27 @@ public function testAddResource_RequiresFullIdentification() { $document->addResource(new ResourceObject('user')); } - public function testGetContainedResources_HappyPath() { + public function testGetContainedResources_HappyPath(): void { $document = new CollectionDocument(); - $this->assertCount(0, $document->getContainedResources()); + parent::assertCount(0, $document->getContainedResources()); $document->add('user', 42); - $this->assertCount(1, $document->getContainedResources()); + parent::assertCount(1, $document->getContainedResources()); $document->add('user', 24); - $this->assertCount(2, $document->getContainedResources()); + parent::assertCount(2, $document->getContainedResources()); } - public function testGetContainedResources_NoNestedResources() { + public function testGetContainedResources_NoNestedResources(): void { $document = new CollectionDocument(); $resourceObject = new ResourceObject('user', 42); $resourceObject->addRelationship('foo', new ResourceObject('user', 24)); $document->addResource($resourceObject); - $this->assertCount(1, $document->getContainedResources()); + parent::assertCount(1, $document->getContainedResources()); } } diff --git a/tests/ConverterTest.php b/tests/ConverterTest.php index 57f41b6f..d2af386a 100644 --- a/tests/ConverterTest.php +++ b/tests/ConverterTest.php @@ -4,56 +4,62 @@ namespace alsvanzelf\jsonapiTests; -use PHPUnit\Framework\Attributes\DataProvider; -use PHPUnit\Framework\TestCase; -use alsvanzelf\jsonapiTests\extensions\TestExtension; -use alsvanzelf\jsonapiTests\profiles\TestProfile; use alsvanzelf\jsonapi\enums\ContentTypeEnum; use alsvanzelf\jsonapi\helpers\Converter; +use alsvanzelf\jsonapi\interfaces\ExtensionInterface; +use alsvanzelf\jsonapi\interfaces\ProfileInterface; use alsvanzelf\jsonapi\objects\AttributesObject; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\TestCase; class ConverterTest extends TestCase { - public function testObjectToArray_HappyPath() { + public function testObjectToArray_HappyPath(): void { $object = new \stdClass(); $object->foo = 'bar'; $object->baz = 42; $array = Converter::objectToArray($object); - $this->assertCount(2, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertArrayHasKey('baz', $array); - $this->assertSame('bar', $array['foo']); - $this->assertSame(42, $array['baz']); + parent::assertCount(2, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertArrayHasKey('baz', $array); + parent::assertSame('bar', $array['foo']); + parent::assertSame(42, $array['baz']); } - public function testObjectToArray_MethodsAndPrivateProperties() { - $object = new TestObject(); + public function testObjectToArray_MethodsAndPrivateProperties(): void { + $object = new class { + public $foo = 'bar'; + public $baz = 42; + private $secret = 'value'; // @phpstan-ignore property.onlyWritten + public function method() {} + }; + $array = Converter::objectToArray($object); - $this->assertCount(2, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertArrayHasKey('baz', $array); - $this->assertArrayNotHasKey('secret', $array); - $this->assertArrayNotHasKey('method', $array); + parent::assertCount(2, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertArrayHasKey('baz', $array); + parent::assertArrayNotHasKey('secret', $array); + parent::assertArrayNotHasKey('method', $array); } - public function testObjectToArray_FromInternalObject() { + public function testObjectToArray_FromInternalObject(): void { $values = ['foo'=>'bar', 'baz'=>42]; $attributesObject = AttributesObject::fromArray($values); $array = Converter::objectToArray($attributesObject); - $this->assertCount(2, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertArrayHasKey('baz', $array); - $this->assertSame('bar', $array['foo']); - $this->assertSame(42, $array['baz']); + parent::assertCount(2, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertArrayHasKey('baz', $array); + parent::assertSame('bar', $array['foo']); + parent::assertSame(42, $array['baz']); } #[DataProvider('dataProviderCamelCaseToWords_HappyPath')] - public function testCamelCaseToWords_HappyPath($camelCase, $expectedOutput) { - $this->assertSame($expectedOutput, Converter::camelCaseToWords($camelCase)); + public function testCamelCaseToWords_HappyPath($camelCase, $expectedOutput): void { + parent::assertSame($expectedOutput, Converter::camelCaseToWords($camelCase)); } public static function dataProviderCamelCaseToWords_HappyPath() { @@ -70,54 +76,41 @@ public static function dataProviderCamelCaseToWords_HappyPath() { * @group Extensions * @group Profiles */ - public function testPrepareContentType_HappyPath() { - $this->assertSame(ContentTypeEnum::Official->value, Converter::prepareContentType(ContentTypeEnum::Official, [], [])); + public function testPrepareContentType_HappyPath(): void { + parent::assertSame(ContentTypeEnum::Official->value, Converter::prepareContentType(ContentTypeEnum::Official, [], [])); } /** * @group Extensions */ - public function testPrepareContentType_WithExtensionStringLink() { - $extension = new TestExtension(); - $extension->setOfficialLink('bar'); + public function testPrepareContentType_WithExtensionStringLink(): void { + $extension = parent::createConfiguredStub(ExtensionInterface::class, ['getOfficialLink' => 'bar']); - $this->assertSame(ContentTypeEnum::Official->value.'; ext="bar"', Converter::prepareContentType(ContentTypeEnum::Official, [$extension], [])); + parent::assertSame(ContentTypeEnum::Official->value.'; ext="bar"', Converter::prepareContentType(ContentTypeEnum::Official, [$extension], [])); } /** * @group Profiles */ - public function testPrepareContentType_WithProfileStringLink() { - $profile = new TestProfile(); - $profile->setOfficialLink('bar'); + public function testPrepareContentType_WithProfileStringLink(): void { + $profile = parent::createConfiguredStub(ProfileInterface::class, ['getOfficialLink' => 'bar']); - $this->assertSame(ContentTypeEnum::Official->value.'; profile="bar"', Converter::prepareContentType(ContentTypeEnum::Official, [], [$profile])); + parent::assertSame(ContentTypeEnum::Official->value.'; profile="bar"', Converter::prepareContentType(ContentTypeEnum::Official, [], [$profile])); } /** * @group Extensions * @group Profiles */ - public function testPrepareContentType_WithMultipleExtensionsAndProfiles() { - $extension1 = new TestExtension(); - $extension1->setOfficialLink('bar'); + public function testPrepareContentType_WithMultipleExtensionsAndProfiles(): void { + $extension1 = parent::createConfiguredStub(ExtensionInterface::class, ['getOfficialLink' => 'bar']); + $extension2 = parent::createConfiguredStub(ExtensionInterface::class, ['getOfficialLink' => 'baz']); + $profile1 = parent::createConfiguredStub(ProfileInterface::class, ['getOfficialLink' => 'bar']); + $profile2 = parent::createConfiguredStub(ProfileInterface::class, ['getOfficialLink' => 'baz']); - $extension2 = new TestExtension(); - $extension2->setOfficialLink('baz'); + $expectedContentType = ContentTypeEnum::Official->value.'; ext="bar baz"; profile="bar baz"'; + $convertedContentType = Converter::prepareContentType(ContentTypeEnum::Official, [$extension1, $extension2], [$profile1, $profile2]); - $profile1 = new TestProfile(); - $profile1->setOfficialLink('bar'); - - $profile2 = new TestProfile(); - $profile2->setOfficialLink('baz'); - - $this->assertSame(ContentTypeEnum::Official->value.'; ext="bar baz"; profile="bar baz"', Converter::prepareContentType(ContentTypeEnum::Official, [$extension1, $extension2], [$profile1, $profile2])); + parent::assertSame($expectedContentType, $convertedContentType); } } - -class TestObject { - public $foo = 'bar'; - public $baz = 42; - private $secret = 'value'; // @phpstan-ignore property.onlyWritten - public function method() {} -} diff --git a/tests/DocumentTest.php b/tests/DocumentTest.php index 024f989d..625088ef 100644 --- a/tests/DocumentTest.php +++ b/tests/DocumentTest.php @@ -4,350 +4,319 @@ namespace alsvanzelf\jsonapiTests; +use alsvanzelf\jsonapi\Document; use alsvanzelf\jsonapi\enums\DocumentLevelEnum; use alsvanzelf\jsonapi\exceptions\DuplicateException; use alsvanzelf\jsonapi\exceptions\Exception; use alsvanzelf\jsonapi\exceptions\InputException; +use alsvanzelf\jsonapi\interfaces\ExtensionInterface; +use alsvanzelf\jsonapi\interfaces\ProfileInterface; use alsvanzelf\jsonapi\objects\LinkObject; -use alsvanzelf\jsonapiTests\TestableNonAbstractDocument as Document; -use alsvanzelf\jsonapiTests\extensions\TestExtension; -use alsvanzelf\jsonapiTests\profiles\TestProfile; use PHPUnit\Framework\TestCase; class DocumentTest extends TestCase { - public function testConstructor_NoContent() { - $document = new Document(); - - $array = $document->toArray(); - - $this->assertCount(1, $array); - $this->assertArrayHasKey('jsonapi', $array); + private object $document; + + public function setUp(): void { + /** + * extending Document to make it non-abstract to test against it + * + * the abstract declaration is to make sure to create valid jsonapi output + * as it needs at least one of `data`, `meta` or `errors` + */ + $this->document = new class extends Document {}; } - public function testSetHttpStatusCode_HappyPath() { - $document = new Document(); + public function testConstructor_NoContent(): void { + $array = $this->document->toArray(); - $this->assertTrue($document->hasHttpStatusCode()); - $this->assertSame(200, $document->getHttpStatusCode()); + parent::assertCount(1, $array); + parent::assertArrayHasKey('jsonapi', $array); } - public function testAddLink_HappyPath() { - $document = new Document(); - - $array = $document->toArray(); - $this->assertArrayNotHasKey('links', $array); + public function testSetHttpStatusCode_HappyPath(): void { + parent::assertTrue($this->document->hasHttpStatusCode()); + parent::assertSame(200, $this->document->getHttpStatusCode()); + } + + public function testAddLink_HappyPath(): void { + $array = $this->document->toArray(); + parent::assertArrayNotHasKey('links', $array); - $document->addLink('foo', 'https://jsonapi.org'); + $this->document->addLink('foo', 'https://jsonapi.org'); - $array = $document->toArray(); + $array = $this->document->toArray(); - $this->assertArrayHasKey('links', $array); - $this->assertCount(1, $array['links']); - $this->assertArrayHasKey('foo', $array['links']); - $this->assertIsString($array['links']['foo']); - $this->assertSame('https://jsonapi.org', $array['links']['foo']); + parent::assertArrayHasKey('links', $array); + parent::assertCount(1, $array['links']); + parent::assertArrayHasKey('foo', $array['links']); + parent::assertIsString($array['links']['foo']); + parent::assertSame('https://jsonapi.org', $array['links']['foo']); } - public function testAddLink_WithMeta() { - $document = new Document(); - $document->addLink('foo', 'https://jsonapi.org', $meta=['bar' => 'baz']); - - $array = $document->toArray(); - - $this->assertCount(1, $array['links']); - $this->assertIsArray($array['links']['foo']); - $this->assertCount(2, $array['links']['foo']); - $this->assertArrayHasKey('href', $array['links']['foo']); - $this->assertArrayHasKey('meta', $array['links']['foo']); - $this->assertSame('https://jsonapi.org', $array['links']['foo']['href']); - $this->assertCount(1, $array['links']['foo']['meta']); - $this->assertArrayHasKey('bar', $array['links']['foo']['meta']); - $this->assertSame('baz', $array['links']['foo']['meta']['bar']); + public function testAddLink_WithMeta(): void { + $this->document->addLink('foo', 'https://jsonapi.org', ['bar' => 'baz']); + + $array = $this->document->toArray(); + + parent::assertCount(1, $array['links']); + parent::assertIsArray($array['links']['foo']); + parent::assertCount(2, $array['links']['foo']); + parent::assertArrayHasKey('href', $array['links']['foo']); + parent::assertArrayHasKey('meta', $array['links']['foo']); + parent::assertSame('https://jsonapi.org', $array['links']['foo']['href']); + parent::assertCount(1, $array['links']['foo']['meta']); + parent::assertArrayHasKey('bar', $array['links']['foo']['meta']); + parent::assertSame('baz', $array['links']['foo']['meta']['bar']); } - public function testAddLink_BlocksJsonapiLevel() { - $document = new Document(); - + public function testAddLink_BlocksJsonapiLevel(): void { $this->expectException(InputException::class); $this->expectExceptionMessage('level "jsonapi" can not be used for links'); - $document->addLink('foo', 'https://jsonapi.org', $meta=[], $level=DocumentLevelEnum::Jsonapi); + $this->document->addLink('foo', 'https://jsonapi.org', level: DocumentLevelEnum::Jsonapi); } - public function testAddLink_BlocksResourceLevel() { - $document = new Document(); - + public function testAddLink_BlocksResourceLevel(): void { $this->expectException(InputException::class); $this->expectExceptionMessage('level "resource" can only be set on a ResourceDocument'); - $document->addLink('foo', 'https://jsonapi.org', $meta=[], $level=DocumentLevelEnum::Resource); + $this->document->addLink('foo', 'https://jsonapi.org', level: DocumentLevelEnum::Resource); } - public function testSetSelfLink_HappyPath() { - $document = new Document(); + public function testSetSelfLink_HappyPath(): void { + $array = $this->document->toArray(); + parent::assertArrayNotHasKey('links', $array); - $array = $document->toArray(); - $this->assertArrayNotHasKey('links', $array); + $this->document->setSelfLink('https://jsonapi.org/foo'); - $document->setSelfLink('https://jsonapi.org/foo'); - - $array = $document->toArray(); - $this->assertArrayHasKey('links', $array); - $this->assertCount(1, $array['links']); - $this->assertArrayHasKey('self', $array['links']); - $this->assertSame('https://jsonapi.org/foo', $array['links']['self']); + $array = $this->document->toArray(); + parent::assertArrayHasKey('links', $array); + parent::assertCount(1, $array['links']); + parent::assertArrayHasKey('self', $array['links']); + parent::assertSame('https://jsonapi.org/foo', $array['links']['self']); } - public function testSetDescribedByLink_HappyPath() { - $document = new Document(); - $document->setDescribedByLink('https://jsonapi.org/format', ['version' => '1.1']); - - $array = $document->toArray(); - - $this->assertCount(1, $array['links']); - $this->assertIsArray($array['links']['describedby']); - $this->assertCount(2, $array['links']['describedby']); - $this->assertArrayHasKey('href', $array['links']['describedby']); - $this->assertArrayHasKey('meta', $array['links']['describedby']); - $this->assertSame('https://jsonapi.org/format', $array['links']['describedby']['href']); - $this->assertCount(1, $array['links']['describedby']['meta']); - $this->assertArrayHasKey('version', $array['links']['describedby']['meta']); - $this->assertSame('1.1', $array['links']['describedby']['meta']['version']); + public function testSetDescribedByLink_HappyPath(): void { + $this->document->setDescribedByLink('https://jsonapi.org/format', ['version' => '1.1']); + + $array = $this->document->toArray(); + + parent::assertCount(1, $array['links']); + parent::assertIsArray($array['links']['describedby']); + parent::assertCount(2, $array['links']['describedby']); + parent::assertArrayHasKey('href', $array['links']['describedby']); + parent::assertArrayHasKey('meta', $array['links']['describedby']); + parent::assertSame('https://jsonapi.org/format', $array['links']['describedby']['href']); + parent::assertCount(1, $array['links']['describedby']['meta']); + parent::assertArrayHasKey('version', $array['links']['describedby']['meta']); + parent::assertSame('1.1', $array['links']['describedby']['meta']['version']); } - public function testSetDescribedByLink_WithMeta() { - $document = new Document(); - - $array = $document->toArray(); - $this->assertArrayNotHasKey('links', $array); + public function testSetDescribedByLink_WithMeta(): void { + $array = $this->document->toArray(); + parent::assertArrayNotHasKey('links', $array); - $document->setDescribedByLink('https://jsonapi.org/format'); + $this->document->setDescribedByLink('https://jsonapi.org/format'); - $array = $document->toArray(); - $this->assertArrayHasKey('links', $array); - $this->assertCount(1, $array['links']); - $this->assertArrayHasKey('describedby', $array['links']); - $this->assertSame('https://jsonapi.org/format', $array['links']['describedby']); + $array = $this->document->toArray(); + parent::assertArrayHasKey('links', $array); + parent::assertCount(1, $array['links']); + parent::assertArrayHasKey('describedby', $array['links']); + parent::assertSame('https://jsonapi.org/format', $array['links']['describedby']); } - public function testAddMeta_HappyPath() { - $document = new Document(); + public function testAddMeta_HappyPath(): void { + $array = $this->document->toArray(); + parent::assertArrayNotHasKey('meta', $array); - $array = $document->toArray(); - $this->assertArrayNotHasKey('meta', $array); + $this->document->addMeta('foo', 'bar'); - $document->addMeta('foo', 'bar'); + $array = $this->document->toArray(); - $array = $document->toArray(); - - $this->assertArrayHasKey('meta', $array); - $this->assertCount(1, $array['meta']); - $this->assertArrayHasKey('foo', $array['meta']); - $this->assertIsString($array['meta']['foo']); - $this->assertSame('bar', $array['meta']['foo']); + parent::assertArrayHasKey('meta', $array); + parent::assertCount(1, $array['meta']); + parent::assertArrayHasKey('foo', $array['meta']); + parent::assertIsString($array['meta']['foo']); + parent::assertSame('bar', $array['meta']['foo']); } - public function testAddMeta_AtJsonapiLevel() { - $document = new Document(); - - $array = $document->toArray(); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayNotHasKey('meta', $array['jsonapi']); + public function testAddMeta_AtJsonapiLevel(): void { + $array = $this->document->toArray(); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayNotHasKey('meta', $array['jsonapi']); - $document->addMeta('foo', 'bar', $level=DocumentLevelEnum::Jsonapi); + $this->document->addMeta('foo', 'bar', DocumentLevelEnum::Jsonapi); - $array = $document->toArray(); + $array = $this->document->toArray(); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayHasKey('meta', $array['jsonapi']); - $this->assertCount(1, $array['jsonapi']['meta']); - $this->assertArrayHasKey('foo', $array['jsonapi']['meta']); - $this->assertIsString($array['jsonapi']['meta']['foo']); - $this->assertSame('bar', $array['jsonapi']['meta']['foo']); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayHasKey('meta', $array['jsonapi']); + parent::assertCount(1, $array['jsonapi']['meta']); + parent::assertArrayHasKey('foo', $array['jsonapi']['meta']); + parent::assertIsString($array['jsonapi']['meta']['foo']); + parent::assertSame('bar', $array['jsonapi']['meta']['foo']); } - public function testAddMeta_BlocksResourceLevel() { - $document = new Document(); - + public function testAddMeta_BlocksResourceLevel(): void { $this->expectException(InputException::class); $this->expectExceptionMessage('level "resource" can only be set on a ResourceDocument'); - $document->addMeta('foo', 'bar', $level=DocumentLevelEnum::Resource); + $this->document->addMeta('foo', 'bar', DocumentLevelEnum::Resource); } - public function testAddLinkObject_HappyPath() { + public function testAddLinkObject_HappyPath(): void { $linkObject = new LinkObject('https://jsonapi.org'); - $document = new Document(); - $document->addLinkObject($key='foo', $linkObject); + $this->document->addLinkObject('foo', $linkObject); - $array = $document->toArray(); + $array = $this->document->toArray(); - $this->assertCount(2, $array); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayHasKey('links', $array); - $this->assertArrayHasKey('foo', $array['links']); - $this->assertArrayHasKey('href', $array['links']['foo']); - $this->assertSame('https://jsonapi.org', $array['links']['foo']['href']); + parent::assertCount(2, $array); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayHasKey('links', $array); + parent::assertArrayHasKey('foo', $array['links']); + parent::assertArrayHasKey('href', $array['links']['foo']); + parent::assertSame('https://jsonapi.org', $array['links']['foo']['href']); } /** * @group Extensions */ - public function testApplyExtension_HappyPath() { - $extension = new TestExtension(); - $extension->setNamespace('test'); - $extension->setOfficialLink('https://jsonapi.org/extension'); - - $document = new Document(); - $document->applyExtension($extension); - $document->addExtensionMember($extension, 'foo', 'bar'); - $document->setSelfLink('https://jsonapi.org/foo'); - - $array = $document->toArray(); - - $this->assertCount(3, $array); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertCount(2, $array['jsonapi']); - $this->assertSame('1.1', $array['jsonapi']['version']); - $this->assertArrayHasKey('ext', $array['jsonapi']); - $this->assertCount(1, $array['jsonapi']['ext']); - $this->assertArrayHasKey(0, $array['jsonapi']['ext']); - $this->assertSame('https://jsonapi.org/extension', $array['jsonapi']['ext'][0]); - $this->assertArrayHasKey('test:foo', $array); - $this->assertSame('bar', $array['test:foo']); - $this->assertArrayHasKey('links', $array); - $this->assertCount(1, $array['links']); - $this->assertArrayHasKey('self', $array['links']); - $this->assertCount(2, $array['links']['self']); - $this->assertArrayHasKey('href', $array['links']['self']); - $this->assertArrayHasKey('type', $array['links']['self']); - $this->assertSame('https://jsonapi.org/foo', $array['links']['self']['href']); - $this->assertSame('application/vnd.api+json; ext="https://jsonapi.org/extension"', $array['links']['self']['type']); + public function testApplyExtension_HappyPath(): void { + $extension = parent::createConfiguredStub(ExtensionInterface::class, [ + 'getNamespace' => 'test', + 'getOfficialLink' => 'https://jsonapi.org/extension', + ]); + + $this->document->applyExtension($extension); + $this->document->addExtensionMember($extension, 'foo', 'bar'); + $this->document->setSelfLink('https://jsonapi.org/foo'); + + $array = $this->document->toArray(); + + parent::assertCount(3, $array); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertCount(2, $array['jsonapi']); + parent::assertSame('1.1', $array['jsonapi']['version']); + parent::assertArrayHasKey('ext', $array['jsonapi']); + parent::assertCount(1, $array['jsonapi']['ext']); + parent::assertArrayHasKey(0, $array['jsonapi']['ext']); + parent::assertSame('https://jsonapi.org/extension', $array['jsonapi']['ext'][0]); + parent::assertArrayHasKey('test:foo', $array); + parent::assertSame('bar', $array['test:foo']); + parent::assertArrayHasKey('links', $array); + parent::assertCount(1, $array['links']); + parent::assertArrayHasKey('self', $array['links']); + parent::assertCount(2, $array['links']['self']); + parent::assertArrayHasKey('href', $array['links']['self']); + parent::assertArrayHasKey('type', $array['links']['self']); + parent::assertSame('https://jsonapi.org/foo', $array['links']['self']['href']); + parent::assertSame('application/vnd.api+json; ext="https://jsonapi.org/extension"', $array['links']['self']['type']); } /** * @group Extensions */ - public function testApplyExtension_InvalidNamespace() { - $document = new Document(); - $extension = new TestExtension(); - $extension->setNamespace('foo-bar'); + public function testApplyExtension_InvalidNamespace(): void { + $extension = parent::createConfiguredStub(ExtensionInterface::class, ['getNamespace' => 'foo-bar']); $this->expectException(Exception::class); $this->expectExceptionMessage('invalid namespace "foo-bar"'); - $document->applyExtension($extension); + $this->document->applyExtension($extension); } /** * @group Extensions */ - public function testApplyExtension_ConflictingNamespace() { - $document = new Document(); + public function testApplyExtension_ConflictingNamespace(): void { + $extension1 = parent::createConfiguredStub(ExtensionInterface::class, ['getNamespace' => 'foo']); + $this->document->applyExtension($extension1); - $extension1 = new TestExtension(); - $extension1->setNamespace('foo'); - $document->applyExtension($extension1); + $extension2 = parent::createConfiguredStub(ExtensionInterface::class, ['getNamespace' => 'bar']); + $this->document->applyExtension($extension2); - $extension2 = new TestExtension(); - $extension2->setNamespace('bar'); - $document->applyExtension($extension2); - - $extension3 = new TestExtension(); - $extension3->setNamespace('foo'); + $extension3 = parent::createConfiguredStub(ExtensionInterface::class, ['getNamespace' => 'foo']); $this->expectException(DuplicateException::class); $this->expectExceptionMessage('an extension with namespace "foo" is already applied'); - $document->applyExtension($extension3); + $this->document->applyExtension($extension3); } /** * @group Profiles */ - public function testApplyProfile_HappyPath() { - $profile = new TestProfile(); - $profile->setOfficialLink('https://jsonapi.org/profile'); - - $document = new Document(); - $document->applyProfile($profile); - $document->setSelfLink('https://jsonapi.org/foo'); - - $array = $document->toArray(); - - $this->assertCount(2, $array); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertCount(2, $array['jsonapi']); - $this->assertSame('1.1', $array['jsonapi']['version']); - $this->assertArrayHasKey('profile', $array['jsonapi']); - $this->assertCount(1, $array['jsonapi']['profile']); - $this->assertArrayHasKey(0, $array['jsonapi']['profile']); - $this->assertSame('https://jsonapi.org/profile', $array['jsonapi']['profile'][0]); - $this->assertArrayHasKey('links', $array); - $this->assertCount(1, $array['links']); - $this->assertArrayHasKey('self', $array['links']); - $this->assertCount(2, $array['links']['self']); - $this->assertArrayHasKey('href', $array['links']['self']); - $this->assertArrayHasKey('type', $array['links']['self']); - $this->assertSame('https://jsonapi.org/foo', $array['links']['self']['href']); - $this->assertSame('application/vnd.api+json; profile="https://jsonapi.org/profile"', $array['links']['self']['type']); + public function testApplyProfile_HappyPath(): void { + $profile = parent::createConfiguredStub(ProfileInterface::class, ['getOfficialLink' => 'https://jsonapi.org/profile']); + + $this->document->applyProfile($profile); + $this->document->setSelfLink('https://jsonapi.org/foo'); + + $array = $this->document->toArray(); + + parent::assertCount(2, $array); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertCount(2, $array['jsonapi']); + parent::assertSame('1.1', $array['jsonapi']['version']); + parent::assertArrayHasKey('profile', $array['jsonapi']); + parent::assertCount(1, $array['jsonapi']['profile']); + parent::assertArrayHasKey(0, $array['jsonapi']['profile']); + parent::assertSame('https://jsonapi.org/profile', $array['jsonapi']['profile'][0]); + parent::assertArrayHasKey('links', $array); + parent::assertCount(1, $array['links']); + parent::assertArrayHasKey('self', $array['links']); + parent::assertCount(2, $array['links']['self']); + parent::assertArrayHasKey('href', $array['links']['self']); + parent::assertArrayHasKey('type', $array['links']['self']); + parent::assertSame('https://jsonapi.org/foo', $array['links']['self']['href']); + parent::assertSame('application/vnd.api+json; profile="https://jsonapi.org/profile"', $array['links']['self']['type']); } - public function testToJson_HappyPath() { - $document = new Document(); - - $this->assertSame('{"jsonapi":{"version":"1.1"}}', $document->toJson()); + public function testToJson_HappyPath(): void { + parent::assertSame('{"jsonapi":{"version":"1.1"}}', $this->document->toJson()); } - public function testToJson_CustomArray() { - $document = new Document(); - + public function testToJson_CustomArray(): void { $options = ['array' => ['foo' => 42]]; - $this->assertSame('{"foo":42}', $document->toJson($options)); + parent::assertSame('{"foo":42}', $this->document->toJson($options)); } - public function testToJson_PrettyPrint() { - $document = new Document(); - + public function testToJson_PrettyPrint(): void { $options = ['prettyPrint' => true]; $expectedJson = '{'.PHP_EOL.' "jsonapi": {'.PHP_EOL.' "version": "1.1"'.PHP_EOL.' }'.PHP_EOL.'}'; - $this->assertSame($expectedJson, $document->toJson($options)); + parent::assertSame($expectedJson, $this->document->toJson($options)); } - public function testToJson_JsonEncodeOptions() { - $document = new Document(); - + public function testToJson_JsonEncodeOptions(): void { $options = ['encodeOptions' => JSON_FORCE_OBJECT, 'array' => ['foo' => [4,2]]]; - $this->assertSame('{"foo":{"0":4,"1":2}}', $document->toJson($options)); + parent::assertSame('{"foo":{"0":4,"1":2}}', $this->document->toJson($options)); } - public function testToJson_JsonpCallback() { - $document = new Document(); - $document->addMeta('foo', 'bar'); + public function testToJson_JsonpCallback(): void { + $this->document->addMeta('foo', 'bar'); $options = ['jsonpCallback' => 'baz']; - $json = $document->toJson($options); - $this->assertSame('baz({"jsonapi":{"version":"1.1"},"meta":{"foo":"bar"}})', $json); + $json = $this->document->toJson($options); + parent::assertSame('baz({"jsonapi":{"version":"1.1"},"meta":{"foo":"bar"}})', $json); } - public function testToJson_InvalidUtf8() { - $document = new Document(); - + public function testToJson_InvalidUtf8(): void { $options = ['array' => ['foo' => "\xB1\x31"]]; - $this->expectException(Exception::class); - $this->expectExceptionMessage('failed to generate json: Malformed UTF-8 characters, possibly incorrectly encoded'); + $this->expectException(\JsonException::class); + $this->expectExceptionMessage('Malformed UTF-8 characters, possibly incorrectly encoded'); + $this->expectExceptionCode(JSON_ERROR_UTF8); - $document->toJson($options); + $this->document->toJson($options); } - public function testJsonSerialize_HappyPath() { - $document = new Document(); - $document->addMeta('foo', 'bar'); + public function testJsonSerialize_HappyPath(): void { + $this->document->addMeta('foo', 'bar'); - $json = $document->toJson(); + $json = $this->document->toJson(); - $this->assertSame($json, json_encode($document)); + parent::assertSame($json, json_encode($this->document, flags: JSON_THROW_ON_ERROR)); } } diff --git a/tests/ErrorsDocumentTest.php b/tests/ErrorsDocumentTest.php index 10e694f5..c7952517 100644 --- a/tests/ErrorsDocumentTest.php +++ b/tests/ErrorsDocumentTest.php @@ -10,53 +10,53 @@ use alsvanzelf\jsonapi\objects\ErrorObject; class ErrorsDocumentTest extends TestCase { - public function testFromException_HappyPath() { + public function testFromException_HappyPath(): void { $document = ErrorsDocument::fromException(new \Exception('foo', 42)); $array = $document->toArray(); - $this->assertArrayHasKey('errors', $array); - $this->assertCount(1, $array['errors']); - $this->assertArrayHasKey('code', $array['errors'][0]); - $this->assertArrayHasKey('meta', $array['errors'][0]); - $this->assertArrayHasKey('type', $array['errors'][0]['meta']); - $this->assertArrayHasKey('message', $array['errors'][0]['meta']); - $this->assertArrayHasKey('code', $array['errors'][0]['meta']); - $this->assertArrayHasKey('trace', $array['errors'][0]['meta']); - $this->assertSame('Exception', $array['errors'][0]['code']); - $this->assertSame('Exception', $array['errors'][0]['meta']['type']); - $this->assertSame('foo', $array['errors'][0]['meta']['message']); - $this->assertSame(42, $array['errors'][0]['meta']['code']); - $this->assertArrayHasKey('function', $array['errors'][0]['meta']['trace'][0]); - $this->assertArrayHasKey('class', $array['errors'][0]['meta']['trace'][0]); - $this->assertSame(__FUNCTION__, $array['errors'][0]['meta']['trace'][0]['function']); - $this->assertSame(self::class, $array['errors'][0]['meta']['trace'][0]['class']); + parent::assertArrayHasKey('errors', $array); + parent::assertCount(1, $array['errors']); + parent::assertArrayHasKey('code', $array['errors'][0]); + parent::assertArrayHasKey('meta', $array['errors'][0]); + parent::assertArrayHasKey('type', $array['errors'][0]['meta']); + parent::assertArrayHasKey('message', $array['errors'][0]['meta']); + parent::assertArrayHasKey('code', $array['errors'][0]['meta']); + parent::assertArrayHasKey('trace', $array['errors'][0]['meta']); + parent::assertSame('Exception', $array['errors'][0]['code']); + parent::assertSame('Exception', $array['errors'][0]['meta']['type']); + parent::assertSame('foo', $array['errors'][0]['meta']['message']); + parent::assertSame(42, $array['errors'][0]['meta']['code']); + parent::assertArrayHasKey('function', $array['errors'][0]['meta']['trace'][0]); + parent::assertArrayHasKey('class', $array['errors'][0]['meta']['trace'][0]); + parent::assertSame(__FUNCTION__, $array['errors'][0]['meta']['trace'][0]['function']); + parent::assertSame(self::class, $array['errors'][0]['meta']['trace'][0]['class']); } - public function testFromException_AllowsThrowable() { + public function testFromException_AllowsThrowable(): void { $document = ErrorsDocument::fromException(new \Error('foo', 42)); $array = $document->toArray(); - $this->assertArrayHasKey('errors', $array); - $this->assertCount(1, $array['errors']); - $this->assertArrayHasKey('code', $array['errors'][0]); - $this->assertArrayHasKey('meta', $array['errors'][0]); - $this->assertArrayHasKey('type', $array['errors'][0]['meta']); - $this->assertArrayHasKey('message', $array['errors'][0]['meta']); - $this->assertArrayHasKey('code', $array['errors'][0]['meta']); - $this->assertArrayHasKey('trace', $array['errors'][0]['meta']); - $this->assertSame('Error', $array['errors'][0]['code']); - $this->assertSame('Error', $array['errors'][0]['meta']['type']); - $this->assertSame('foo', $array['errors'][0]['meta']['message']); - $this->assertSame(42, $array['errors'][0]['meta']['code']); - $this->assertArrayHasKey('function', $array['errors'][0]['meta']['trace'][0]); - $this->assertArrayHasKey('class', $array['errors'][0]['meta']['trace'][0]); - $this->assertSame(__FUNCTION__, $array['errors'][0]['meta']['trace'][0]['function']); - $this->assertSame(self::class, $array['errors'][0]['meta']['trace'][0]['class']); + parent::assertArrayHasKey('errors', $array); + parent::assertCount(1, $array['errors']); + parent::assertArrayHasKey('code', $array['errors'][0]); + parent::assertArrayHasKey('meta', $array['errors'][0]); + parent::assertArrayHasKey('type', $array['errors'][0]['meta']); + parent::assertArrayHasKey('message', $array['errors'][0]['meta']); + parent::assertArrayHasKey('code', $array['errors'][0]['meta']); + parent::assertArrayHasKey('trace', $array['errors'][0]['meta']); + parent::assertSame('Error', $array['errors'][0]['code']); + parent::assertSame('Error', $array['errors'][0]['meta']['type']); + parent::assertSame('foo', $array['errors'][0]['meta']['message']); + parent::assertSame(42, $array['errors'][0]['meta']['code']); + parent::assertArrayHasKey('function', $array['errors'][0]['meta']['trace'][0]); + parent::assertArrayHasKey('class', $array['errors'][0]['meta']['trace'][0]); + parent::assertSame(__FUNCTION__, $array['errors'][0]['meta']['trace'][0]['function']); + parent::assertSame(self::class, $array['errors'][0]['meta']['trace'][0]['class']); } - public function testAddException_WithPrevious() { + public function testAddException_WithPrevious(): void { $exception = new \Exception('foo', 1, new \Exception('bar', 2)); $document = new ErrorsDocument(); @@ -64,17 +64,17 @@ public function testAddException_WithPrevious() { $array = $document->toArray(); - $this->assertArrayHasKey('errors', $array); - $this->assertCount(2, $array['errors']); - $this->assertArrayHasKey('meta', $array['errors'][0]); - $this->assertArrayHasKey('meta', $array['errors'][1]); - $this->assertArrayHasKey('message', $array['errors'][0]['meta']); - $this->assertArrayHasKey('message', $array['errors'][1]['meta']); - $this->assertSame('foo', $array['errors'][0]['meta']['message']); - $this->assertSame('bar', $array['errors'][1]['meta']['message']); + parent::assertArrayHasKey('errors', $array); + parent::assertCount(2, $array['errors']); + parent::assertArrayHasKey('meta', $array['errors'][0]); + parent::assertArrayHasKey('meta', $array['errors'][1]); + parent::assertArrayHasKey('message', $array['errors'][0]['meta']); + parent::assertArrayHasKey('message', $array['errors'][1]['meta']); + parent::assertSame('foo', $array['errors'][0]['meta']['message']); + parent::assertSame('bar', $array['errors'][1]['meta']['message']); } - public function testAddException_SkipPrevious() { + public function testAddException_SkipPrevious(): void { $exception = new \Exception('foo', 1, new \Exception('bar', 2)); $options = ['includeExceptionPrevious' => false]; @@ -83,31 +83,31 @@ public function testAddException_SkipPrevious() { $array = $document->toArray(); - $this->assertArrayHasKey('errors', $array); - $this->assertCount(1, $array['errors']); - $this->assertArrayHasKey('meta', $array['errors'][0]); - $this->assertArrayHasKey('message', $array['errors'][0]['meta']); - $this->assertSame('foo', $array['errors'][0]['meta']['message']); + parent::assertArrayHasKey('errors', $array); + parent::assertCount(1, $array['errors']); + parent::assertArrayHasKey('meta', $array['errors'][0]); + parent::assertArrayHasKey('message', $array['errors'][0]['meta']); + parent::assertSame('foo', $array['errors'][0]['meta']['message']); } - public function testToArray_EmptyErrorObject() { + public function testToArray_EmptyErrorObject(): void { $document = new ErrorsDocument(); $document->addErrorObject(new ErrorObject('foo')); $document->addErrorObject(new ErrorObject()); $array = $document->toArray(); - $this->assertArrayHasKey('errors', $array); - $this->assertCount(1, $array['errors']); - $this->assertArrayHasKey('code', $array['errors'][0]); - $this->assertSame('foo', $array['errors'][0]['code']); + parent::assertArrayHasKey('errors', $array); + parent::assertCount(1, $array['errors']); + parent::assertArrayHasKey('code', $array['errors'][0]); + parent::assertSame('foo', $array['errors'][0]['code']); } /** * @param non-empty-array $allErrorCodes */ #[DataProvider('dataProviderDetermineHttpStatusCode_HappyPath')] - public function testDetermineHttpStatusCode_HappyPath(int $expectedAdvisedErrorCode, array $allErrorCodes) { + public function testDetermineHttpStatusCode_HappyPath(int $expectedAdvisedErrorCode, array $allErrorCodes): void { $document = new ErrorsDocument(); $method = new \ReflectionMethod($document, 'determineHttpStatusCode'); @@ -117,7 +117,7 @@ public function testDetermineHttpStatusCode_HappyPath(int $expectedAdvisedErrorC $advisedErrorCode = $method->invoke($document, $errorCode); } - $this->assertSame($expectedAdvisedErrorCode, $advisedErrorCode); + parent::assertSame($expectedAdvisedErrorCode, $advisedErrorCode); } public static function dataProviderDetermineHttpStatusCode_HappyPath() { @@ -135,10 +135,10 @@ public static function dataProviderDetermineHttpStatusCode_HappyPath() { ]; } - public function testDetermineHttpStatusCode_Override() { + public function testDetermineHttpStatusCode_Override(): void { $document = new ErrorsDocument(); - $this->assertSame(200, $document->getHttpStatusCode()); + parent::assertSame(200, $document->getHttpStatusCode()); $allErrorCodes = [422, 404, 501, 503]; foreach ($allErrorCodes as $errorCode) { @@ -148,10 +148,10 @@ public function testDetermineHttpStatusCode_Override() { $document->addErrorObject($errorObject); } - $this->assertSame(500, $document->getHttpStatusCode()); + parent::assertSame(500, $document->getHttpStatusCode()); $document->setHttpStatusCode(422); - $this->assertSame(422, $document->getHttpStatusCode()); + parent::assertSame(422, $document->getHttpStatusCode()); } } diff --git a/tests/ExampleOutputTest.php b/tests/ExampleOutputTest.php index 20f641a4..75a699f0 100644 --- a/tests/ExampleOutputTest.php +++ b/tests/ExampleOutputTest.php @@ -16,8 +16,8 @@ class ExampleOutputTest extends TestCase { ]; #[DataProvider('dataProviderTestOutput')] - public function testOutput($generator, $expectedJson, array $options=[], $testName=null) { - $options = array_merge(self::$defaults, $options); + public function testOutput($generator, $expectedJson, array $options=[], $testName=null): void { + $options = [...self::$defaults, ...$options]; $document = $generator::createJsonapiDocument(); $actualJson = $document->toJson($options); @@ -29,10 +29,10 @@ public function testOutput($generator, $expectedJson, array $options=[], $testNa $actualJsonPath = __DIR__.'/example_output/'.$testName.'/'.$testName.'.json'; if ($expectedJson === null && file_exists($actualJsonPath) === false) { file_put_contents($actualJsonPath, $actualJson); - $this->markTestSkipped('no stored json to test against, try again'); + parent::markTestSkipped('no stored json to test against, try again'); } - $this->assertSame($expectedJson, $actualJson); + parent::assertSame($expectedJson, $actualJson); } public static function dataProviderTestOutput() { @@ -53,7 +53,7 @@ public static function dataProviderTestOutput() { $expectedJson = file_get_contents($directory.'/'.$testName.'.json'); } if (file_exists($directory.'/options.txt')) { - $options = json_decode(file_get_contents($directory.'/options.txt'), true); + $options = json_decode(file_get_contents($directory.'/options.txt'), associative: true, flags: JSON_THROW_ON_ERROR); } $testCases[$testName] = [$generator, $expectedJson, $options, $testName]; diff --git a/tests/MetaDocumentTest.php b/tests/MetaDocumentTest.php index cfb6d18a..1db500d8 100644 --- a/tests/MetaDocumentTest.php +++ b/tests/MetaDocumentTest.php @@ -8,29 +8,29 @@ use PHPUnit\Framework\TestCase; class MetaDocumentTest extends TestCase { - public function testConstructor_NoMeta() { + public function testConstructor_NoMeta(): void { $document = new MetaDocument(); $array = $document->toArray(); - $this->assertArrayHasKey('meta', $array); + parent::assertArrayHasKey('meta', $array); // verify meta is an object, not an array $json = $document->toJson(); - $this->assertSame('{"jsonapi":{"version":"1.1"},"meta":{}}', $json); + parent::assertSame('{"jsonapi":{"version":"1.1"},"meta":{}}', $json); } - public function testFromArray_HappyPath() { + public function testFromArray_HappyPath(): void { $document = MetaDocument::fromArray(['foo' => 'bar']); $array = $document->toArray(); - $this->assertArrayHasKey('meta', $array); - $this->assertCount(1, $array['meta']); - $this->assertArrayHasKey('foo', $array['meta']); - $this->assertSame('bar', $array['meta']['foo']); + parent::assertArrayHasKey('meta', $array); + parent::assertCount(1, $array['meta']); + parent::assertArrayHasKey('foo', $array['meta']); + parent::assertSame('bar', $array['meta']['foo']); } - public function testFromObject_HappyPath() { + public function testFromObject_HappyPath(): void { $object = new \stdClass(); $object->foo = 'bar'; @@ -38,37 +38,37 @@ public function testFromObject_HappyPath() { $array = $document->toArray(); - $this->assertArrayHasKey('meta', $array); - $this->assertCount(1, $array['meta']); - $this->assertArrayHasKey('foo', $array['meta']); - $this->assertSame('bar', $array['meta']['foo']); + parent::assertArrayHasKey('meta', $array); + parent::assertCount(1, $array['meta']); + parent::assertArrayHasKey('foo', $array['meta']); + parent::assertSame('bar', $array['meta']['foo']); } - public function testAddMeta_HappyPath() { + public function testAddMeta_HappyPath(): void { $document = new MetaDocument(); $document->addMeta('foo', 'bar'); $array = $document->toArray(); - $this->assertArrayHasKey('meta', $array); - $this->assertCount(1, $array['meta']); - $this->assertArrayHasKey('foo', $array['meta']); - $this->assertSame('bar', $array['meta']['foo']); + parent::assertArrayHasKey('meta', $array); + parent::assertCount(1, $array['meta']); + parent::assertArrayHasKey('foo', $array['meta']); + parent::assertSame('bar', $array['meta']['foo']); } - public function testAdd_HappyPath() { + public function testAdd_HappyPath(): void { $document = new MetaDocument(); $document->add('foo', 'bar'); $array = $document->toArray(); - $this->assertArrayHasKey('meta', $array); - $this->assertCount(1, $array['meta']); - $this->assertArrayHasKey('foo', $array['meta']); - $this->assertSame('bar', $array['meta']['foo']); + parent::assertArrayHasKey('meta', $array); + parent::assertCount(1, $array['meta']); + parent::assertArrayHasKey('foo', $array['meta']); + parent::assertSame('bar', $array['meta']['foo']); - $this->assertCount(2, $array); - $this->assertArrayNotHasKey('data', $array); - $this->assertArrayHasKey('jsonapi', $array); + parent::assertCount(2, $array); + parent::assertArrayNotHasKey('data', $array); + parent::assertArrayHasKey('jsonapi', $array); } } diff --git a/tests/ResourceDocumentTest.php b/tests/ResourceDocumentTest.php index 01da41d6..144d574c 100644 --- a/tests/ResourceDocumentTest.php +++ b/tests/ResourceDocumentTest.php @@ -8,6 +8,7 @@ use alsvanzelf\jsonapi\enums\DocumentLevelEnum; use alsvanzelf\jsonapi\exceptions\Exception; use alsvanzelf\jsonapi\exceptions\InputException; +use alsvanzelf\jsonapi\interfaces\ExtensionInterface; use alsvanzelf\jsonapi\objects\AttributesObject; use alsvanzelf\jsonapi\objects\RelationshipObject; use alsvanzelf\jsonapi\objects\RelationshipsObject; @@ -16,16 +17,16 @@ use PHPUnit\Framework\TestCase; class ResourceDocumentTest extends TestCase { - public function testConstructor_NoResource() { + public function testConstructor_NoResource(): void { $document = new ResourceDocument(); $array = $document->toArray(); - $this->assertArrayHasKey('data', $array); - $this->assertNull($array['data']); + parent::assertArrayHasKey('data', $array); + parent::assertNull($array['data']); } - public function testFromObject_WithAttributesObject() { + public function testFromObject_WithAttributesObject(): void { $attributesObject = new AttributesObject(); $attributesObject->add('foo', 'bar'); @@ -33,25 +34,25 @@ public function testFromObject_WithAttributesObject() { $array = $document->toArray(); - $this->assertArrayHasKey('data', $array); - $this->assertArrayHasKey('attributes', $array['data']); - $this->assertArrayHasKey('foo', $array['data']['attributes']); - $this->assertSame('bar', $array['data']['attributes']['foo']); + parent::assertArrayHasKey('data', $array); + parent::assertArrayHasKey('attributes', $array['data']); + parent::assertArrayHasKey('foo', $array['data']['attributes']); + parent::assertSame('bar', $array['data']['attributes']['foo']); } - public function testAdd_HappyPath() { + public function testAdd_HappyPath(): void { $document = new ResourceDocument('user', 42); $document->add('foo', 'bar'); $array = $document->toArray(); - $this->assertArrayHasKey('data', $array); - $this->assertArrayHasKey('attributes', $array['data']); - $this->assertArrayHasKey('foo', $array['data']['attributes']); - $this->assertSame('bar', $array['data']['attributes']['foo']); + parent::assertArrayHasKey('data', $array); + parent::assertArrayHasKey('attributes', $array['data']); + parent::assertArrayHasKey('foo', $array['data']['attributes']); + parent::assertSame('bar', $array['data']['attributes']['foo']); } - public function testAdd_IdentifierOnlyObject() { + public function testAdd_IdentifierOnlyObject(): void { $document = new ResourceDocument(); $document->setPrimaryResource(new ResourceIdentifierObject('user', 42)); @@ -60,7 +61,20 @@ public function testAdd_IdentifierOnlyObject() { $document->add('foo', 'bar'); } - public function testAddRelationship_WithIncluded() { + /** + * @group Extensions + */ + public function testAdd_BlocksExtensionMembersViaRegularAdd(): void { + $document = new ResourceDocument(); + $document->applyExtension(parent::createConfiguredStub(ExtensionInterface::class, ['getNamespace' => 'test'])); + + $this->expectException(InputException::class); + $this->expectExceptionMessage('invalid member name "test:foo"'); + + $document->add('test:foo', 'bar'); + } + + public function testAddRelationship_WithIncluded(): void { $resourceObject = new ResourceObject('user', 42); $resourceObject->add('foo', 'bar'); @@ -69,85 +83,85 @@ public function testAddRelationship_WithIncluded() { $array = $document->toArray(); - $this->assertArrayHasKey('included', $array); + parent::assertArrayHasKey('included', $array); } - public function testAddRelationship_DoNotIncludeContainedResources() { + public function testAddRelationship_DoNotIncludeContainedResources(): void { $resourceObject = new ResourceObject('user', 42); $resourceObject->add('foo', 'bar'); $options = ['includeContainedResources' => false]; $document = new ResourceDocument('test', 1); - $document->addRelationship('foo', $resourceObject, $links=[], $meta=[], $options); + $document->addRelationship('foo', $resourceObject, options: $options); $array = $document->toArray(); - $this->assertArrayNotHasKey('included', $array); + parent::assertArrayNotHasKey('included', $array); } - public function testAddMeta_HappyPath() { + public function testAddMeta_HappyPath(): void { $document = new ResourceDocument(); - $document->addMeta('foo', 'root', $level=DocumentLevelEnum::Root); - $document->addMeta('bar', 'resource', $level=DocumentLevelEnum::Resource); - $document->addMeta('baz', 'jsonapi', $level=DocumentLevelEnum::Jsonapi); + $document->addMeta('foo', 'root', DocumentLevelEnum::Root); + $document->addMeta('bar', 'resource', DocumentLevelEnum::Resource); + $document->addMeta('baz', 'jsonapi', DocumentLevelEnum::Jsonapi); $array = $document->toArray(); - $this->assertArrayHasKey('meta', $array); - $this->assertArrayHasKey('data', $array); - $this->assertArrayHasKey('meta', $array['data']); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayHasKey('meta', $array['jsonapi']); - $this->assertArrayHasKey('foo', $array['meta']); - $this->assertArrayHasKey('bar', $array['data']['meta']); - $this->assertArrayHasKey('baz', $array['jsonapi']['meta']); - $this->assertCount(1, $array['meta']); - $this->assertCount(1, $array['data']['meta']); - $this->assertCount(1, $array['jsonapi']['meta']); - $this->assertSame('root', $array['meta']['foo']); - $this->assertSame('resource', $array['data']['meta']['bar']); - $this->assertSame('jsonapi', $array['jsonapi']['meta']['baz']); + parent::assertArrayHasKey('meta', $array); + parent::assertArrayHasKey('data', $array); + parent::assertArrayHasKey('meta', $array['data']); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayHasKey('meta', $array['jsonapi']); + parent::assertArrayHasKey('foo', $array['meta']); + parent::assertArrayHasKey('bar', $array['data']['meta']); + parent::assertArrayHasKey('baz', $array['jsonapi']['meta']); + parent::assertCount(1, $array['meta']); + parent::assertCount(1, $array['data']['meta']); + parent::assertCount(1, $array['jsonapi']['meta']); + parent::assertSame('root', $array['meta']['foo']); + parent::assertSame('resource', $array['data']['meta']['bar']); + parent::assertSame('jsonapi', $array['jsonapi']['meta']['baz']); } - public function testAddMeta_RecreateJsonapiObject() { + public function testAddMeta_RecreateJsonapiObject(): void { $document = new ResourceDocument(); $array = $document->toArray(); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayNotHasKey('meta', $array['jsonapi']); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayNotHasKey('meta', $array['jsonapi']); $document->unsetJsonapiObject(); $array = $document->toArray(); - $this->assertArrayNotHasKey('jsonapi', $array); + parent::assertArrayNotHasKey('jsonapi', $array); - $document->addMeta('baz', 'jsonapi', $level=DocumentLevelEnum::Jsonapi); + $document->addMeta('baz', 'jsonapi', DocumentLevelEnum::Jsonapi); $array = $document->toArray(); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayHasKey('meta', $array['jsonapi']); - $this->assertCount(1, $array['jsonapi']['meta']); - $this->assertSame('jsonapi', $array['jsonapi']['meta']['baz']); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayHasKey('meta', $array['jsonapi']); + parent::assertCount(1, $array['jsonapi']['meta']); + parent::assertSame('jsonapi', $array['jsonapi']['meta']['baz']); } - public function testSetLocalId_HappyPath() { + public function testSetLocalId_HappyPath(): void { $document = new ResourceDocument(); $document->setType('user'); $document->setLocalId('42'); $array = $document->toArray(); - $this->assertArrayHasKey('data', $array); - $this->assertArrayHasKey('lid', $array['data']); - $this->assertArrayNotHasKey('id', $array['data']); - $this->assertSame('42', $array['data']['lid']); + parent::assertArrayHasKey('data', $array); + parent::assertArrayHasKey('lid', $array['data']); + parent::assertArrayNotHasKey('id', $array['data']); + parent::assertSame('42', $array['data']['lid']); } - public function testAddRelationshipObject_WithIncluded() { + public function testAddRelationshipObject_WithIncluded(): void { $resourceObject = new ResourceObject('user', 42); $resourceObject->add('foo', 'bar'); $relationshipObject = RelationshipObject::fromAnything($resourceObject); @@ -157,10 +171,10 @@ public function testAddRelationshipObject_WithIncluded() { $array = $document->toArray(); - $this->assertArrayHasKey('included', $array); + parent::assertArrayHasKey('included', $array); } - public function testAddRelationshipObject_DoNotIncludeContainedResources() { + public function testAddRelationshipObject_DoNotIncludeContainedResources(): void { $resourceObject = new ResourceObject('user', 42); $resourceObject->add('foo', 'bar'); $relationshipObject = RelationshipObject::fromAnything($resourceObject); @@ -172,10 +186,10 @@ public function testAddRelationshipObject_DoNotIncludeContainedResources() { $array = $document->toArray(); - $this->assertArrayNotHasKey('included', $array); + parent::assertArrayNotHasKey('included', $array); } - public function testSetRelationshipsObject_WithIncluded() { + public function testSetRelationshipsObject_WithIncluded(): void { $resourceObject = new ResourceObject('user', 42); $resourceObject->add('foo', 'bar'); $relationshipObject = RelationshipObject::fromAnything($resourceObject); @@ -188,10 +202,10 @@ public function testSetRelationshipsObject_WithIncluded() { $array = $document->toArray(); - $this->assertArrayHasKey('included', $array); + parent::assertArrayHasKey('included', $array); } - public function testSetRelationshipsObject_DoNotIncludeContainedResources() { + public function testSetRelationshipsObject_DoNotIncludeContainedResources(): void { $resourceObject = new ResourceObject('user', 42); $resourceObject->add('foo', 'bar'); $relationshipObject = RelationshipObject::fromAnything($resourceObject); @@ -206,24 +220,24 @@ public function testSetRelationshipsObject_DoNotIncludeContainedResources() { $array = $document->toArray(); - $this->assertArrayNotHasKey('included', $array); + parent::assertArrayNotHasKey('included', $array); } - public function testSetPrimaryResource_HappyPath() { + public function testSetPrimaryResource_HappyPath(): void { $document = new ResourceDocument(); $document->setPrimaryResource(new ResourceObject('user', 42)); $array = $document->toArray(); - $this->assertArrayHasKey('data', $array); - $this->assertArrayHasKey('type', $array['data']); - $this->assertArrayHasKey('id', $array['data']); - $this->assertSame('user', $array['data']['type']); - $this->assertSame('42', $array['data']['id']); - $this->assertArrayNotHasKey('attributes', $array['data']); + parent::assertArrayHasKey('data', $array); + parent::assertArrayHasKey('type', $array['data']); + parent::assertArrayHasKey('id', $array['data']); + parent::assertSame('user', $array['data']['type']); + parent::assertSame('42', $array['data']['id']); + parent::assertArrayNotHasKey('attributes', $array['data']); } - public function testSetPrimaryResource_WithIncluded() { + public function testSetPrimaryResource_WithIncluded(): void { $relatedResourceObject = new ResourceObject('user', 24); $relatedResourceObject->add('foo', 'bar'); @@ -235,10 +249,10 @@ public function testSetPrimaryResource_WithIncluded() { $array = $document->toArray(); - $this->assertArrayHasKey('included', $array); + parent::assertArrayHasKey('included', $array); } - public function testSetPrimaryResource_DoNotIncludeContainedResources() { + public function testSetPrimaryResource_DoNotIncludeContainedResources(): void { $relatedResourceObject = new ResourceObject('user', 24); $relatedResourceObject->add('foo', 'bar'); @@ -252,10 +266,10 @@ public function testSetPrimaryResource_DoNotIncludeContainedResources() { $array = $document->toArray(); - $this->assertArrayNotHasKey('included', $array); + parent::assertArrayNotHasKey('included', $array); } - public function testSetPrimaryResource_BlocksResourceDocument() { + public function testSetPrimaryResource_BlocksResourceDocument(): void { $document = new ResourceDocument(); $this->expectException(InputException::class); diff --git a/tests/SeparateProcessTest.php b/tests/SeparateProcessTest.php index 95f8290a..2dc68ce1 100644 --- a/tests/SeparateProcessTest.php +++ b/tests/SeparateProcessTest.php @@ -4,181 +4,182 @@ namespace alsvanzelf\jsonapiTests; +use alsvanzelf\jsonapi\Document; use alsvanzelf\jsonapi\enums\ContentTypeEnum; -use alsvanzelf\jsonapiTests\TestableNonAbstractDocument; -use alsvanzelf\jsonapiTests\extensions\TestExtension; -use alsvanzelf\jsonapiTests\profiles\TestProfile; +use alsvanzelf\jsonapi\interfaces\ExtensionInterface; +use alsvanzelf\jsonapi\interfaces\ProfileInterface; use PHPUnit\Framework\TestCase; /** * @group SeparateProcess */ class SeparateProcessTest extends TestCase { + private object $document; + + public function setUp(): void { + /** + * extending Document to make it non-abstract to test against it + * + * the abstract declaration is to make sure to create valid jsonapi output + * as it needs at least one of `data`, `meta` or `errors` + */ + $this->document = new class extends Document {}; + } + /** * @runInSeparateProcess */ - public function testSendResponse_HappyPath() { - $document = new TestableNonAbstractDocument(); - + public function testSendResponse_HappyPath(): void { ob_start(); - $document->sendResponse(); + $this->document->sendResponse(); $output = ob_get_clean(); - $this->assertSame('{"jsonapi":{"version":"1.1"}}', $output); + parent::assertSame('{"jsonapi":{"version":"1.1"}}', $output); } /** * @runInSeparateProcess */ - public function testSendResponse_NoContent() { - $document = new TestableNonAbstractDocument(); - $document->setHttpStatusCode(204); + public function testSendResponse_NoContent(): void { + $this->document->setHttpStatusCode(204); ob_start(); - $document->sendResponse(); + $this->document->sendResponse(); $output = ob_get_clean(); - $this->assertSame('', $output); - $this->assertSame(204, http_response_code()); + parent::assertSame('', $output); + parent::assertSame(204, http_response_code()); } /** * @runInSeparateProcess */ - public function testSendResponse_ContentTypeHeader() { + public function testSendResponse_ContentTypeHeader(): void { if (extension_loaded('xdebug') === false) { - $this->markTestSkipped('can not run without xdebug'); + parent::markTestSkipped('can not run without xdebug'); } - $document = new TestableNonAbstractDocument(); - ob_start(); - $document->sendResponse(); + $this->document->sendResponse(); ob_end_clean(); - $this->assertSame(['Content-Type: '.ContentTypeEnum::Official->value], xdebug_get_headers()); + parent::assertSame(['Content-Type: '.ContentTypeEnum::Official->value], xdebug_get_headers()); $options = ['contentType' => ContentTypeEnum::Official]; ob_start(); - $document->sendResponse($options); + $this->document->sendResponse($options); ob_end_clean(); - $this->assertSame(['Content-Type: '.ContentTypeEnum::Official->value], xdebug_get_headers()); + parent::assertSame(['Content-Type: '.ContentTypeEnum::Official->value], xdebug_get_headers()); $options = ['contentType' => ContentTypeEnum::Debug]; ob_start(); - $document->sendResponse($options); + $this->document->sendResponse($options); ob_end_clean(); - $this->assertSame(['Content-Type: '.ContentTypeEnum::Debug->value], xdebug_get_headers()); + parent::assertSame(['Content-Type: '.ContentTypeEnum::Debug->value], xdebug_get_headers()); $options = ['contentType' => ContentTypeEnum::Jsonp]; ob_start(); - $document->sendResponse($options); + $this->document->sendResponse($options); ob_end_clean(); - $this->assertSame(['Content-Type: '.ContentTypeEnum::Jsonp->value], xdebug_get_headers()); + parent::assertSame(['Content-Type: '.ContentTypeEnum::Jsonp->value], xdebug_get_headers()); } /** * @runInSeparateProcess * @group Extensions */ - public function testSendResponse_ContentTypeHeaderWithExtensions() { + public function testSendResponse_ContentTypeHeaderWithExtensions(): void { if (extension_loaded('xdebug') === false) { - $this->markTestSkipped('can not run without xdebug'); + parent::markTestSkipped('can not run without xdebug'); } - $extension = new TestExtension(); - $extension->setNamespace('one'); - $extension->setOfficialLink('https://jsonapi.org'); - - $document = new TestableNonAbstractDocument(); - $document->applyExtension($extension); + $extension = parent::createConfiguredStub(ExtensionInterface::class, [ + 'getNamespace' => 'one', + 'getOfficialLink' => 'https://jsonapi.org', + ]); + $this->document->applyExtension($extension); ob_start(); - $document->sendResponse(); + $this->document->sendResponse(); ob_end_clean(); - $this->assertSame(['Content-Type: '.ContentTypeEnum::Official->value.'; ext="https://jsonapi.org"'], xdebug_get_headers()); + parent::assertSame(['Content-Type: '.ContentTypeEnum::Official->value.'; ext="https://jsonapi.org"'], xdebug_get_headers()); - $extension = new TestExtension(); - $extension->setNamespace('two'); - $extension->setOfficialLink('https://jsonapi.org/2'); - $document->applyExtension($extension); + $extension = parent::createConfiguredStub(ExtensionInterface::class, [ + 'getNamespace' => 'two', + 'getOfficialLink' => 'https://jsonapi.org/2', + ]); + $this->document->applyExtension($extension); ob_start(); - $document->sendResponse(); + $this->document->sendResponse(); ob_end_clean(); - $this->assertSame(['Content-Type: '.ContentTypeEnum::Official->value.'; ext="https://jsonapi.org https://jsonapi.org/2"'], xdebug_get_headers()); + parent::assertSame(['Content-Type: '.ContentTypeEnum::Official->value.'; ext="https://jsonapi.org https://jsonapi.org/2"'], xdebug_get_headers()); } /** * @runInSeparateProcess * @group Profiles */ - public function testSendResponse_ContentTypeHeaderWithProfiles() { + public function testSendResponse_ContentTypeHeaderWithProfiles(): void { if (extension_loaded('xdebug') === false) { - $this->markTestSkipped('can not run without xdebug'); + parent::markTestSkipped('can not run without xdebug'); } - $profile = new TestProfile(); - $profile->setOfficialLink('https://jsonapi.org'); - - $document = new TestableNonAbstractDocument(); - $document->applyProfile($profile); + $profile = parent::createConfiguredStub(ProfileInterface::class, ['getOfficialLink' => 'https://jsonapi.org']); + $this->document->applyProfile($profile); ob_start(); - $document->sendResponse(); + $this->document->sendResponse(); ob_end_clean(); - $this->assertSame(['Content-Type: '.ContentTypeEnum::Official->value.'; profile="https://jsonapi.org"'], xdebug_get_headers()); + parent::assertSame(['Content-Type: '.ContentTypeEnum::Official->value.'; profile="https://jsonapi.org"'], xdebug_get_headers()); - $profile = new TestProfile(); - $profile->setOfficialLink('https://jsonapi.org/2'); - $document->applyProfile($profile); + $profile = parent::createConfiguredStub(ProfileInterface::class, ['getOfficialLink' => 'https://jsonapi.org/2']); + $this->document->applyProfile($profile); ob_start(); - $document->sendResponse(); + $this->document->sendResponse(); ob_end_clean(); - $this->assertSame(['Content-Type: '.ContentTypeEnum::Official->value.'; profile="https://jsonapi.org https://jsonapi.org/2"'], xdebug_get_headers()); + parent::assertSame(['Content-Type: '.ContentTypeEnum::Official->value.'; profile="https://jsonapi.org https://jsonapi.org/2"'], xdebug_get_headers()); } /** * @runInSeparateProcess */ - public function testSendResponse_StatusCodeHeader() { - $document = new TestableNonAbstractDocument(); + public function testSendResponse_StatusCodeHeader(): void { ob_start(); - $document->sendResponse(); + $this->document->sendResponse(); ob_end_clean(); - $this->assertSame(200, http_response_code()); + parent::assertSame(200, http_response_code()); - $document->setHttpStatusCode(201); + $this->document->setHttpStatusCode(201); ob_start(); - $document->sendResponse(); + $this->document->sendResponse(); ob_end_clean(); - $this->assertSame(201, http_response_code()); + parent::assertSame(201, http_response_code()); - $document->setHttpStatusCode(422); + $this->document->setHttpStatusCode(422); ob_start(); - $document->sendResponse(); + $this->document->sendResponse(); ob_end_clean(); - $this->assertSame(422, http_response_code()); + parent::assertSame(422, http_response_code()); - $document->setHttpStatusCode(503); + $this->document->setHttpStatusCode(503); ob_start(); - $document->sendResponse(); + $this->document->sendResponse(); ob_end_clean(); - $this->assertSame(503, http_response_code()); + parent::assertSame(503, http_response_code()); } /** * @runInSeparateProcess */ - public function testSendResponse_CustomJson() { - $document = new TestableNonAbstractDocument(); + public function testSendResponse_CustomJson(): void { $options = ['json' => '{"foo":42}']; ob_start(); - $document->sendResponse($options); + $this->document->sendResponse($options); $output = ob_get_clean(); - $this->assertSame('{"foo":42}', $output); + parent::assertSame('{"foo":42}', $output); } } diff --git a/tests/TestableNonAbstractDocument.php b/tests/TestableNonAbstractDocument.php deleted file mode 100644 index 57f55161..00000000 --- a/tests/TestableNonAbstractDocument.php +++ /dev/null @@ -1,15 +0,0 @@ -claimUsedFields($fieldNames, $objectContainer); } - public function testClaimUsedFields_EnforceNamespace() { + public function testClaimUsedFields_EnforceNamespace(): void { $validator = new Validator(); $fieldNames = ['foo']; @@ -41,7 +41,7 @@ public function testClaimUsedFields_EnforceNamespace() { } #[DoesNotPerformAssertions] - public function testClaimUsedFields_AllowSameContainer() { + public function testClaimUsedFields_AllowSameContainer(): void { $validator = new Validator(); $fieldNames = ['foo']; @@ -53,7 +53,7 @@ public function testClaimUsedFields_AllowSameContainer() { } #[DoesNotPerformAssertions] - public function testClaimUsedFields_OptionForReusingTypeField() { + public function testClaimUsedFields_OptionForReusingTypeField(): void { $validator = new Validator(); $fieldNames = ['type']; @@ -66,7 +66,7 @@ public function testClaimUsedFields_OptionForReusingTypeField() { } #[DoesNotPerformAssertions] - public function testClearUsedFields_HappyPath() { + public function testClearUsedFields_HappyPath(): void { $validator = new Validator(); $fieldNames = ['foo']; @@ -76,7 +76,7 @@ public function testClearUsedFields_HappyPath() { $validator->clearUsedFields($objectContainer); } - public function testClearUsedFields_FreesForAnotherNamespace() { + public function testClearUsedFields_FreesForAnotherNamespace(): void { $validator = new Validator(); $fieldNames = ['foo', 'bar']; @@ -92,7 +92,7 @@ public function testClearUsedFields_FreesForAnotherNamespace() { catch (DuplicateException) { $thrown = true; } - $this->assertTrue($thrown); + parent::assertTrue($thrown); $objectContainer = ObjectContainerEnum::Attributes; $validator->clearUsedFields($objectContainer); @@ -113,7 +113,7 @@ public function testClearUsedFields_FreesForAnotherNamespace() { } #[DoesNotPerformAssertions] - public function testClaimUsedResourceIdentifier_HappyPath() { + public function testClaimUsedResourceIdentifier_HappyPath(): void { $validator = new Validator(); $resource = new ResourceObject('foo', 1); @@ -123,7 +123,7 @@ public function testClaimUsedResourceIdentifier_HappyPath() { $validator->claimUsedResourceIdentifier($resource); } - public function testClaimUsedResourceIdentifier_RequiresIdentification() { + public function testClaimUsedResourceIdentifier_RequiresIdentification(): void { $validator = new Validator(); $resource = new ResourceObject(); @@ -134,7 +134,7 @@ public function testClaimUsedResourceIdentifier_RequiresIdentification() { $validator->claimUsedResourceIdentifier($resource); } - public function testClaimUsedResourceIdentifier_BlocksDuplicates() { + public function testClaimUsedResourceIdentifier_BlocksDuplicates(): void { $validator = new Validator(); $resource = new ResourceObject('foo', 1); @@ -147,7 +147,7 @@ public function testClaimUsedResourceIdentifier_BlocksDuplicates() { #[DoesNotPerformAssertions] #[DataProvider('dataProviderCheckMemberName_HappyPath')] - public function testCheckMemberName_HappyPath($memberName) { + public function testCheckMemberName_HappyPath($memberName): void { Validator::checkMemberName($memberName); } @@ -162,7 +162,7 @@ public static function dataProviderCheckMemberName_HappyPath() { } #[DataProvider('dataProviderCheckMemberName_InvalidNames')] - public function testCheckMemberName_InvalidNames($memberName) { + public function testCheckMemberName_InvalidNames($memberName): void { $this->expectException(InputException::class); Validator::checkMemberName($memberName); @@ -178,8 +178,8 @@ public static function dataProviderCheckMemberName_InvalidNames() { } #[DataProvider('dataProviderCheckHttpStatusCode_HappyPath')] - public function testCheckHttpStatusCode_HappyPath($expectedOutput, $httpStatusCode) { - $this->assertSame($expectedOutput, Validator::checkHttpStatusCode($httpStatusCode)); + public function testCheckHttpStatusCode_HappyPath($expectedOutput, $httpStatusCode): void { + parent::assertSame($expectedOutput, Validator::checkHttpStatusCode($httpStatusCode)); } public static function dataProviderCheckHttpStatusCode_HappyPath() { diff --git a/tests/example_output/collection/collection.php b/tests/example_output/collection/collection.php index 74a2b4bc..991fbaee 100644 --- a/tests/example_output/collection/collection.php +++ b/tests/example_output/collection/collection.php @@ -27,7 +27,7 @@ public static function createJsonapiDocument() { $collection = []; foreach ($users as $user) { - $resource = ResourceObject::fromObject($user, $type='user', $user->id); + $resource = ResourceObject::fromObject($user, 'user', $user->id); if ($user->id == 42) { $ship = new ResourceObject('ship', 5); diff --git a/tests/example_output/collection_canonical/collection_canonical.php b/tests/example_output/collection_canonical/collection_canonical.php index 58edac71..a58f9451 100644 --- a/tests/example_output/collection_canonical/collection_canonical.php +++ b/tests/example_output/collection_canonical/collection_canonical.php @@ -70,7 +70,7 @@ public static function createJsonapiDocument() { } $document->setSelfLink('http://example.com/articles'); - $document->setPaginationLinks($previous=null, $next='http://example.com/articles?page[offset]=2', $first=null, $last='http://example.com/articles?page[offset]=10'); + $document->setPaginationLinks(previousHref: null, nextHref: 'http://example.com/articles?page[offset]=2', firstHref: null, lastHref: 'http://example.com/articles?page[offset]=10'); $document->unsetJsonapiObject(); return $document; diff --git a/tests/example_output/cursor_pagination_profile/cursor_pagination_profile.php b/tests/example_output/cursor_pagination_profile/cursor_pagination_profile.php index 3af39a28..77363cdf 100644 --- a/tests/example_output/cursor_pagination_profile/cursor_pagination_profile.php +++ b/tests/example_output/cursor_pagination_profile/cursor_pagination_profile.php @@ -23,8 +23,8 @@ public static function createJsonapiDocument() { $document = CollectionDocument::fromResources($user1, $user2, $user42); $document->applyProfile($profile); - $profile->setCount($document, $exactTotal=3, $bestGuessTotal=10); - $profile->setLinksFirstPage($document, $currentUrl='/users?sort=42&page[size]=10', $lastCursor='zaphod'); + $profile->setCount($document, exactTotal: 3, bestGuessTotal: 10); + $profile->setLinksFirstPage($document, baseOrCurrentUrl: '/users?sort=42&page[size]=10', lastCursor: 'zaphod'); return $document; } diff --git a/tests/example_output/errors_all_options/errors_all_options.php b/tests/example_output/errors_all_options/errors_all_options.php index c0e563af..6d44d3a8 100644 --- a/tests/example_output/errors_all_options/errors_all_options.php +++ b/tests/example_output/errors_all_options/errors_all_options.php @@ -9,24 +9,24 @@ class errors_all_options { public static function createJsonapiDocument() { - $errorHumanApi = new ErrorObject($genericCode='Invalid input', $genericTitle='Too much options', $specificDetails='Please, choose a bit less. Consult your ...', $specificAboutLink='https://www.example.com/explanation.html', $genericTypeLink='https://www.example.com/documentation.html'); + $errorHumanApi = new ErrorObject('Invalid input', 'Too much options', 'Please, choose a bit less. Consult your ...', 'https://www.example.com/explanation.html', 'https://www.example.com/documentation.html'); $errorSpecApi = new ErrorObject(); - $errorSpecApi->blameJsonPointer($pointer='/data/attributes/title'); - $errorSpecApi->blameQueryParameter($parameter='filter'); - $errorSpecApi->blameHeader($headerName='X-Foo'); - $errorSpecApi->setUniqueIdentifier($id=42); - $errorSpecApi->addMeta($key='foo', $value='bar'); - $errorSpecApi->setHttpStatusCode($httpStatusCode=404); - $errorSpecApi->setApplicationCode($genericCode='Invalid input'); - $errorSpecApi->setHumanTitle($genericTitle='Too much options'); - $errorSpecApi->setHumanDetails($specificDetails='Please, choose a bit less. Consult your ...'); - $errorSpecApi->setAboutLink($specificAboutLink='https://www.example.com/explanation.html', ['foo'=>'bar']); - $errorSpecApi->setTypeLink($genericTypeLink='https://www.example.com/documentation.html', ['foo'=>'bar']); + $errorSpecApi->blameJsonPointer('/data/attributes/title'); + $errorSpecApi->blameQueryParameter('filter'); + $errorSpecApi->blameHeader('X-Foo'); + $errorSpecApi->setUniqueIdentifier(42); + $errorSpecApi->addMeta('foo', 'bar'); + $errorSpecApi->setHttpStatusCode(404); + $errorSpecApi->setApplicationCode('Invalid input'); + $errorSpecApi->setHumanTitle('Too much options'); + $errorSpecApi->setHumanDetails('Please, choose a bit less. Consult your ...'); + $errorSpecApi->setAboutLink('https://www.example.com/explanation.html', ['foo'=>'bar']); + $errorSpecApi->setTypeLink('https://www.example.com/documentation.html', ['foo'=>'bar']); $metaObject = new \stdClass(); $metaObject->property = 'value'; - $errorSpecApi->addMeta($key='object', $metaObject); + $errorSpecApi->addMeta('object', $metaObject); $anotherError = new ErrorObject('kiss', 'Error objects can be small and simple as well.'); $previousException = new \Exception('something went wrong!'); @@ -35,8 +35,8 @@ public static function createJsonapiDocument() { $document = new ErrorsDocument($errorHumanApi); $document->addErrorObject($errorSpecApi); $document->addErrorObject($anotherError); - $document->addException($someException, $options=['includeExceptionTrace' => false, 'stripExceptionBasePath' => __DIR__]); - $document->add($genericCode='Authentication error', $genericTitle='Not logged in'); + $document->addException($someException, ['includeExceptionTrace' => false, 'stripExceptionBasePath' => __DIR__]); + $document->add('Authentication error', 'Not logged in'); $document->addLink('redirect', '/login', ['label'=>'Log in']); $document->setHttpStatusCode(400); diff --git a/tests/example_output/relationship_to_one_document/relationship_to_one_document.php b/tests/example_output/relationship_to_one_document/relationship_to_one_document.php index 4da6f756..25979b76 100644 --- a/tests/example_output/relationship_to_one_document/relationship_to_one_document.php +++ b/tests/example_output/relationship_to_one_document/relationship_to_one_document.php @@ -11,7 +11,7 @@ class relationship_to_one_document { public static function createJsonapiDocument() { $document = new ResourceDocument('author', 12); - $document->setSelfLink('/articles/1/relationship/author', $meta=[], $level=DocumentLevelEnum::Root); + $document->setSelfLink('/articles/1/relationship/author', level: DocumentLevelEnum::Root); $document->addLink('related', '/articles/1/author'); return $document; diff --git a/tests/example_output/relationships/relationships.php b/tests/example_output/relationships/relationships.php index 49f833f2..4fc9d1ed 100644 --- a/tests/example_output/relationships/relationships.php +++ b/tests/example_output/relationships/relationships.php @@ -40,13 +40,13 @@ public static function createJsonapiDocument() { */ $options = ['includeContainedResources' => false]; - $document->addRelationship('excluded-ship', $ship2Resource, $links=[], $meta=[], $options); + $document->addRelationship('excluded-ship', $ship2Resource, options: $options); /** * to-many relationship, one-by-one */ - $relationshipObject = new RelationshipObject($type=RelationshipTypeEnum::ToMany); + $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToMany); $relationshipObject->addResource($friend1Resource); $relationshipObject->addResource($friend2Resource); @@ -66,7 +66,7 @@ public static function createJsonapiDocument() { * to-many relationship, different types */ - $relationshipObject = new RelationshipObject($type=RelationshipTypeEnum::ToMany); + $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToMany); $relationshipObject->addResource($ship1Resource); $relationshipObject->addResource($dockResource); diff --git a/tests/example_output/resource_human_api/resource_human_api.php b/tests/example_output/resource_human_api/resource_human_api.php index 5505ce40..7f7d3284 100644 --- a/tests/example_output/resource_human_api/resource_human_api.php +++ b/tests/example_output/resource_human_api/resource_human_api.php @@ -17,12 +17,12 @@ public static function createJsonapiDocument() { $user42->name = 'Zaphod Beeblebrox'; $user42->heads = 2; - $document = ResourceDocument::fromObject($user1, $type='user', $user1->id); + $document = ResourceDocument::fromObject($user1, 'user', $user1->id); $document->add('location', $user1->getCurrentLocation()); $document->addLink('homepage', 'https://jsonapi.org'); $document->addMeta('difference', 'is in the code to generate this'); - $relation = ResourceDocument::fromObject($user42, $type='user', $user42->id); + $relation = ResourceDocument::fromObject($user42, 'user', $user42->id); $document->addRelationship('friend', $relation); return $document; diff --git a/tests/example_output/resource_links/resource_links.php b/tests/example_output/resource_links/resource_links.php index 2da44728..8ce95ac7 100644 --- a/tests/example_output/resource_links/resource_links.php +++ b/tests/example_output/resource_links/resource_links.php @@ -14,15 +14,15 @@ public static function createJsonapiDocument() { $user42->name = 'Zaphod Beeblebrox'; $user42->heads = 2; - $document = ResourceDocument::fromObject($user42, $type='user', $user42->id); + $document = ResourceDocument::fromObject($user42, 'user', $user42->id); $selfResourceMeta = ['level' => DocumentLevelEnum::Resource->name]; $partnerMeta = ['level' => DocumentLevelEnum::Resource->name]; $redirectMeta = ['level' => DocumentLevelEnum::Root->name]; $document->setSelfLink('/user/42', $selfResourceMeta); - $document->addLink('partner', '/user/1', $partnerMeta, $level=DocumentLevelEnum::Resource); - $document->addLink('redirect', '/login', $redirectMeta, $level=DocumentLevelEnum::Root); + $document->addLink('partner', '/user/1', $partnerMeta, DocumentLevelEnum::Resource); + $document->addLink('redirect', '/login', $redirectMeta, DocumentLevelEnum::Root); return $document; } diff --git a/tests/example_output/resource_nested_relations/resource_nested_relations.php b/tests/example_output/resource_nested_relations/resource_nested_relations.php index 5db1d549..244c5574 100644 --- a/tests/example_output/resource_nested_relations/resource_nested_relations.php +++ b/tests/example_output/resource_nested_relations/resource_nested_relations.php @@ -29,7 +29,7 @@ public static function createJsonapiDocument() { * building up the json response */ - $document = ResourceDocument::fromObject($user42, $type='user', $user42->id); + $document = ResourceDocument::fromObject($user42, 'user', $user42->id); $document->addRelationship('ship', $ship); return $document; diff --git a/tests/extensions/AtomicOperationsDocumentTest.php b/tests/extensions/AtomicOperationsDocumentTest.php index d4f5c40c..56b9bb9c 100644 --- a/tests/extensions/AtomicOperationsDocumentTest.php +++ b/tests/extensions/AtomicOperationsDocumentTest.php @@ -13,7 +13,7 @@ * @group Extensions */ class AtomicOperationsDocumentTest extends TestCase { - public function testSetResults_HappyPath() { + public function testSetResults_HappyPath(): void { $document = new AtomicOperationsDocument(); $resource1 = new ResourceObject('person', 1); @@ -27,35 +27,35 @@ public function testSetResults_HappyPath() { $array = $document->toArray(); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayHasKey('ext', $array['jsonapi']); - $this->assertCount(1, $array['jsonapi']['ext']); - $this->assertSame((new AtomicOperationsExtension())->getOfficialLink(), $array['jsonapi']['ext'][0]); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayHasKey('ext', $array['jsonapi']); + parent::assertCount(1, $array['jsonapi']['ext']); + parent::assertSame((new AtomicOperationsExtension())->getOfficialLink(), $array['jsonapi']['ext'][0]); - $this->assertArrayHasKey('links', $array); - $this->assertArrayHasKey('self', $array['links']); - $this->assertArrayHasKey('href', $array['links']['self']); - $this->assertArrayHasKey('type', $array['links']['self']); - $this->assertSame('https://example.org/operations', $array['links']['self']['href']); - $this->assertSame('application/vnd.api+json; ext="'.(new AtomicOperationsExtension())->getOfficialLink().'"', $array['links']['self']['type']); + parent::assertArrayHasKey('links', $array); + parent::assertArrayHasKey('self', $array['links']); + parent::assertArrayHasKey('href', $array['links']['self']); + parent::assertArrayHasKey('type', $array['links']['self']); + parent::assertSame('https://example.org/operations', $array['links']['self']['href']); + parent::assertSame('application/vnd.api+json; ext="'.(new AtomicOperationsExtension())->getOfficialLink().'"', $array['links']['self']['type']); - $this->assertArrayHasKey('atomic:results', $array); - $this->assertCount(3, $array['atomic:results']); - $this->assertSame(['data' => $resource1->toArray()], $array['atomic:results'][0]); - $this->assertSame(['data' => $resource2->toArray()], $array['atomic:results'][1]); - $this->assertSame(['data' => $resource3->toArray()], $array['atomic:results'][2]); + parent::assertArrayHasKey('atomic:results', $array); + parent::assertCount(3, $array['atomic:results']); + parent::assertSame(['data' => $resource1->toArray()], $array['atomic:results'][0]); + parent::assertSame(['data' => $resource2->toArray()], $array['atomic:results'][1]); + parent::assertSame(['data' => $resource3->toArray()], $array['atomic:results'][2]); } - public function testSetResults_EmptySuccessResults() { + public function testSetResults_EmptySuccessResults(): void { $document = new AtomicOperationsDocument(); $array = $document->toArray(); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayHasKey('ext', $array['jsonapi']); - $this->assertCount(1, $array['jsonapi']['ext']); - $this->assertSame((new AtomicOperationsExtension())->getOfficialLink(), $array['jsonapi']['ext'][0]); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayHasKey('ext', $array['jsonapi']); + parent::assertCount(1, $array['jsonapi']['ext']); + parent::assertSame((new AtomicOperationsExtension())->getOfficialLink(), $array['jsonapi']['ext'][0]); - $this->assertArrayHasKey('atomic:results', $array); - $this->assertCount(0, $array['atomic:results']); + parent::assertArrayHasKey('atomic:results', $array); + parent::assertCount(0, $array['atomic:results']); } } diff --git a/tests/extensions/TestExtension.php b/tests/extensions/TestExtension.php deleted file mode 100644 index 3c7b814d..00000000 --- a/tests/extensions/TestExtension.php +++ /dev/null @@ -1,28 +0,0 @@ -namespace = $namespace; - } - - public function setOfficialLink(string $officialLink) { - $this->officialLink = $officialLink; - } - - public function getNamespace(): string { - return $this->namespace; - } - - public function getOfficialLink(): string { - return $this->officialLink; - } -} diff --git a/tests/helpers/AtMemberManagerTest.php b/tests/helpers/AtMemberManagerTest.php index ee2fc210..40174cc9 100644 --- a/tests/helpers/AtMemberManagerTest.php +++ b/tests/helpers/AtMemberManagerTest.php @@ -5,56 +5,57 @@ namespace alsvanzelf\jsonapiTests\helpers; use alsvanzelf\jsonapi\exceptions\InputException; -use alsvanzelf\jsonapiTests\helpers\TestableNonTraitAtMemberManager as AtMemberManager; +use alsvanzelf\jsonapi\helpers\AtMemberManager; use PHPUnit\Framework\TestCase; class AtMemberManagerTest extends TestCase { - public function testAddAtMember_HappyPath() { - $helper = new AtMemberManager(); - - $this->assertFalse($helper->hasAtMembers()); - $this->assertSame([], $helper->getAtMembers()); + private static object $helper; + + public static function setUpBeforeClass(): void { + // using AtMemberManager to make it non-trait to test against it + self::$helper = new class { + use AtMemberManager; + }; + } + + public function testAddAtMember_HappyPath(): void { + parent::assertFalse(self::$helper->hasAtMembers()); + parent::assertSame([], self::$helper->getAtMembers()); - $helper->addAtMember('@foo', 'bar'); + self::$helper->addAtMember('@foo', 'bar'); - $array = $helper->getAtMembers(); + $array = self::$helper->getAtMembers(); - $this->assertTrue($helper->hasAtMembers()); - $this->assertCount(1, $array); - $this->assertArrayHasKey('@foo', $array); - $this->assertSame('bar', $array['@foo']); + parent::assertTrue(self::$helper->hasAtMembers()); + parent::assertCount(1, $array); + parent::assertArrayHasKey('@foo', $array); + parent::assertSame('bar', $array['@foo']); } - public function testAddAtMember_WithoutAtSign() { - $helper = new AtMemberManager(); + public function testAddAtMember_WithoutAtSign(): void { + self::$helper->addAtMember('foo', 'bar'); - $helper->addAtMember('foo', 'bar'); + $array = self::$helper->getAtMembers(); - $array = $helper->getAtMembers(); - - $this->assertArrayHasKey('@foo', $array); + parent::assertArrayHasKey('@foo', $array); } - public function testAddAtMember_WithObjectValue() { - $helper = new AtMemberManager(); - + public function testAddAtMember_WithObjectValue(): void { $object = new \stdClass(); $object->bar = 'baz'; - $helper->addAtMember('foo', $object); + self::$helper->addAtMember('foo', $object); - $array = $helper->getAtMembers(); + $array = self::$helper->getAtMembers(); - $this->assertArrayHasKey('@foo', $array); - $this->assertArrayHasKey('bar', $array['@foo']); - $this->assertSame('baz', $array['@foo']['bar']); + parent::assertArrayHasKey('@foo', $array); + parent::assertArrayHasKey('bar', $array['@foo']); + parent::assertSame('baz', $array['@foo']['bar']); } - public function testAddAtMember_InvalidDoubleAt() { - $helper = new AtMemberManager(); - + public function testAddAtMember_InvalidDoubleAt(): void { $this->expectException(InputException::class); - $helper->addAtMember('@@foo', 'bar'); + self::$helper->addAtMember('@@foo', 'bar'); } } diff --git a/tests/helpers/ExtensionMemberManagerTest.php b/tests/helpers/ExtensionMemberManagerTest.php index 16c49334..deee7e32 100644 --- a/tests/helpers/ExtensionMemberManagerTest.php +++ b/tests/helpers/ExtensionMemberManagerTest.php @@ -5,68 +5,69 @@ namespace alsvanzelf\jsonapiTests\helpers; use alsvanzelf\jsonapi\exceptions\InputException; -use alsvanzelf\jsonapiTests\helpers\TestableNonTraitExtensionMemberManager as ExtensionMemberManager; -use alsvanzelf\jsonapiTests\extensions\TestExtension; +use alsvanzelf\jsonapi\helpers\ExtensionMemberManager; +use alsvanzelf\jsonapi\interfaces\ExtensionInterface; use PHPUnit\Framework\TestCase; /** * @group Extensions */ class ExtensionMemberManagerTest extends TestCase { - public function testAddExtensionMember_HappyPath() { - $helper = new ExtensionMemberManager(); - $extension = new TestExtension(); - $extension->setNamespace('test'); + private static object $helper; + + public static function setUpBeforeClass(): void { + // using ExtensionMemberManager to make it non-trait to test against it + self::$helper = new class { + use ExtensionMemberManager; + }; + } + + public function testAddExtensionMember_HappyPath(): void { + $extension = parent::createConfiguredStub(ExtensionInterface::class, ['getNamespace' => 'test']); - $this->assertFalse($helper->hasExtensionMembers()); - $this->assertSame([], $helper->getExtensionMembers()); + parent::assertFalse(self::$helper->hasExtensionMembers()); + parent::assertSame([], self::$helper->getExtensionMembers()); - $helper->addExtensionMember($extension, 'foo', 'bar'); + self::$helper->addExtensionMember($extension, 'foo', 'bar'); - $array = $helper->getExtensionMembers(); + $array = self::$helper->getExtensionMembers(); - $this->assertTrue($helper->hasExtensionMembers()); - $this->assertCount(1, $array); - $this->assertArrayHasKey('test:foo', $array); - $this->assertSame('bar', $array['test:foo']); + parent::assertTrue(self::$helper->hasExtensionMembers()); + parent::assertCount(1, $array); + parent::assertArrayHasKey('test:foo', $array); + parent::assertSame('bar', $array['test:foo']); } - public function testAddExtensionMember_WithNamespacePrefixed() { - $helper = new ExtensionMemberManager(); - $extension = new TestExtension(); - $extension->setNamespace('test'); + public function testAddExtensionMember_WithNamespacePrefixed(): void { + $extension = parent::createConfiguredStub(ExtensionInterface::class, ['getNamespace' => 'test']); - $helper->addExtensionMember($extension, 'test:foo', 'bar'); + self::$helper->addExtensionMember($extension, 'test:foo', 'bar'); - $array = $helper->getExtensionMembers(); + $array = self::$helper->getExtensionMembers(); - $this->assertArrayHasKey('test:foo', $array); + parent::assertArrayHasKey('test:foo', $array); } - public function testAddExtensionMember_WithObjectValue() { - $helper = new ExtensionMemberManager(); - $extension = new TestExtension(); - $extension->setNamespace('test'); + public function testAddExtensionMember_WithObjectValue(): void { + $extension = parent::createConfiguredStub(ExtensionInterface::class, ['getNamespace' => 'test']); $object = new \stdClass(); $object->bar = 'baz'; - $helper->addExtensionMember($extension, 'foo', $object); + self::$helper->addExtensionMember($extension, 'foo', $object); - $array = $helper->getExtensionMembers(); + $array = self::$helper->getExtensionMembers(); - $this->assertArrayHasKey('test:foo', $array); - $this->assertArrayHasKey('bar', $array['test:foo']); - $this->assertSame('baz', $array['test:foo']['bar']); + parent::assertArrayHasKey('test:foo', $array); + parent::assertArrayHasKey('bar', $array['test:foo']); + parent::assertSame('baz', $array['test:foo']['bar']); } - public function testAddExtensionMember_InvalidNamespaceOrCharacter() { - $helper = new ExtensionMemberManager(); - $extension = new TestExtension(); - $extension->setNamespace('test'); + public function testAddExtensionMember_InvalidNamespaceOrCharacter(): void { + $extension = parent::createConfiguredStub(ExtensionInterface::class, ['getNamespace' => 'test']); $this->expectException(InputException::class); - $helper->addExtensionMember($extension, 'foo:bar', 'baz'); + self::$helper->addExtensionMember($extension, 'foo:bar', 'baz'); } } diff --git a/tests/helpers/HttpStatusCodeManagerTest.php b/tests/helpers/HttpStatusCodeManagerTest.php index ea125c9e..9fe2b96f 100644 --- a/tests/helpers/HttpStatusCodeManagerTest.php +++ b/tests/helpers/HttpStatusCodeManagerTest.php @@ -5,35 +5,38 @@ namespace alsvanzelf\jsonapiTests\helpers; use alsvanzelf\jsonapi\exceptions\InputException; -use alsvanzelf\jsonapiTests\helpers\TestableNonTraitHttpStatusCodeManager as HttpStatusCodeManager; +use alsvanzelf\jsonapi\helpers\HttpStatusCodeManager; use PHPUnit\Framework\TestCase; class HttpStatusCodeManagerTest extends TestCase { - public function testSetHttpStatusCode_HappyPath() { - $helper = new HttpStatusCodeManager(); - - $this->assertFalse($helper->hasHttpStatusCode()); + private static object $helper; + + public static function setUpBeforeClass(): void { + // using HttpStatusCodeManager to make it non-trait to test against it + self::$helper = new class { + use HttpStatusCodeManager; + }; + } + + public function testSetHttpStatusCode_HappyPath(): void { + parent::assertFalse(self::$helper->hasHttpStatusCode()); - $helper->setHttpStatusCode(204); + self::$helper->setHttpStatusCode(204); - $this->assertTrue($helper->hasHttpStatusCode()); - $this->assertSame(204, $helper->getHttpStatusCode()); + parent::assertTrue(self::$helper->hasHttpStatusCode()); + parent::assertSame(204, self::$helper->getHttpStatusCode()); } - public function testSetHttpStatusCode_InvalidForHttp() { - $helper = new HttpStatusCodeManager(); - + public function testSetHttpStatusCode_InvalidForHttp(): void { $this->expectException(InputException::class); - $helper->setHttpStatusCode(42); + self::$helper->setHttpStatusCode(42); } - public function testSetHttpStatusCode_AllowsYetUnknownHttpCodes() { - $helper = new HttpStatusCodeManager(); - - $helper->setHttpStatusCode(299); + public function testSetHttpStatusCode_AllowsYetUnknownHttpCodes(): void { + self::$helper->setHttpStatusCode(299); - $this->assertTrue($helper->hasHttpStatusCode()); - $this->assertSame(299, $helper->getHttpStatusCode()); + parent::assertTrue(self::$helper->hasHttpStatusCode()); + parent::assertSame(299, self::$helper->getHttpStatusCode()); } } diff --git a/tests/helpers/LinksManagerTest.php b/tests/helpers/LinksManagerTest.php index 97c462b0..47df373c 100644 --- a/tests/helpers/LinksManagerTest.php +++ b/tests/helpers/LinksManagerTest.php @@ -4,31 +4,45 @@ namespace alsvanzelf\jsonapiTests\helpers; +use alsvanzelf\jsonapi\helpers\LinksManager; use alsvanzelf\jsonapi\objects\LinkObject; -use alsvanzelf\jsonapiTests\helpers\TestableNonTraitLinksManager as LinksManager; use PHPUnit\Framework\TestCase; class LinksManagerTest extends TestCase { - public function testAddLink_HappyPath() { - $linksManager = new LinksManager(); - $linksManager->addLink('foo', 'https://jsonapi.org'); + private object $linksManager; + + public function setUp(): void { + // using LinksManager to make it non-trait to test against it + $this->linksManager = new class { + use LinksManager; + + /** + * @return array + */ + public function toArray(): array { + return $this->links->toArray(); + } + }; + } + + public function testAddLink_HappyPath(): void { + $this->linksManager->addLink('foo', 'https://jsonapi.org'); - $array = $linksManager->toArray(); + $array = $this->linksManager->toArray(); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertSame('https://jsonapi.org', $array['foo']); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertSame('https://jsonapi.org', $array['foo']); } - public function testAddLinkObject_HappyPath() { - $linksManager = new LinksManager(); - $linksManager->addLinkObject('foo', new LinkObject('https://jsonapi.org')); + public function testAddLinkObject_HappyPath(): void { + $this->linksManager->addLinkObject('foo', new LinkObject('https://jsonapi.org')); - $array = $linksManager->toArray(); + $array = $this->linksManager->toArray(); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertArrayHasKey('href', $array['foo']); - $this->assertSame('https://jsonapi.org', $array['foo']['href']); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertArrayHasKey('href', $array['foo']); + parent::assertSame('https://jsonapi.org', $array['foo']['href']); } } diff --git a/tests/helpers/RequestParserTest.php b/tests/helpers/RequestParserTest.php index 529696e1..2f03689c 100644 --- a/tests/helpers/RequestParserTest.php +++ b/tests/helpers/RequestParserTest.php @@ -7,12 +7,14 @@ use alsvanzelf\jsonapi\enums\ContentTypeEnum; use alsvanzelf\jsonapi\enums\SortOrderEnum; use alsvanzelf\jsonapi\helpers\RequestParser; -use alsvanzelf\jsonapiTests\helpers\TestableNonInterfaceRequestInterface; -use alsvanzelf\jsonapiTests\helpers\TestableNonInterfaceServerRequestInterface; use PHPUnit\Framework\TestCase; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ServerRequestInterface; +use Psr\Http\Message\StreamInterface; +use Psr\Http\Message\UriInterface; class RequestParserTest extends TestCase { - public function testFromSuperglobals_HappyPath() { + public function testFromSuperglobals_HappyPath(): void { $_GET = [ 'include' => 'ship,ship.wing', 'fields' => [ @@ -54,60 +56,68 @@ public function testFromSuperglobals_HappyPath() { $requestParser = RequestParser::fromSuperglobals(); - $this->assertSame('https://example.org/user/42?'.http_build_query($_GET), $requestParser->getSelfLink()); + parent::assertSame('https://example.org/user/42?'.http_build_query($_GET), $requestParser->getSelfLink()); - $this->assertTrue($requestParser->hasIncludePaths()); - $this->assertTrue($requestParser->hasSparseFieldset('user')); - $this->assertTrue($requestParser->hasSortFields()); - $this->assertTrue($requestParser->hasPagination()); - $this->assertTrue($requestParser->hasFilter()); + parent::assertTrue($requestParser->hasIncludePaths()); + parent::assertTrue($requestParser->hasSparseFieldset('user')); + parent::assertTrue($requestParser->hasSortFields()); + parent::assertTrue($requestParser->hasPagination()); + parent::assertTrue($requestParser->hasFilter()); - $this->assertSame(['ship' => ['wing' => []]], $requestParser->getIncludePaths()); - $this->assertSame(['name', 'location'], $requestParser->getSparseFieldset('user')); - $this->assertSame([['field' => 'name', 'order' => SortOrderEnum::Ascending], ['field' => 'location', 'order' => SortOrderEnum::Descending]], $requestParser->getSortFields()); - $this->assertSame(['number' => '2', 'size' => '10'], $requestParser->getPagination()); - $this->assertSame('42', $requestParser->getFilter()); + parent::assertSame(['ship' => ['wing' => []]], $requestParser->getIncludePaths()); + parent::assertSame(['name', 'location'], $requestParser->getSparseFieldset('user')); + parent::assertSame([['field' => 'name', 'order' => SortOrderEnum::Ascending], ['field' => 'location', 'order' => SortOrderEnum::Descending]], $requestParser->getSortFields()); + parent::assertSame(['number' => '2', 'size' => '10'], $requestParser->getPagination()); + parent::assertSame('42', $requestParser->getFilter()); - $this->assertTrue($requestParser->hasAttribute('name')); - $this->assertTrue($requestParser->hasRelationship('ship')); - $this->assertTrue($requestParser->hasMeta('lock')); + parent::assertTrue($requestParser->hasAttribute('name')); + parent::assertTrue($requestParser->hasRelationship('ship')); + parent::assertTrue($requestParser->hasMeta('lock')); - $this->assertSame('Foo', $requestParser->getAttribute('name')); - $this->assertSame(['data' => ['type' => 'ship', 'id' => '42']], $requestParser->getRelationship('ship')); - $this->assertTrue($requestParser->getMeta('lock')); + parent::assertSame('Foo', $requestParser->getAttribute('name')); + parent::assertSame(['data' => ['type' => 'ship', 'id' => '42']], $requestParser->getRelationship('ship')); + parent::assertTrue($requestParser->getMeta('lock')); - $this->assertSame($_POST, $requestParser->getDocument()); + parent::assertSame($_POST, $requestParser->getDocument()); } - public function testFromSuperglobals_WithPhpInputStream() { + public function testFromSuperglobals_WithPhpInputStream(): void { $_SERVER['REQUEST_SCHEME'] = 'https'; $_SERVER['HTTP_HOST'] = 'example.org'; $_SERVER['REQUEST_URI'] = '/'; $_SERVER['CONTENT_TYPE'] = ContentTypeEnum::Official->value; $_GET = []; - $_POST = []; + $_POST = [ + 'meta' => [ + 'foo' => 'bar', + ], + ]; $requestParser = RequestParser::fromSuperglobals(); - $this->assertSame([], $requestParser->getDocument()); + parent::assertSame($_POST, $requestParser->getDocument()); } - public function testFromSuperglobals_WithoutServerContext() { + public function testFromSuperglobals_WithoutServerContext(): void { unset($_SERVER['REQUEST_SCHEME']); unset($_SERVER['HTTP_HOST']); unset($_SERVER['REQUEST_URI']); unset($_SERVER['CONTENT_TYPE']); - $_GET = []; - $_POST = []; + $_GET = []; + $_POST = [ + 'meta' => [ + 'foo' => 'bar', + ], + ]; $requestParser = RequestParser::fromSuperglobals(); - $this->assertSame([], $requestParser->getDocument()); + parent::assertSame($_POST, $requestParser->getDocument()); } - public function testFromPsrRequest_WithRequestInterface() { + public function testFromPsrRequest_WithRequestInterface(): void { $queryParameters = [ 'include' => 'ship,ship.wing', 'fields' => [ @@ -142,81 +152,117 @@ public function testFromPsrRequest_WithRequestInterface() { ], ]; - $request = new TestableNonInterfaceRequestInterface($selfLink, $queryParameters, $document); + $request = parent::createConfiguredStub(RequestInterface::class, [ + 'getBody' => parent::createConfiguredStub(StreamInterface::class, ['getContents' => json_encode($document, flags: JSON_THROW_ON_ERROR)]), + 'getUri' => parent::createConfiguredStub(UriInterface::class, [ + '__toString' => $selfLink, + 'getQuery' => http_build_query($queryParameters), + ]), + ]); + $requestParser = RequestParser::fromPsrRequest($request); - $this->assertSame('https://example.org/user/42?'.http_build_query($queryParameters), $requestParser->getSelfLink()); + parent::assertSame($selfLink, $requestParser->getSelfLink()); - $this->assertTrue($requestParser->hasIncludePaths()); - $this->assertTrue($requestParser->hasSparseFieldset('user')); - $this->assertTrue($requestParser->hasSortFields()); - $this->assertTrue($requestParser->hasPagination()); - $this->assertTrue($requestParser->hasFilter()); + parent::assertTrue($requestParser->hasIncludePaths()); + parent::assertTrue($requestParser->hasSparseFieldset('user')); + parent::assertTrue($requestParser->hasSortFields()); + parent::assertTrue($requestParser->hasPagination()); + parent::assertTrue($requestParser->hasFilter()); - $this->assertSame(['ship' => ['wing' => []]], $requestParser->getIncludePaths()); - $this->assertSame(['name', 'location'], $requestParser->getSparseFieldset('user')); - $this->assertSame([['field' => 'name', 'order' => SortOrderEnum::Ascending], ['field' => 'location', 'order' => SortOrderEnum::Descending]], $requestParser->getSortFields()); - $this->assertSame(['number' => '2', 'size' => '10'], $requestParser->getPagination()); - $this->assertSame('42', $requestParser->getFilter()); + parent::assertSame(['ship' => ['wing' => []]], $requestParser->getIncludePaths()); + parent::assertSame(['name', 'location'], $requestParser->getSparseFieldset('user')); + parent::assertSame([['field' => 'name', 'order' => SortOrderEnum::Ascending], ['field' => 'location', 'order' => SortOrderEnum::Descending]], $requestParser->getSortFields()); + parent::assertSame(['number' => '2', 'size' => '10'], $requestParser->getPagination()); + parent::assertSame('42', $requestParser->getFilter()); - $this->assertTrue($requestParser->hasAttribute('name')); - $this->assertTrue($requestParser->hasRelationship('ship')); - $this->assertTrue($requestParser->hasMeta('lock')); + parent::assertTrue($requestParser->hasAttribute('name')); + parent::assertTrue($requestParser->hasRelationship('ship')); + parent::assertTrue($requestParser->hasMeta('lock')); - $this->assertSame('Foo', $requestParser->getAttribute('name')); - $this->assertSame(['data' => ['type' => 'ship', 'id' => '42']], $requestParser->getRelationship('ship')); - $this->assertTrue($requestParser->getMeta('lock')); + parent::assertSame('Foo', $requestParser->getAttribute('name')); + parent::assertSame(['data' => ['type' => 'ship', 'id' => '42']], $requestParser->getRelationship('ship')); + parent::assertTrue($requestParser->getMeta('lock')); - $this->assertSame($document, $requestParser->getDocument()); + parent::assertSame($document, $requestParser->getDocument()); } - public function testFromPsrRequest_WithEmptyDocument() { + public function testFromPsrRequest_WithEmptyDocument(): void { $selfLink = ''; $queryParameters = []; $document = null; - $request = new TestableNonInterfaceRequestInterface($selfLink, $queryParameters, $document); + $request = parent::createConfiguredStub(RequestInterface::class, [ + 'getBody' => parent::createConfiguredStub(StreamInterface::class, ['getContents' => '']), + 'getUri' => parent::createConfiguredStub(UriInterface::class, ['getQuery' => '']), + ]); + $requestParser = RequestParser::fromPsrRequest($request); - $this->assertSame([], $requestParser->getDocument()); + parent::assertSame([], $requestParser->getDocument()); } - public function testFromPsrRequest_WithServerRequestInterface() { + public function testFromPsrRequest_WithServerRequestInterface(): void { $queryParameters = [ 'sort' => 'name,-location', ]; $selfLink = 'https://example.org/user/42?'.http_build_query($queryParameters); - $document = []; - $request = new TestableNonInterfaceServerRequestInterface($selfLink, $queryParameters, $document); + $request = parent::createConfiguredStub(ServerRequestInterface::class, [ + 'getBody' => parent::createConfiguredStub(StreamInterface::class, ['getContents' => '']), + 'getQueryParams' => $queryParameters, + 'getUri' => parent::createConfiguredStub(UriInterface::class, ['__toString' => $selfLink]), + ]); $requestParser = RequestParser::fromPsrRequest($request); - $this->assertSame('https://example.org/user/42?'.http_build_query($queryParameters), $requestParser->getSelfLink()); - $this->assertTrue($requestParser->hasSortFields()); - $this->assertSame([['field' => 'name', 'order' => SortOrderEnum::Ascending], ['field' => 'location', 'order' => SortOrderEnum::Descending]], $requestParser->getSortFields()); + parent::assertSame($selfLink, $requestParser->getSelfLink()); + parent::assertTrue($requestParser->hasSortFields()); + parent::assertSame([['field' => 'name', 'order' => SortOrderEnum::Ascending], ['field' => 'location', 'order' => SortOrderEnum::Descending]], $requestParser->getSortFields()); + } + + public function testFromPsrRequest_WithTooBigJson(): void { + $document = ['meta' => 'foo']; + $currentKey =& $document['meta']; + for ($i=0; $i<513; $i++) { + $currentKey = ['foo' => 'bar']; + $currentKey =& $currentKey['foo']; + } + + $json = json_encode($document, depth: 514, flags: JSON_THROW_ON_ERROR); + + $request = parent::createConfiguredStub(RequestInterface::class, [ + 'getBody' => parent::createConfiguredStub(StreamInterface::class, ['getContents' => $json]), + 'getUri' => parent::createConfiguredStub(UriInterface::class, ['getQuery' => '']), + ]); + + $this->expectException(\JsonException::class); + $this->expectExceptionMessage('Maximum stack depth exceeded'); + $this->expectExceptionCode(JSON_ERROR_DEPTH); + + RequestParser::fromPsrRequest($request); } - public function testGetSelfLink() { + public function testGetSelfLink(): void { $requestParser = new RequestParser('https://example.org/'); - $this->assertSame('https://example.org/', $requestParser->getSelfLink()); + parent::assertSame('https://example.org/', $requestParser->getSelfLink()); $queryParameters = ['foo' => 'bar']; $selfLink = 'https://example.org/user/42?'.http_build_query($queryParameters); $requestParser = new RequestParser($selfLink, $queryParameters); - $this->assertSame($selfLink, $requestParser->getSelfLink()); + parent::assertSame($selfLink, $requestParser->getSelfLink()); } - public function testHasIncludePaths() { + public function testHasIncludePaths(): void { $requestParser = new RequestParser(); - $this->assertFalse($requestParser->hasIncludePaths()); + parent::assertFalse($requestParser->hasIncludePaths()); $queryParameters = ['include' => 'foo,bar,baz.baf']; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertTrue($requestParser->hasIncludePaths()); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertTrue($requestParser->hasIncludePaths()); } - public function testGetIncludePaths_Reformatted() { + public function testGetIncludePaths_Reformatted(): void { $paths = [ 'foo', 'bar', @@ -245,145 +291,145 @@ public function testGetIncludePaths_Reformatted() { ]; $queryParameters = ['include' => implode(',', $paths)]; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertSame($expected, $requestParser->getIncludePaths()); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertSame($expected, $requestParser->getIncludePaths()); } - public function testGetIncludePaths_Raw() { + public function testGetIncludePaths_Raw(): void { $queryParameters = ['include' => 'foo,bar,baz.baf']; - $requestParser = new RequestParser($selfLink='', $queryParameters); + $requestParser = new RequestParser(queryParameters: $queryParameters); $options = ['useNestedIncludePaths' => false]; - $this->assertSame(['foo', 'bar', 'baz.baf'], $requestParser->getIncludePaths($options)); + parent::assertSame(['foo', 'bar', 'baz.baf'], $requestParser->getIncludePaths($options)); } - public function testGetIncludePaths_Empty() { + public function testGetIncludePaths_Empty(): void { $queryParameters = ['include' => '']; - $requestParser = new RequestParser($selfLink='', $queryParameters); + $requestParser = new RequestParser(queryParameters: $queryParameters); - $this->assertTrue($requestParser->hasIncludePaths()); - $this->assertSame([], $requestParser->getIncludePaths()); + parent::assertTrue($requestParser->hasIncludePaths()); + parent::assertSame([], $requestParser->getIncludePaths()); } - public function testHasSparseFieldset() { + public function testHasSparseFieldset(): void { $requestParser = new RequestParser(); - $this->assertFalse($requestParser->hasSparseFieldset('foo')); + parent::assertFalse($requestParser->hasSparseFieldset('foo')); $queryParameters = ['fields' => ['foo' => 'bar']]; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertTrue($requestParser->hasSparseFieldset('foo')); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertTrue($requestParser->hasSparseFieldset('foo')); } - public function testGetSparseFieldset() { + public function testGetSparseFieldset(): void { $queryParameters = ['fields' => ['foo' => 'bar,baz']]; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertSame(['bar', 'baz'], $requestParser->getSparseFieldset('foo')); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertSame(['bar', 'baz'], $requestParser->getSparseFieldset('foo')); $queryParameters = ['fields' => ['foo' => '']]; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertSame([], $requestParser->getSparseFieldset('foo')); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertSame([], $requestParser->getSparseFieldset('foo')); } - public function testHasSortFields() { + public function testHasSortFields(): void { $requestParser = new RequestParser(); - $this->assertFalse($requestParser->hasSortFields()); + parent::assertFalse($requestParser->hasSortFields()); $queryParameters = ['sort' => 'foo']; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertTrue($requestParser->hasSortFields()); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertTrue($requestParser->hasSortFields()); } - public function testGetSortFields_Reformatted() { + public function testGetSortFields_Reformatted(): void { $queryParameters = ['sort' => 'foo']; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertSame([['field' => 'foo', 'order' => SortOrderEnum::Ascending]], $requestParser->getSortFields()); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertSame([['field' => 'foo', 'order' => SortOrderEnum::Ascending]], $requestParser->getSortFields()); $queryParameters = ['sort' => '-bar']; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertSame([['field' => 'bar', 'order' => SortOrderEnum::Descending]], $requestParser->getSortFields()); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertSame([['field' => 'bar', 'order' => SortOrderEnum::Descending]], $requestParser->getSortFields()); $queryParameters = ['sort' => 'foo,-bar']; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertSame([['field' => 'foo', 'order' => SortOrderEnum::Ascending], ['field' => 'bar', 'order' => SortOrderEnum::Descending]], $requestParser->getSortFields()); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertSame([['field' => 'foo', 'order' => SortOrderEnum::Ascending], ['field' => 'bar', 'order' => SortOrderEnum::Descending]], $requestParser->getSortFields()); } - public function testGetSortFields_Raw() { + public function testGetSortFields_Raw(): void { $queryParameters = ['sort' => 'foo,-bar']; - $requestParser = new RequestParser($selfLink='', $queryParameters); + $requestParser = new RequestParser(queryParameters: $queryParameters); $options = ['useAnnotatedSortFields' => false]; - $this->assertSame(['foo', '-bar'], $requestParser->getSortFields($options)); + parent::assertSame(['foo', '-bar'], $requestParser->getSortFields($options)); } - public function testGetSortFields_Empty() { + public function testGetSortFields_Empty(): void { $queryParameters = ['sort' => '']; - $requestParser = new RequestParser($selfLink='', $queryParameters); + $requestParser = new RequestParser(queryParameters: $queryParameters); - $this->assertTrue($requestParser->hasSortFields()); - $this->assertSame([], $requestParser->getSortFields()); + parent::assertTrue($requestParser->hasSortFields()); + parent::assertSame([], $requestParser->getSortFields()); } - public function testHasPagination() { + public function testHasPagination(): void { $requestParser = new RequestParser(); - $this->assertFalse($requestParser->hasPagination()); + parent::assertFalse($requestParser->hasPagination()); $queryParameters = ['page' => ['number' => '2', 'size' => '10']]; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertTrue($requestParser->hasPagination()); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertTrue($requestParser->hasPagination()); } - public function testGetPagination() { + public function testGetPagination(): void { $queryParameters = ['page' => ['number' => '2', 'size' => '10']]; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertSame(['number' => '2', 'size' => '10'], $requestParser->getPagination()); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertSame(['number' => '2', 'size' => '10'], $requestParser->getPagination()); } - public function testHasFilter() { + public function testHasFilter(): void { $requestParser = new RequestParser(); - $this->assertFalse($requestParser->hasFilter()); + parent::assertFalse($requestParser->hasFilter()); $queryParameters = ['filter' => 'foo']; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertTrue($requestParser->hasFilter()); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertTrue($requestParser->hasFilter()); } - public function testGetFilter() { + public function testGetFilter(): void { $queryParameters = ['filter' => 'foo']; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertSame('foo', $requestParser->getFilter()); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertSame('foo', $requestParser->getFilter()); $queryParameters = ['filter' => ['foo' => 'bar']]; - $requestParser = new RequestParser($selfLink='', $queryParameters); - $this->assertSame(['foo' => 'bar'], $requestParser->getFilter()); + $requestParser = new RequestParser(queryParameters: $queryParameters); + parent::assertSame(['foo' => 'bar'], $requestParser->getFilter()); } - public function testHasLocalId() { + public function testHasLocalId(): void { $document = [ 'data' => [ 'id' => 'foo', ], ]; - $requestParser = new RequestParser($selfLink='', $queryParameters=[], $document); + $requestParser = new RequestParser(document: $document); - $this->assertArrayHasKey('data', $requestParser->getDocument()); - $this->assertArrayHasKey('id', $requestParser->getDocument()['data']); - $this->assertFalse($requestParser->hasLocalId()); + parent::assertArrayHasKey('data', $requestParser->getDocument()); + parent::assertArrayHasKey('id', $requestParser->getDocument()['data']); + parent::assertFalse($requestParser->hasLocalId()); $document = [ 'data' => [ 'lid' => 'foo', ], ]; - $requestParser = new RequestParser($selfLink='', $queryParameters=[], $document); + $requestParser = new RequestParser(document: $document); - $this->assertArrayHasKey('data', $requestParser->getDocument()); - $this->assertArrayNotHasKey('id', $requestParser->getDocument()['data']); - $this->assertTrue($requestParser->hasLocalId()); - $this->assertSame('foo', $requestParser->getLocalId()); + parent::assertArrayHasKey('data', $requestParser->getDocument()); + parent::assertArrayNotHasKey('id', $requestParser->getDocument()['data']); + parent::assertTrue($requestParser->hasLocalId()); + parent::assertSame('foo', $requestParser->getLocalId()); } - public function testHasAttribute() { + public function testHasAttribute(): void { $requestParser = new RequestParser(); - $this->assertFalse($requestParser->hasAttribute('foo')); - $this->assertFalse($requestParser->hasAttribute('bar')); + parent::assertFalse($requestParser->hasAttribute('foo')); + parent::assertFalse($requestParser->hasAttribute('bar')); $document = [ 'data' => [ @@ -393,12 +439,12 @@ public function testHasAttribute() { ], ]; - $requestParser = new RequestParser($selfLink='', $queryParameters=[], $document); - $this->assertTrue($requestParser->hasAttribute('foo')); - $this->assertFalse($requestParser->hasAttribute('bar')); + $requestParser = new RequestParser(document: $document); + parent::assertTrue($requestParser->hasAttribute('foo')); + parent::assertFalse($requestParser->hasAttribute('bar')); } - public function testGetAttribute() { + public function testGetAttribute(): void { $document = [ 'data' => [ 'attributes' => [ @@ -407,14 +453,14 @@ public function testGetAttribute() { ], ]; - $requestParser = new RequestParser($selfLink='', $queryParameters=[], $document); - $this->assertSame('bar', $requestParser->getAttribute('foo')); + $requestParser = new RequestParser(document: $document); + parent::assertSame('bar', $requestParser->getAttribute('foo')); } - public function testHasRelationship() { + public function testHasRelationship(): void { $requestParser = new RequestParser(); - $this->assertFalse($requestParser->hasRelationship('foo')); - $this->assertFalse($requestParser->hasRelationship('bar')); + parent::assertFalse($requestParser->hasRelationship('foo')); + parent::assertFalse($requestParser->hasRelationship('bar')); $document = [ 'data' => [ @@ -429,12 +475,12 @@ public function testHasRelationship() { ], ]; - $requestParser = new RequestParser($selfLink='', $queryParameters=[], $document); - $this->assertTrue($requestParser->hasRelationship('foo')); - $this->assertFalse($requestParser->hasRelationship('bar')); + $requestParser = new RequestParser(document: $document); + parent::assertTrue($requestParser->hasRelationship('foo')); + parent::assertFalse($requestParser->hasRelationship('bar')); } - public function testGetRelationship() { + public function testGetRelationship(): void { $document = [ 'data' => [ 'relationships' => [ @@ -448,14 +494,14 @@ public function testGetRelationship() { ], ]; - $requestParser = new RequestParser($selfLink='', $queryParameters=[], $document); - $this->assertSame(['data' => ['type' => 'bar', 'id' => '42']], $requestParser->getRelationship('foo')); + $requestParser = new RequestParser(document: $document); + parent::assertSame(['data' => ['type' => 'bar', 'id' => '42']], $requestParser->getRelationship('foo')); } - public function testHasMeta() { + public function testHasMeta(): void { $requestParser = new RequestParser(); - $this->assertFalse($requestParser->hasMeta('foo')); - $this->assertFalse($requestParser->hasMeta('bar')); + parent::assertFalse($requestParser->hasMeta('foo')); + parent::assertFalse($requestParser->hasMeta('bar')); $document = [ 'meta' => [ @@ -463,23 +509,23 @@ public function testHasMeta() { ], ]; - $requestParser = new RequestParser($selfLink='', $queryParameters=[], $document); - $this->assertTrue($requestParser->hasMeta('foo')); - $this->assertFalse($requestParser->hasMeta('bar')); + $requestParser = new RequestParser(document: $document); + parent::assertTrue($requestParser->hasMeta('foo')); + parent::assertFalse($requestParser->hasMeta('bar')); } - public function testGetMeta() { + public function testGetMeta(): void { $document = [ 'meta' => [ 'foo' => 'bar', ], ]; - $requestParser = new RequestParser($selfLink='', $queryParameters=[], $document); - $this->assertSame('bar', $requestParser->getMeta('foo')); + $requestParser = new RequestParser(document: $document); + parent::assertSame('bar', $requestParser->getMeta('foo')); } - public function testGetDocument() { + public function testGetDocument(): void { $document = [ 'data' => [ 'attributes' => [ @@ -500,7 +546,7 @@ public function testGetDocument() { 'foo' => 'bar', ]; - $requestParser = new RequestParser($selfLink='', $queryParameters=[], $document); - $this->assertSame($document, $requestParser->getDocument()); + $requestParser = new RequestParser(document: $document); + parent::assertSame($document, $requestParser->getDocument()); } } diff --git a/tests/helpers/TestableNonInterfaceRequestInterface.php b/tests/helpers/TestableNonInterfaceRequestInterface.php deleted file mode 100644 index 1918c52e..00000000 --- a/tests/helpers/TestableNonInterfaceRequestInterface.php +++ /dev/null @@ -1,98 +0,0 @@ -selfLink, $this->queryParameters); - } - - // not used in current implementation - public function getRequestTarget() { - return ''; - } - - public function withRequestTarget($requestTarget) { - return $this; - } - - public function getMethod() { - return ''; - } - - public function withMethod($method) { - return $this; - } - - public function withUri(UriInterface $uri, $preserveHost = false) { - return $this; - } - - - /** - * MessageInterface - */ - - public function getBody() { - return new TestableNonInterfaceStreamInterface($this->document); - } - - // not used in current implementation - public function getProtocolVersion() { - return ''; - } - - public function withProtocolVersion($version) { - return $this; - } - - public function getHeaders() { - return [['']]; - } - - public function hasHeader($name) { - return false; - } - - public function getHeader($name) { - return ['']; - } - - public function getHeaderLine($name) { - return ''; - } - - public function withHeader($name, $value) { - return $this; - } - - public function withAddedHeader($name, $value) { - return $this; - } - - public function withoutHeader($name) { - return $this; - } - - public function withBody(StreamInterface $body) { - return $this; - } -} diff --git a/tests/helpers/TestableNonInterfaceServerRequestInterface.php b/tests/helpers/TestableNonInterfaceServerRequestInterface.php deleted file mode 100644 index c732b1b7..00000000 --- a/tests/helpers/TestableNonInterfaceServerRequestInterface.php +++ /dev/null @@ -1,67 +0,0 @@ -queryParameters; - } - - // not used in current implementation - public function getServerParams() { - return []; - } - - public function getCookieParams() { - return []; - } - - public function withCookieParams(array $cookies) { - return $this; - } - - public function withQueryParams(array $query) { - return $this; - } - - public function getUploadedFiles() { - return []; - } - - public function withUploadedFiles(array $uploadedFiles) { - return $this; - } - - public function getParsedBody() { - return null; - } - - public function withParsedBody($data) { - return $this; - } - - public function getAttributes() { - return []; - } - - public function getAttribute($name, $default = null) { - return null; - } - - public function withAttribute($name, $value) { - return $this; - } - - public function withoutAttribute($name) { - return $this; - } -} diff --git a/tests/helpers/TestableNonInterfaceStreamInterface.php b/tests/helpers/TestableNonInterfaceStreamInterface.php deleted file mode 100644 index 47e4b5cb..00000000 --- a/tests/helpers/TestableNonInterfaceStreamInterface.php +++ /dev/null @@ -1,76 +0,0 @@ -document === null) { - return ''; - } - - return (string) json_encode($this->document); - } - - // not used in current implementation - public function __toString(): string { - return ''; - } - - public function close() {} - - public function detach() { - return null; - } - - public function getSize() { - return null; - } - - public function tell() { - return 0; - } - - public function eof() { - return false; - } - - public function isSeekable() { - return false; - } - - public function seek($offset, $whence = SEEK_SET) {} - - public function rewind() {} - - public function isWritable() { - return false; - } - - public function write($string) { - return 0; - } - - public function isReadable() { - return false; - } - - public function read($length) { - return ''; - } - - public function getMetadata($key = null) { - return null; - } -} diff --git a/tests/helpers/TestableNonInterfaceUriInterface.php b/tests/helpers/TestableNonInterfaceUriInterface.php deleted file mode 100644 index 97d8359b..00000000 --- a/tests/helpers/TestableNonInterfaceUriInterface.php +++ /dev/null @@ -1,83 +0,0 @@ -queryParameters); - } - - public function __toString(): string { - return (string) $this->selfLink; - } - - // not used in current implementation - public function getScheme() { - return ''; - } - - public function getAuthority() { - return ''; - } - - public function getUserInfo() { - return ''; - } - - public function getHost() { - return ''; - } - - public function getPort() { - return null; - } - - public function getPath() { - return ''; - } - - public function getFragment() { - return ''; - } - - public function withScheme($scheme) { - return $this; - } - - public function withUserInfo($user, $password = null) { - return $this; - } - - public function withHost($host) { - return $this; - } - - public function withPort($port) { - return $this; - } - - public function withPath($path) { - return $this; - } - - public function withQuery($query) { - return $this; - } - - public function withFragment($fragment) { - return $this; - } -} diff --git a/tests/helpers/TestableNonTraitAtMemberManager.php b/tests/helpers/TestableNonTraitAtMemberManager.php deleted file mode 100644 index 1cea2835..00000000 --- a/tests/helpers/TestableNonTraitAtMemberManager.php +++ /dev/null @@ -1,14 +0,0 @@ -hasLinks() === false) { - return []; - } - - return $this->links->toArray(); - } -} diff --git a/tests/objects/AttributesObjectTest.php b/tests/objects/AttributesObjectTest.php index 90e69c0f..ca604990 100644 --- a/tests/objects/AttributesObjectTest.php +++ b/tests/objects/AttributesObjectTest.php @@ -4,13 +4,12 @@ namespace alsvanzelf\jsonapiTests\objects; -use alsvanzelf\jsonapi\exceptions\InputException; +use alsvanzelf\jsonapi\interfaces\ExtensionInterface; use alsvanzelf\jsonapi\objects\AttributesObject; -use alsvanzelf\jsonapiTests\extensions\TestExtension; use PHPUnit\Framework\TestCase; class AttributesObjectTest extends TestCase { - public function testFromObject_HappyPath() { + public function testFromObject_HappyPath(): void { $object = new \stdClass(); $object->foo = 'bar'; @@ -18,23 +17,23 @@ public function testFromObject_HappyPath() { $array = $attributesObject->toArray(); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertSame('bar', $array['foo']); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertSame('bar', $array['foo']); } - public function testAdd_HappyPath() { + public function testAdd_HappyPath(): void { $attributesObject = new AttributesObject(); $attributesObject->add('foo', 'bar'); $array = $attributesObject->toArray(); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertSame('bar', $array['foo']); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertSame('bar', $array['foo']); } - public function testAdd_AllowsMixedValue() { + public function testAdd_AllowsMixedValue(): void { $attributesObject = new AttributesObject(); $attributesObject->add('array-list', ['foo']); $attributesObject->add('array-int-key', [42 => 'foo']); @@ -48,10 +47,10 @@ public function testAdd_AllowsMixedValue() { $array = $attributesObject->toArray(); - $this->assertCount(9, $array); + parent::assertCount(9, $array); } - public function testAdd_WithObject() { + public function testAdd_WithObject(): void { $object = new \stdClass(); $object->bar = 'baz'; @@ -60,45 +59,28 @@ public function testAdd_WithObject() { $array = $attributesObject->toArray(); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); - $this->assertCount(1, $array['foo']); - $this->assertArrayHasKey('bar', $array['foo']); - $this->assertSame('baz', $array['foo']['bar']); + parent::assertCount(1, $array['foo']); + parent::assertArrayHasKey('bar', $array['foo']); + parent::assertSame('baz', $array['foo']['bar']); } /** * @group Extensions */ - public function testAdd_BlocksExtensionMembersViaRegularAdd() { + public function testAddExtensionMember_HappyPath(): void { $attributesObject = new AttributesObject(); - $extension = new TestExtension(); - $extension->setNamespace('test'); + $extension = parent::createConfiguredStub(ExtensionInterface::class, ['getNamespace' => 'test']); - $this->assertSame([], $attributesObject->toArray()); - - $this->expectException(InputException::class); - $this->expectExceptionMessage('invalid member name "test:foo"'); - - $attributesObject->add('test:foo', 'bar'); - } - - /** - * @group Extensions - */ - public function testAddExtensionMember_HappyPath() { - $attributesObject = new AttributesObject(); - $extension = new TestExtension(); - $extension->setNamespace('test'); - - $this->assertSame([], $attributesObject->toArray()); + parent::assertSame([], $attributesObject->toArray()); $attributesObject->addExtensionMember($extension, 'foo', 'bar'); $array = $attributesObject->toArray(); - $this->assertArrayHasKey('test:foo', $array); - $this->assertSame('bar', $array['test:foo']); + parent::assertArrayHasKey('test:foo', $array); + parent::assertSame('bar', $array['test:foo']); } } diff --git a/tests/objects/ErrorObjectTest.php b/tests/objects/ErrorObjectTest.php index 31365208..8bb42453 100644 --- a/tests/objects/ErrorObjectTest.php +++ b/tests/objects/ErrorObjectTest.php @@ -5,42 +5,42 @@ namespace alsvanzelf\jsonapiTests\objects; use alsvanzelf\jsonapi\exceptions\InputException; +use alsvanzelf\jsonapi\interfaces\ExtensionInterface; use alsvanzelf\jsonapi\objects\ErrorObject; -use alsvanzelf\jsonapiTests\extensions\TestExtension; use PHPUnit\Framework\TestCase; class ErrorObjectTest extends TestCase { - public function testFromException_HappyPath() { + public function testFromException_HappyPath(): void { $exception = new \Exception('foo', 1); $expectedLine = (__LINE__ - 1); $errorObject = ErrorObject::fromException($exception); $array = $errorObject->toArray(); - $this->assertCount(2, $array); - $this->assertArrayHasKey('code', $array); - $this->assertArrayHasKey('meta', $array); - $this->assertSame('Exception', $array['code']); - $this->assertCount(6, $array['meta']); - $this->assertArrayHasKey('type', $array['meta']); - $this->assertArrayHasKey('message', $array['meta']); - $this->assertArrayHasKey('code', $array['meta']); - $this->assertArrayHasKey('file', $array['meta']); - $this->assertArrayHasKey('line', $array['meta']); - $this->assertArrayHasKey('trace', $array['meta']); - $this->assertSame('Exception', $array['meta']['type']); - $this->assertSame('foo', $array['meta']['message']); - $this->assertSame(1, $array['meta']['code']); - $this->assertSame(__FILE__, $array['meta']['file']); - $this->assertSame($expectedLine, $array['meta']['line']); - $this->assertGreaterThan(1, $array['meta']['trace']); - $this->assertArrayHasKey('function', $array['meta']['trace'][0]); - $this->assertArrayHasKey('class', $array['meta']['trace'][0]); - $this->assertSame(__FUNCTION__, $array['meta']['trace'][0]['function']); - $this->assertSame(self::class, $array['meta']['trace'][0]['class']); + parent::assertCount(2, $array); + parent::assertArrayHasKey('code', $array); + parent::assertArrayHasKey('meta', $array); + parent::assertSame('Exception', $array['code']); + parent::assertCount(6, $array['meta']); + parent::assertArrayHasKey('type', $array['meta']); + parent::assertArrayHasKey('message', $array['meta']); + parent::assertArrayHasKey('code', $array['meta']); + parent::assertArrayHasKey('file', $array['meta']); + parent::assertArrayHasKey('line', $array['meta']); + parent::assertArrayHasKey('trace', $array['meta']); + parent::assertSame('Exception', $array['meta']['type']); + parent::assertSame('foo', $array['meta']['message']); + parent::assertSame(1, $array['meta']['code']); + parent::assertSame(__FILE__, $array['meta']['file']); + parent::assertSame($expectedLine, $array['meta']['line']); + parent::assertGreaterThan(1, $array['meta']['trace']); + parent::assertArrayHasKey('function', $array['meta']['trace'][0]); + parent::assertArrayHasKey('class', $array['meta']['trace'][0]); + parent::assertSame(__FUNCTION__, $array['meta']['trace'][0]['function']); + parent::assertSame(self::class, $array['meta']['trace'][0]['class']); } - public function testFromException_DoNotExposeTrace() { + public function testFromException_DoNotExposeTrace(): void { $exception = new \Exception('foo', 1); $expectedLine = (__LINE__ - 1); $options = ['includeExceptionTrace' => false]; @@ -48,18 +48,18 @@ public function testFromException_DoNotExposeTrace() { $array = $errorObject->toArray(); - $this->assertArrayHasKey('meta', $array); - $this->assertSame('Exception', $array['code']); - $this->assertCount(5, $array['meta']); - $this->assertArrayHasKey('type', $array['meta']); - $this->assertArrayHasKey('message', $array['meta']); - $this->assertArrayHasKey('code', $array['meta']); - $this->assertArrayHasKey('file', $array['meta']); - $this->assertArrayHasKey('line', $array['meta']); - $this->assertArrayNotHasKey('trace', $array['meta']); + parent::assertArrayHasKey('meta', $array); + parent::assertSame('Exception', $array['code']); + parent::assertCount(5, $array['meta']); + parent::assertArrayHasKey('type', $array['meta']); + parent::assertArrayHasKey('message', $array['meta']); + parent::assertArrayHasKey('code', $array['meta']); + parent::assertArrayHasKey('file', $array['meta']); + parent::assertArrayHasKey('line', $array['meta']); + parent::assertArrayNotHasKey('trace', $array['meta']); } - public function testFromException_StripFilePath() { + public function testFromException_StripFilePath(): void { $exception = new \Exception('foo', 1); $basePath = realpath(__DIR__.'/../../').'/'; $options = ['stripExceptionBasePath' => $basePath]; @@ -67,110 +67,109 @@ public function testFromException_StripFilePath() { $array = $errorObject->toArray(); - $this->assertArrayHasKey('meta', $array); - $this->assertArrayHasKey('file', $array['meta']); - $this->assertArrayHasKey('trace', $array['meta']); - $this->assertSame('tests/objects/ErrorObjectTest.php', $array['meta']['file']); - $this->assertGreaterThan(2, $array['meta']['trace']); - $this->assertArrayHasKey('file', $array['meta']['trace'][1]); - $this->assertSame('vendor/phpunit/phpunit/src/Framework/TestCase.php', $array['meta']['trace'][1]['file']); + parent::assertArrayHasKey('meta', $array); + parent::assertArrayHasKey('file', $array['meta']); + parent::assertArrayHasKey('trace', $array['meta']); + parent::assertSame('tests/objects/ErrorObjectTest.php', $array['meta']['file']); + parent::assertGreaterThan(2, $array['meta']['trace']); + parent::assertArrayHasKey('file', $array['meta']['trace'][1]); + parent::assertSame('vendor/phpunit/phpunit/src/Framework/TestCase.php', $array['meta']['trace'][1]['file']); } - public function testFromException_NamespacedException() { + public function testFromException_NamespacedException(): void { $exception = new InputException(); $errorObject = ErrorObject::fromException($exception); $array = $errorObject->toArray(); - $this->assertArrayHasKey('code', $array); - $this->assertArrayHasKey('meta', $array); - $this->assertArrayHasKey('type', $array['meta']); - $this->assertSame('Input Exception', $array['code']); - $this->assertSame('alsvanzelf\jsonapi\exceptions\InputException', $array['meta']['type']); + parent::assertArrayHasKey('code', $array); + parent::assertArrayHasKey('meta', $array); + parent::assertArrayHasKey('type', $array['meta']); + parent::assertSame('Input Exception', $array['code']); + parent::assertSame('alsvanzelf\jsonapi\exceptions\InputException', $array['meta']['type']); } - public function testFromException_NamespacedThrowable() { + public function testFromException_NamespacedThrowable(): void { $exception = new TestError(); $errorObject = ErrorObject::fromException($exception); $array = $errorObject->toArray(); - $this->assertArrayHasKey('code', $array); - $this->assertArrayHasKey('meta', $array); - $this->assertArrayHasKey('type', $array['meta']); - $this->assertSame('Test Error', $array['code']); - $this->assertSame('alsvanzelf\jsonapiTests\objects\TestError', $array['meta']['type']); + parent::assertArrayHasKey('code', $array); + parent::assertArrayHasKey('meta', $array); + parent::assertArrayHasKey('type', $array['meta']); + parent::assertSame('Test Error', $array['code']); + parent::assertSame('alsvanzelf\jsonapiTests\objects\TestError', $array['meta']['type']); } - public function testIsEmpty_All() { + public function testIsEmpty_All(): void { $errorObject = new ErrorObject(); - $this->assertTrue($errorObject->isEmpty()); + parent::assertTrue($errorObject->isEmpty()); $errorObject = new ErrorObject(); $errorObject->setUniqueIdentifier(42); - $this->assertFalse($errorObject->isEmpty()); + parent::assertFalse($errorObject->isEmpty()); $errorObject = new ErrorObject(); $errorObject->setHttpStatusCode(422); - $this->assertFalse($errorObject->isEmpty()); + parent::assertFalse($errorObject->isEmpty()); $errorObject = new ErrorObject(); $errorObject->setApplicationCode(42); - $this->assertFalse($errorObject->isEmpty()); + parent::assertFalse($errorObject->isEmpty()); $errorObject = new ErrorObject(); $errorObject->setHumanTitle('foo'); - $this->assertFalse($errorObject->isEmpty()); + parent::assertFalse($errorObject->isEmpty()); $errorObject = new ErrorObject(); $errorObject->setHumanDetails('foo'); - $this->assertFalse($errorObject->isEmpty()); + parent::assertFalse($errorObject->isEmpty()); $errorObject = new ErrorObject(); $errorObject->addLink('foo', 'https://jsonapi.org'); - $this->assertFalse($errorObject->isEmpty()); + parent::assertFalse($errorObject->isEmpty()); $errorObject = new ErrorObject(); $errorObject->addSource('pointer', '/bar'); - $this->assertFalse($errorObject->isEmpty()); + parent::assertFalse($errorObject->isEmpty()); $errorObject = new ErrorObject(); $errorObject->addSource('parameter', 'bar'); - $this->assertFalse($errorObject->isEmpty()); + parent::assertFalse($errorObject->isEmpty()); $errorObject = new ErrorObject(); $errorObject->addSource('header', 'X-Bar'); - $this->assertFalse($errorObject->isEmpty()); + parent::assertFalse($errorObject->isEmpty()); $errorObject = new ErrorObject(); $errorObject->addMeta('foo', 'bar'); - $this->assertFalse($errorObject->isEmpty()); + parent::assertFalse($errorObject->isEmpty()); $errorObject = new ErrorObject(); $errorObject->addAtMember('context', 'test'); - $this->assertFalse($errorObject->isEmpty()); + parent::assertFalse($errorObject->isEmpty()); $errorObject = new ErrorObject(); - $errorObject->addExtensionMember(new TestExtension(), 'foo', 'bar'); - $this->assertFalse($errorObject->isEmpty()); + $errorObject->addExtensionMember(parent::createStub(ExtensionInterface::class), 'foo', 'bar'); + parent::assertFalse($errorObject->isEmpty()); } /** * @group Extensions */ - public function testToArray_WithExtensionMembers() { + public function testToArray_WithExtensionMembers(): void { $errorObject = new ErrorObject(); - $extension = new TestExtension(); - $extension->setNamespace('test'); + $extension = parent::createConfiguredStub(ExtensionInterface::class, ['getNamespace' => 'test']); - $this->assertSame([], $errorObject->toArray()); + parent::assertSame([], $errorObject->toArray()); $errorObject->addExtensionMember($extension, 'foo', 'bar'); $array = $errorObject->toArray(); - $this->assertArrayHasKey('test:foo', $array); - $this->assertSame('bar', $array['test:foo']); + parent::assertArrayHasKey('test:foo', $array); + parent::assertSame('bar', $array['test:foo']); } } diff --git a/tests/objects/JsonapiObjectTest.php b/tests/objects/JsonapiObjectTest.php index a2c3c4e1..29965b54 100644 --- a/tests/objects/JsonapiObjectTest.php +++ b/tests/objects/JsonapiObjectTest.php @@ -4,74 +4,74 @@ namespace alsvanzelf\jsonapiTests\objects; +use alsvanzelf\jsonapi\interfaces\ExtensionInterface; +use alsvanzelf\jsonapi\interfaces\ProfileInterface; use alsvanzelf\jsonapi\objects\JsonapiObject; -use alsvanzelf\jsonapiTests\extensions\TestExtension; -use alsvanzelf\jsonapiTests\profiles\TestProfile; use PHPUnit\Framework\TestCase; class JsonapiObjectTest extends TestCase { - public function testAddMeta_HappyPath() { + public function testAddMeta_HappyPath(): void { $jsonapiObject = new JsonapiObject($version=null); - $this->assertTrue($jsonapiObject->isEmpty()); + parent::assertTrue($jsonapiObject->isEmpty()); $jsonapiObject->addMeta('foo', 'bar'); - $this->assertFalse($jsonapiObject->isEmpty()); + parent::assertFalse($jsonapiObject->isEmpty()); $array = $jsonapiObject->toArray(); - $this->assertArrayHasKey('meta', $array); - $this->assertArrayHasKey('foo', $array['meta']); - $this->assertSame('bar', $array['meta']['foo']); + parent::assertArrayHasKey('meta', $array); + parent::assertArrayHasKey('foo', $array['meta']); + parent::assertSame('bar', $array['meta']['foo']); } - public function testIsEmpty_WithAtMembers() { + public function testIsEmpty_WithAtMembers(): void { $jsonapiObject = new JsonapiObject($version=null); - $this->assertTrue($jsonapiObject->isEmpty()); + parent::assertTrue($jsonapiObject->isEmpty()); $jsonapiObject->addAtMember('context', 'test'); - $this->assertFalse($jsonapiObject->isEmpty()); + parent::assertFalse($jsonapiObject->isEmpty()); } /** * @group Extensions */ - public function testIsEmpty_WithExtensionLink() { + public function testIsEmpty_WithExtensionLink(): void { $jsonapiObject = new JsonapiObject($version=null); - $this->assertTrue($jsonapiObject->isEmpty()); + parent::assertTrue($jsonapiObject->isEmpty()); - $jsonapiObject->addExtension(new TestExtension()); + $jsonapiObject->addExtension(parent::createStub(ExtensionInterface::class)); - $this->assertFalse($jsonapiObject->isEmpty()); + parent::assertFalse($jsonapiObject->isEmpty()); } /** * @group Profiles */ - public function testIsEmpty_WithProfileLink() { + public function testIsEmpty_WithProfileLink(): void { $jsonapiObject = new JsonapiObject($version=null); - $this->assertTrue($jsonapiObject->isEmpty()); + parent::assertTrue($jsonapiObject->isEmpty()); - $jsonapiObject->addProfile(new TestProfile()); + $jsonapiObject->addProfile(parent::createStub(ProfileInterface::class)); - $this->assertFalse($jsonapiObject->isEmpty()); + parent::assertFalse($jsonapiObject->isEmpty()); } /** * @group Extensions */ - public function testIsEmpty_WithExtensionMembers() { + public function testIsEmpty_WithExtensionMembers(): void { $jsonapiObject = new JsonapiObject($version=null); - $this->assertTrue($jsonapiObject->isEmpty()); + parent::assertTrue($jsonapiObject->isEmpty()); - $jsonapiObject->addExtensionMember(new TestExtension(), 'foo', 'bar'); + $jsonapiObject->addExtensionMember(parent::createStub(ExtensionInterface::class), 'foo', 'bar'); - $this->assertFalse($jsonapiObject->isEmpty()); + parent::assertFalse($jsonapiObject->isEmpty()); } } diff --git a/tests/objects/LinkObjectTest.php b/tests/objects/LinkObjectTest.php index c37d1377..fe6da28a 100644 --- a/tests/objects/LinkObjectTest.php +++ b/tests/objects/LinkObjectTest.php @@ -4,167 +4,167 @@ namespace alsvanzelf\jsonapiTests\objects; +use alsvanzelf\jsonapi\interfaces\ExtensionInterface; use alsvanzelf\jsonapi\objects\LinkObject; -use alsvanzelf\jsonapiTests\extensions\TestExtension; use PHPUnit\Framework\TestCase; class LinkObjectTest extends TestCase { - public function testSetDescribedBy_HappyPath() { + public function testSetDescribedBy_HappyPath(): void { $linkObject = new LinkObject(); - $this->assertTrue($linkObject->isEmpty()); + parent::assertTrue($linkObject->isEmpty()); $linkObject->setDescribedBy('https://jsonapi.org'); - $this->assertFalse($linkObject->isEmpty()); + parent::assertFalse($linkObject->isEmpty()); $array = $linkObject->toArray(); - $this->assertArrayHasKey('describedby', $array); - $this->assertArrayHasKey('href', $array['describedby']); - $this->assertSame('https://jsonapi.org', $array['describedby']['href']); + parent::assertArrayHasKey('describedby', $array); + parent::assertArrayHasKey('href', $array['describedby']); + parent::assertSame('https://jsonapi.org', $array['describedby']['href']); } - public function testAddLanguage_HappyPath() { + public function testAddLanguage_HappyPath(): void { $linkObject = new LinkObject(); - $this->assertTrue($linkObject->isEmpty()); + parent::assertTrue($linkObject->isEmpty()); $linkObject->addLanguage('nl-NL'); - $this->assertFalse($linkObject->isEmpty()); + parent::assertFalse($linkObject->isEmpty()); $array = $linkObject->toArray(); - $this->assertArrayHasKey('hreflang', $array); - $this->assertSame('nl-NL', $array['hreflang']); + parent::assertArrayHasKey('hreflang', $array); + parent::assertSame('nl-NL', $array['hreflang']); } - public function testAddLanguage_Multiple() { + public function testAddLanguage_Multiple(): void { $linkObject = new LinkObject(); $linkObject->addLanguage('nl-NL'); $array = $linkObject->toArray(); - $this->assertSame('nl-NL', $array['hreflang']); + parent::assertSame('nl-NL', $array['hreflang']); $linkObject->addLanguage('en-US'); $array = $linkObject->toArray(); - $this->assertSame(['nl-NL', 'en-US'], $array['hreflang']); + parent::assertSame(['nl-NL', 'en-US'], $array['hreflang']); } - public function testAddMeta_HappyPath() { + public function testAddMeta_HappyPath(): void { $linkObject = new LinkObject(); - $this->assertTrue($linkObject->isEmpty()); + parent::assertTrue($linkObject->isEmpty()); $linkObject->addMeta('foo', 'bar'); - $this->assertFalse($linkObject->isEmpty()); + parent::assertFalse($linkObject->isEmpty()); $array = $linkObject->toArray(); - $this->assertArrayHasKey('meta', $array); - $this->assertArrayHasKey('foo', $array['meta']); - $this->assertSame('bar', $array['meta']['foo']); + parent::assertArrayHasKey('meta', $array); + parent::assertArrayHasKey('foo', $array['meta']); + parent::assertSame('bar', $array['meta']['foo']); } - public function testSetRelationType_HappyPath() { + public function testSetRelationType_HappyPath(): void { $linkObject = new LinkObject(); - $this->assertTrue($linkObject->isEmpty()); + parent::assertTrue($linkObject->isEmpty()); $linkObject->setRelationType('external'); - $this->assertFalse($linkObject->isEmpty()); + parent::assertFalse($linkObject->isEmpty()); $array = $linkObject->toArray(); - $this->assertArrayHasKey('rel', $array); - $this->assertSame('external', $array['rel']); + parent::assertArrayHasKey('rel', $array); + parent::assertSame('external', $array['rel']); } - public function testSetDescribedByLinkObject_HappyPath() { + public function testSetDescribedByLinkObject_HappyPath(): void { $linkObject = new LinkObject(); - $this->assertTrue($linkObject->isEmpty()); + parent::assertTrue($linkObject->isEmpty()); $describedBy = new LinkObject('https://jsonapi.org'); $linkObject->setDescribedByLinkObject($describedBy); - $this->assertFalse($linkObject->isEmpty()); + parent::assertFalse($linkObject->isEmpty()); $array = $linkObject->toArray(); - $this->assertArrayHasKey('describedby', $array); - $this->assertArrayHasKey('href', $array['describedby']); - $this->assertSame('https://jsonapi.org', $array['describedby']['href']); + parent::assertArrayHasKey('describedby', $array); + parent::assertArrayHasKey('href', $array['describedby']); + parent::assertSame('https://jsonapi.org', $array['describedby']['href']); } - public function testSetHumanTitle_HappyPath() { + public function testSetHumanTitle_HappyPath(): void { $linkObject = new LinkObject(); - $this->assertTrue($linkObject->isEmpty()); + parent::assertTrue($linkObject->isEmpty()); $linkObject->setHumanTitle('A link'); - $this->assertFalse($linkObject->isEmpty()); + parent::assertFalse($linkObject->isEmpty()); $array = $linkObject->toArray(); - $this->assertArrayHasKey('title', $array); - $this->assertSame('A link', $array['title']); + parent::assertArrayHasKey('title', $array); + parent::assertSame('A link', $array['title']); } - public function testSetMediaType_HappyPath() { + public function testSetMediaType_HappyPath(): void { $linkObject = new LinkObject(); - $this->assertTrue($linkObject->isEmpty()); + parent::assertTrue($linkObject->isEmpty()); $linkObject->setMediaType('text/html'); - $this->assertFalse($linkObject->isEmpty()); + parent::assertFalse($linkObject->isEmpty()); $array = $linkObject->toArray(); - $this->assertArrayHasKey('type', $array); - $this->assertSame('text/html', $array['type']); + parent::assertArrayHasKey('type', $array); + parent::assertSame('text/html', $array['type']); } - public function testSetHreflang_HappyPath() { + public function testSetHreflang_HappyPath(): void { $linkObject = new LinkObject(); - $this->assertTrue($linkObject->isEmpty()); + parent::assertTrue($linkObject->isEmpty()); $linkObject->setHreflang('nl-NL', 'en-US'); - $this->assertFalse($linkObject->isEmpty()); + parent::assertFalse($linkObject->isEmpty()); $array = $linkObject->toArray(); - $this->assertArrayHasKey('hreflang', $array); - $this->assertSame(['nl-NL', 'en-US'], $array['hreflang']); + parent::assertArrayHasKey('hreflang', $array); + parent::assertSame(['nl-NL', 'en-US'], $array['hreflang']); } - public function testIsEmpty_WithAtMembers() { + public function testIsEmpty_WithAtMembers(): void { $linkObject = new LinkObject(); - $this->assertTrue($linkObject->isEmpty()); + parent::assertTrue($linkObject->isEmpty()); $linkObject->addAtMember('context', 'test'); - $this->assertFalse($linkObject->isEmpty()); + parent::assertFalse($linkObject->isEmpty()); } /** * @group Extensions */ - public function testIsEmpty_WithExtensionMembers() { + public function testIsEmpty_WithExtensionMembers(): void { $linkObject = new LinkObject(); - $this->assertTrue($linkObject->isEmpty()); + parent::assertTrue($linkObject->isEmpty()); - $linkObject->addExtensionMember(new TestExtension(), 'foo', 'bar'); + $linkObject->addExtensionMember(parent::createStub(ExtensionInterface::class), 'foo', 'bar'); - $this->assertFalse($linkObject->isEmpty()); + parent::assertFalse($linkObject->isEmpty()); } } diff --git a/tests/objects/LinksObjectTest.php b/tests/objects/LinksObjectTest.php index c65643d1..846766ed 100644 --- a/tests/objects/LinksObjectTest.php +++ b/tests/objects/LinksObjectTest.php @@ -11,7 +11,7 @@ use PHPUnit\Framework\TestCase; class LinksObjectTest extends TestCase { - public function testFromObject_HappyPath() { + public function testFromObject_HappyPath(): void { $object = new \stdClass(); $object->foo = 'https://jsonapi.org'; @@ -19,83 +19,83 @@ public function testFromObject_HappyPath() { $array = $linksObject->toArray(); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertSame('https://jsonapi.org', $array['foo']); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertSame('https://jsonapi.org', $array['foo']); } - public function testAddLinkString_HappyPath() { + public function testAddLinkString_HappyPath(): void { $linksObject = new LinksObject(); - $linksObject->addLinkString($key='foo', 'https://jsonapi.org'); + $linksObject->addLinkString('foo', 'https://jsonapi.org'); $array = $linksObject->toArray(); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertSame('https://jsonapi.org', $array['foo']); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertSame('https://jsonapi.org', $array['foo']); } - public function testAddLinkString_InvalidKey() { + public function testAddLinkString_InvalidKey(): void { $linksObject = new LinksObject(); $this->expectException(InputException::class); - $linksObject->addLinkString($key='-foo', 'https://jsonapi.org'); + $linksObject->addLinkString('-foo', 'https://jsonapi.org'); } - public function testAddLinkString_ExistingKey() { + public function testAddLinkString_ExistingKey(): void { $linksObject = new LinksObject(); - $linksObject->addLinkString($key='foo', 'https://jsonapi.org'); + $linksObject->addLinkString('foo', 'https://jsonapi.org'); $this->expectException(DuplicateException::class); - $linksObject->addLinkString($key='foo', 'https://jsonapi.org/2'); + $linksObject->addLinkString('foo', 'https://jsonapi.org/2'); } - public function testAddLinkObject_HappyPath() { + public function testAddLinkObject_HappyPath(): void { $linkObject = new LinkObject('https://jsonapi.org'); $linksObject = new LinksObject(); - $linksObject->addLinkObject($key='foo', $linkObject); + $linksObject->addLinkObject('foo', $linkObject); $array = $linksObject->toArray(); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertArrayHasKey('href', $array['foo']); - $this->assertSame('https://jsonapi.org', $array['foo']['href']); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertArrayHasKey('href', $array['foo']); + parent::assertSame('https://jsonapi.org', $array['foo']['href']); } - public function testAddLinkObject_InvalidKey() { + public function testAddLinkObject_InvalidKey(): void { $linkObject = new LinkObject('https://jsonapi.org'); $linksObject = new LinksObject(); $this->expectException(InputException::class); - $linksObject->addLinkObject($key='-foo', $linkObject); + $linksObject->addLinkObject('-foo', $linkObject); } - public function testAddLinkObject_ExistingKey() { + public function testAddLinkObject_ExistingKey(): void { $linksObject = new LinksObject(); $linkObject = new LinkObject('https://jsonapi.org'); - $linksObject->addLinkObject($key='foo', $linkObject); + $linksObject->addLinkObject('foo', $linkObject); $linkObject = new LinkObject('https://jsonapi.org/2'); $this->expectException(DuplicateException::class); - $linksObject->addLinkObject($key='foo', $linkObject); + $linksObject->addLinkObject('foo', $linkObject); } - public function testToArray_ExplicitlyEmpty() { + public function testToArray_ExplicitlyEmpty(): void { $linksObject = new LinksObject(); $linksObject->addLinkObject('foo', new LinkObject()); $array = $linksObject->toArray(); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertNull($array['foo']); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertNull($array['foo']); } } diff --git a/tests/objects/MetaObjectTest.php b/tests/objects/MetaObjectTest.php index 15c762ab..baf46664 100644 --- a/tests/objects/MetaObjectTest.php +++ b/tests/objects/MetaObjectTest.php @@ -4,12 +4,12 @@ namespace alsvanzelf\jsonapiTests\objects; +use alsvanzelf\jsonapi\interfaces\ExtensionInterface; use alsvanzelf\jsonapi\objects\MetaObject; -use alsvanzelf\jsonapiTests\extensions\TestExtension; use PHPUnit\Framework\TestCase; class MetaObjectTest extends TestCase { - public function testAdd_AllowsMixedValue() { + public function testAdd_AllowsMixedValue(): void { $metaObject = new MetaObject(); $metaObject->add('array-list', ['foo']); $metaObject->add('array-int-key', [42 => 'foo']); @@ -23,10 +23,10 @@ public function testAdd_AllowsMixedValue() { $array = $metaObject->toArray(); - $this->assertCount(9, $array); + parent::assertCount(9, $array); } - public function testFromObject_HappyPath() { + public function testFromObject_HappyPath(): void { $object = new \stdClass(); $object->foo = 'bar'; @@ -34,31 +34,31 @@ public function testFromObject_HappyPath() { $array = $metaObject->toArray(); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertSame('bar', $array['foo']); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertSame('bar', $array['foo']); } - public function testIsEmpty_WithAtMembers() { + public function testIsEmpty_WithAtMembers(): void { $metaObject = new MetaObject(); - $this->assertTrue($metaObject->isEmpty()); + parent::assertTrue($metaObject->isEmpty()); $metaObject->addAtMember('context', 'test'); - $this->assertFalse($metaObject->isEmpty()); + parent::assertFalse($metaObject->isEmpty()); } /** * @group Extensions */ - public function testIsEmpty_WithExtensionMembers() { + public function testIsEmpty_WithExtensionMembers(): void { $metaObject = new MetaObject(); - $this->assertTrue($metaObject->isEmpty()); + parent::assertTrue($metaObject->isEmpty()); - $metaObject->addExtensionMember(new TestExtension(), 'foo', 'bar'); + $metaObject->addExtensionMember(parent::createStub(ExtensionInterface::class), 'foo', 'bar'); - $this->assertFalse($metaObject->isEmpty()); + parent::assertFalse($metaObject->isEmpty()); } } diff --git a/tests/objects/RelationshipObjectTest.php b/tests/objects/RelationshipObjectTest.php index 8ce618d6..e35a0a51 100644 --- a/tests/objects/RelationshipObjectTest.php +++ b/tests/objects/RelationshipObjectTest.php @@ -8,29 +8,29 @@ use alsvanzelf\jsonapi\ResourceDocument; use alsvanzelf\jsonapi\enums\RelationshipTypeEnum; use alsvanzelf\jsonapi\exceptions\InputException; +use alsvanzelf\jsonapi\interfaces\ExtensionInterface; use alsvanzelf\jsonapi\objects\LinkObject; use alsvanzelf\jsonapi\objects\RelationshipObject; use alsvanzelf\jsonapi\objects\ResourceIdentifierObject; use alsvanzelf\jsonapi\objects\ResourceObject; -use alsvanzelf\jsonapiTests\extensions\TestExtension; use PHPUnit\Framework\TestCase; class RelationshipObjectTest extends TestCase { - public function testConstructor_ToOne() { + public function testConstructor_ToOne(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); $relationshipObject->setResource(new ResourceObject('user', 42)); $this->validateToOneRelationshipArray($relationshipObject->toArray()); } - public function testConstructor_ToMany() { + public function testConstructor_ToMany(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToMany); $relationshipObject->addResource(new ResourceObject('user', 42)); $this->validateToManyRelationshipArray($relationshipObject->toArray()); } - public function testFromAnything_WithResourceObject() { + public function testFromAnything_WithResourceObject(): void { $resourceObject = new ResourceObject('user', 42); $resourceObject->addMeta('foo', 'bar'); @@ -39,19 +39,19 @@ public function testFromAnything_WithResourceObject() { $this->validateToOneRelationshipArray($relationshipObject->toArray()); } - public function testFromAnything_WithResourceIdentifierObject() { + public function testFromAnything_WithResourceIdentifierObject(): void { $relationshipObject = RelationshipObject::fromAnything(new ResourceIdentifierObject('user', 42)); $this->validateToOneRelationshipArray($relationshipObject->toArray()); } - public function testFromAnything_WithResourceDocument() { + public function testFromAnything_WithResourceDocument(): void { $relationshipObject = RelationshipObject::fromAnything(new ResourceDocument('user', 42)); $this->validateToOneRelationshipArray($relationshipObject->toArray()); } - public function testFromAnything_WithCollectionDocument() { + public function testFromAnything_WithCollectionDocument(): void { $resourceObject = new ResourceObject('user', 42); $collectionDocument = CollectionDocument::fromResources($resourceObject); $relationshipObject = RelationshipObject::fromAnything($collectionDocument); @@ -59,29 +59,29 @@ public function testFromAnything_WithCollectionDocument() { $this->validateToManyRelationshipArray($relationshipObject->toArray()); } - public function testFromAnything_WithResourceObjects() { + public function testFromAnything_WithResourceObjects(): void { $relationshipObject = RelationshipObject::fromAnything([new ResourceObject('user', 42)]); $this->validateToManyRelationshipArray($relationshipObject->toArray()); } - public function testFromResource_ToMany() { + public function testFromResource_ToMany(): void { $resourceObject = new ResourceObject('user', 42); $type = RelationshipTypeEnum::ToMany; - $relationshipObject = RelationshipObject::fromResource($resourceObject, $links=[], $meta=[], $type); + $relationshipObject = RelationshipObject::fromResource($resourceObject, type: $type); $array = $relationshipObject->toArray(); - $this->assertArrayHasKey('data', $array); - $this->assertCount(1, $array['data']); - $this->assertArrayHasKey('type', $array['data'][0]); - $this->assertArrayHasKey('id', $array['data'][0]); - $this->assertSame('user', $array['data'][0]['type']); - $this->assertSame('42', $array['data'][0]['id']); + parent::assertArrayHasKey('data', $array); + parent::assertCount(1, $array['data']); + parent::assertArrayHasKey('type', $array['data'][0]); + parent::assertArrayHasKey('id', $array['data'][0]); + parent::assertSame('user', $array['data'][0]['type']); + parent::assertSame('42', $array['data'][0]['id']); } - public function testFromResource_WithLinks() { + public function testFromResource_WithLinks(): void { $resourceObject = new ResourceObject('user', 42); $links = ['self' => 'https://jsonapi.org']; @@ -89,63 +89,63 @@ public function testFromResource_WithLinks() { $array = $relationshipObject->toArray(); - $this->assertArrayHasKey('links', $array); - $this->assertCount(1, $array['links']); - $this->assertArrayHasKey('self', $array['links']); - $this->assertSame('https://jsonapi.org', $array['links']['self']); + parent::assertArrayHasKey('links', $array); + parent::assertCount(1, $array['links']); + parent::assertArrayHasKey('self', $array['links']); + parent::assertSame('https://jsonapi.org', $array['links']['self']); } - public function testFromResource_WithMeta() { + public function testFromResource_WithMeta(): void { $resourceObject = new ResourceObject('user', 42); $meta = ['foo' => 'bar']; - $relationshipObject = RelationshipObject::fromResource($resourceObject, $links=[], $meta); + $relationshipObject = RelationshipObject::fromResource($resourceObject, meta: $meta); $array = $relationshipObject->toArray(); - $this->assertArrayHasKey('meta', $array); - $this->assertCount(1, $array['meta']); - $this->assertArrayHasKey('foo', $array['meta']); - $this->assertSame('bar', $array['meta']['foo']); + parent::assertArrayHasKey('meta', $array); + parent::assertCount(1, $array['meta']); + parent::assertArrayHasKey('foo', $array['meta']); + parent::assertSame('bar', $array['meta']['foo']); } - public function testFromCollectionDocument_WithMeta() { + public function testFromCollectionDocument_WithMeta(): void { $collectionDocument = CollectionDocument::fromResources(new ResourceObject('user', 42)); $meta = ['foo' => 'bar']; - $relationshipObject = RelationshipObject::fromCollectionDocument($collectionDocument, $links=[], $meta); + $relationshipObject = RelationshipObject::fromCollectionDocument($collectionDocument, meta: $meta); $array = $relationshipObject->toArray(); - $this->assertArrayHasKey('meta', $array); - $this->assertCount(1, $array['meta']); - $this->assertArrayHasKey('foo', $array['meta']); - $this->assertSame('bar', $array['meta']['foo']); + parent::assertArrayHasKey('meta', $array); + parent::assertCount(1, $array['meta']); + parent::assertArrayHasKey('foo', $array['meta']); + parent::assertSame('bar', $array['meta']['foo']); } - public function testSetSelfLink_HappyPath() { + public function testSetSelfLink_HappyPath(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); $relationshipObject->setSelfLink('https://jsonapi.org'); $array = $relationshipObject->toArray(); - $this->assertArrayHasKey('links', $array); - $this->assertArrayHasKey('self', $array['links']); - $this->assertSame('https://jsonapi.org', $array['links']['self']); + parent::assertArrayHasKey('links', $array); + parent::assertArrayHasKey('self', $array['links']); + parent::assertSame('https://jsonapi.org', $array['links']['self']); } - public function testSetRelatedLink_HappyPath() { + public function testSetRelatedLink_HappyPath(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); $relationshipObject->setRelatedLink('https://jsonapi.org'); $array = $relationshipObject->toArray(); - $this->assertArrayHasKey('links', $array); - $this->assertArrayHasKey('related', $array['links']); - $this->assertSame('https://jsonapi.org', $array['links']['related']); + parent::assertArrayHasKey('links', $array); + parent::assertArrayHasKey('related', $array['links']); + parent::assertSame('https://jsonapi.org', $array['links']['related']); } - public function testSetPaginationLinks_HappyPath() { + public function testSetPaginationLinks_HappyPath(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToMany); $baseUrl = 'https://jsonapi.org/?page='; @@ -153,19 +153,19 @@ public function testSetPaginationLinks_HappyPath() { $array = $relationshipObject->toArray(); - $this->assertArrayHasKey('links', $array); - $this->assertCount(4, $array['links']); - $this->assertArrayHasKey('prev', $array['links']); - $this->assertArrayHasKey('next', $array['links']); - $this->assertArrayHasKey('first', $array['links']); - $this->assertArrayHasKey('last', $array['links']); - $this->assertSame($baseUrl.'prev', $array['links']['prev']); - $this->assertSame($baseUrl.'next', $array['links']['next']); - $this->assertSame($baseUrl.'first', $array['links']['first']); - $this->assertSame($baseUrl.'last', $array['links']['last']); + parent::assertArrayHasKey('links', $array); + parent::assertCount(4, $array['links']); + parent::assertArrayHasKey('prev', $array['links']); + parent::assertArrayHasKey('next', $array['links']); + parent::assertArrayHasKey('first', $array['links']); + parent::assertArrayHasKey('last', $array['links']); + parent::assertSame($baseUrl.'prev', $array['links']['prev']); + parent::assertSame($baseUrl.'next', $array['links']['next']); + parent::assertSame($baseUrl.'first', $array['links']['first']); + parent::assertSame($baseUrl.'last', $array['links']['last']); } - public function testSetPaginationLinks_BlockedOnToOne() { + public function testSetPaginationLinks_BlockedOnToOne(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); $this->expectException(InputException::class); @@ -173,63 +173,63 @@ public function testSetPaginationLinks_BlockedOnToOne() { $relationshipObject->setPaginationLinks('foo'); } - public function testAddMeta_HappyPath() { + public function testAddMeta_HappyPath(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); - $this->assertTrue($relationshipObject->isEmpty()); + parent::assertTrue($relationshipObject->isEmpty()); $relationshipObject->addMeta('foo', 'bar'); - $this->assertFalse($relationshipObject->isEmpty()); + parent::assertFalse($relationshipObject->isEmpty()); $array = $relationshipObject->toArray(); - $this->assertArrayHasKey('meta', $array); - $this->assertArrayHasKey('foo', $array['meta']); - $this->assertSame('bar', $array['meta']['foo']); + parent::assertArrayHasKey('meta', $array); + parent::assertArrayHasKey('foo', $array['meta']); + parent::assertSame('bar', $array['meta']['foo']); } - public function testHasResource_ToMany() { + public function testHasResource_ToMany(): void { $resourceObject = new ResourceObject('user', 42); $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToMany); $relationshipObject->addResource($resourceObject); - $this->assertTrue($relationshipObject->hasResource($resourceObject)); - $this->assertTrue($relationshipObject->hasResource(new ResourceObject('user', 42))); - $this->assertFalse($relationshipObject->hasResource(new ResourceObject('user', 24))); + parent::assertTrue($relationshipObject->hasResource($resourceObject)); + parent::assertTrue($relationshipObject->hasResource(new ResourceObject('user', 42))); + parent::assertFalse($relationshipObject->hasResource(new ResourceObject('user', 24))); } - public function testGetContainedResources_SkipsResourceIdentifierObjects() { + public function testGetContainedResources_SkipsResourceIdentifierObjects(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToMany); $resourceIdentifierObject = new ResourceIdentifierObject('user', 24); $resourceObjectIdentifierOnly = new ResourceObject('user', 42); $resourceObjectWithAttributes = new ResourceObject('user', 42); $resourceObjectWithAttributes->add('foo', 'bar'); - $this->assertCount(0, $relationshipObject->getNestedContainedResourceObjects()); + parent::assertCount(0, $relationshipObject->getNestedContainedResourceObjects()); $relationshipObject->addResource($resourceIdentifierObject); - $this->assertCount(0, $relationshipObject->getNestedContainedResourceObjects()); + parent::assertCount(0, $relationshipObject->getNestedContainedResourceObjects()); $relationshipObject->addResource($resourceObjectIdentifierOnly); - $this->assertCount(0, $relationshipObject->getNestedContainedResourceObjects()); + parent::assertCount(0, $relationshipObject->getNestedContainedResourceObjects()); $relationshipObject->addResource($resourceObjectWithAttributes); - $this->assertCount(1, $relationshipObject->getNestedContainedResourceObjects()); + parent::assertCount(1, $relationshipObject->getNestedContainedResourceObjects()); } - public function testSetResource_HappyPath() { + public function testSetResource_HappyPath(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); $relationshipObject->setResource(new ResourceObject('user', 42)); $this->validateToOneRelationshipArray($relationshipObject->toArray()); } - public function testSetResource_RequiresToOneType() { + public function testSetResource_RequiresToOneType(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToMany); $this->expectException(InputException::class); @@ -237,14 +237,14 @@ public function testSetResource_RequiresToOneType() { $relationshipObject->setResource(new ResourceObject('user', 42)); } - public function testAddResource_HappyPath() { + public function testAddResource_HappyPath(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToMany); $relationshipObject->addResource(new ResourceObject('user', 42)); $this->validateToManyRelationshipArray($relationshipObject->toArray()); } - public function testAddResource_RequiresToOneType() { + public function testAddResource_RequiresToOneType(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); $this->expectException(InputException::class); @@ -252,82 +252,82 @@ public function testAddResource_RequiresToOneType() { $relationshipObject->addResource(new ResourceObject('user', 42)); } - public function testAddLinkObject_HappyPath() { + public function testAddLinkObject_HappyPath(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); - $this->assertTrue($relationshipObject->isEmpty()); + parent::assertTrue($relationshipObject->isEmpty()); $relationshipObject->addLinkObject('foo', new LinkObject('https://jsonapi.org')); - $this->assertFalse($relationshipObject->isEmpty()); + parent::assertFalse($relationshipObject->isEmpty()); $array = $relationshipObject->toArray(); - $this->assertArrayHasKey('links', $array); - $this->assertArrayHasKey('foo', $array['links']); - $this->assertArrayHasKey('href', $array['links']['foo']); - $this->assertArrayNotHasKey('meta', $array['links']['foo']); - $this->assertSame('https://jsonapi.org', $array['links']['foo']['href']); + parent::assertArrayHasKey('links', $array); + parent::assertArrayHasKey('foo', $array['links']); + parent::assertArrayHasKey('href', $array['links']['foo']); + parent::assertArrayNotHasKey('meta', $array['links']['foo']); + parent::assertSame('https://jsonapi.org', $array['links']['foo']['href']); } - public function testToArray_EmptyResource() { + public function testToArray_EmptyResource(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); $array = $relationshipObject->toArray(); - $this->assertArrayHasKey('data', $array); - $this->assertNull($array['data']); + parent::assertArrayHasKey('data', $array); + parent::assertNull($array['data']); } - public function testToArray_EmptyResources() { + public function testToArray_EmptyResources(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToMany); $array = $relationshipObject->toArray(); - $this->assertArrayHasKey('data', $array); - $this->assertIsArray($array['data']); + parent::assertArrayHasKey('data', $array); + parent::assertIsArray($array['data']); } - public function testIsEmpty_WithAtMembers() { + public function testIsEmpty_WithAtMembers(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); - $this->assertTrue($relationshipObject->isEmpty()); + parent::assertTrue($relationshipObject->isEmpty()); $relationshipObject->addAtMember('context', 'test'); - $this->assertFalse($relationshipObject->isEmpty()); + parent::assertFalse($relationshipObject->isEmpty()); } /** * @group Extensions */ - public function testIsEmpty_WithExtensionMembers() { + public function testIsEmpty_WithExtensionMembers(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); - $this->assertTrue($relationshipObject->isEmpty()); + parent::assertTrue($relationshipObject->isEmpty()); - $relationshipObject->addExtensionMember(new TestExtension(), 'foo', 'bar'); + $relationshipObject->addExtensionMember(parent::createStub(ExtensionInterface::class), 'foo', 'bar'); - $this->assertFalse($relationshipObject->isEmpty()); + parent::assertFalse($relationshipObject->isEmpty()); } private function validateToOneRelationshipArray(array $array) { - $this->assertNotEmpty($array); - $this->assertArrayHasKey('data', $array); - $this->assertArrayHasKey('type', $array['data']); - $this->assertArrayHasKey('id', $array['data']); - $this->assertSame('user', $array['data']['type']); - $this->assertSame('42', $array['data']['id']); + parent::assertNotEmpty($array); + parent::assertArrayHasKey('data', $array); + parent::assertArrayHasKey('type', $array['data']); + parent::assertArrayHasKey('id', $array['data']); + parent::assertSame('user', $array['data']['type']); + parent::assertSame('42', $array['data']['id']); } private function validateToManyRelationshipArray(array $array) { - $this->assertNotEmpty($array); - $this->assertArrayHasKey('data', $array); - $this->assertCount(1, $array['data']); - $this->assertArrayHasKey(0, $array['data']); - $this->assertArrayHasKey('type', $array['data'][0]); - $this->assertArrayHasKey('id', $array['data'][0]); - $this->assertSame('user', $array['data'][0]['type']); - $this->assertSame('42', $array['data'][0]['id']); + parent::assertNotEmpty($array); + parent::assertArrayHasKey('data', $array); + parent::assertCount(1, $array['data']); + parent::assertArrayHasKey(0, $array['data']); + parent::assertArrayHasKey('type', $array['data'][0]); + parent::assertArrayHasKey('id', $array['data'][0]); + parent::assertSame('user', $array['data'][0]['type']); + parent::assertSame('42', $array['data'][0]['id']); } } diff --git a/tests/objects/RelationshipsObjectTest.php b/tests/objects/RelationshipsObjectTest.php index 9c98b613..6b7f0af3 100644 --- a/tests/objects/RelationshipsObjectTest.php +++ b/tests/objects/RelationshipsObjectTest.php @@ -13,39 +13,39 @@ use PHPUnit\Framework\TestCase; class RelationshipsObjectTest extends TestCase { - public function testAdd_HappyPath() { + public function testAdd_HappyPath(): void { $relationshipsObject = new RelationshipsObject(); $relationshipsObject->add('foo', new ResourceObject('user', 42)); $array = $relationshipsObject->toArray(); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertArrayHasKey('data', $array['foo']); - $this->assertArrayHasKey('type', $array['foo']['data']); - $this->assertArrayHasKey('id', $array['foo']['data']); - $this->assertSame('user', $array['foo']['data']['type']); - $this->assertSame('42', $array['foo']['data']['id']); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertArrayHasKey('data', $array['foo']); + parent::assertArrayHasKey('type', $array['foo']['data']); + parent::assertArrayHasKey('id', $array['foo']['data']); + parent::assertSame('user', $array['foo']['data']['type']); + parent::assertSame('42', $array['foo']['data']['id']); } - public function testAddRelationshipObject_HappyPath() { + public function testAddRelationshipObject_HappyPath(): void { $relationshipObject = RelationshipObject::fromAnything(new ResourceObject('user', 42)); $relationshipsObject = new RelationshipsObject(); - $relationshipsObject->addRelationshipObject($key='foo', $relationshipObject); + $relationshipsObject->addRelationshipObject('foo', $relationshipObject); $array = $relationshipsObject->toArray(); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertArrayHasKey('data', $array['foo']); - $this->assertArrayHasKey('type', $array['foo']['data']); - $this->assertArrayHasKey('id', $array['foo']['data']); - $this->assertSame('user', $array['foo']['data']['type']); - $this->assertSame('42', $array['foo']['data']['id']); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertArrayHasKey('data', $array['foo']); + parent::assertArrayHasKey('type', $array['foo']['data']); + parent::assertArrayHasKey('id', $array['foo']['data']); + parent::assertSame('user', $array['foo']['data']['type']); + parent::assertSame('42', $array['foo']['data']['id']); } - public function testAddRelationshipObject_WithPredefinedKey() { + public function testAddRelationshipObject_WithPredefinedKey(): void { $relationshipObject = RelationshipObject::fromAnything(new ResourceObject('user', 42)); $relationshipsObject = new RelationshipsObject(); @@ -53,61 +53,61 @@ public function testAddRelationshipObject_WithPredefinedKey() { $array = $relationshipsObject->toArray(); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertArrayHasKey('data', $array['foo']); - $this->assertArrayHasKey('type', $array['foo']['data']); - $this->assertArrayHasKey('id', $array['foo']['data']); - $this->assertSame('user', $array['foo']['data']['type']); - $this->assertSame('42', $array['foo']['data']['id']); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertArrayHasKey('data', $array['foo']); + parent::assertArrayHasKey('type', $array['foo']['data']); + parent::assertArrayHasKey('id', $array['foo']['data']); + parent::assertSame('user', $array['foo']['data']['type']); + parent::assertSame('42', $array['foo']['data']['id']); } - public function testAddRelationshipObject_InvalidKey() { + public function testAddRelationshipObject_InvalidKey(): void { $relationshipObject = RelationshipObject::fromAnything(new ResourceObject('user', 42)); $relationshipsObject = new RelationshipsObject(); $this->expectException(InputException::class); - $relationshipsObject->addRelationshipObject($key='-foo', $relationshipObject); + $relationshipsObject->addRelationshipObject('-foo', $relationshipObject); } - public function testAddRelationshipObject_MultipleRelationships() { + public function testAddRelationshipObject_MultipleRelationships(): void { $relationshipObject = RelationshipObject::fromAnything(new ResourceObject('user', 42)); $relationshipsObject = new RelationshipsObject(); - $relationshipsObject->addRelationshipObject($key='foo', $relationshipObject); - $relationshipsObject->addRelationshipObject($key='bar', $relationshipObject); + $relationshipsObject->addRelationshipObject('foo', $relationshipObject); + $relationshipsObject->addRelationshipObject('bar', $relationshipObject); $array = $relationshipsObject->toArray(); - $this->assertCount(2, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertArrayHasKey('bar', $array); + parent::assertCount(2, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertArrayHasKey('bar', $array); } - public function testAddRelationshipObject_MultipleReusingKeys() { + public function testAddRelationshipObject_MultipleReusingKeys(): void { $relationshipObject = RelationshipObject::fromAnything(new ResourceObject('user', 42)); $relationshipsObject = new RelationshipsObject(); - $relationshipsObject->addRelationshipObject($key='foo', $relationshipObject); + $relationshipsObject->addRelationshipObject('foo', $relationshipObject); $this->expectException(DuplicateException::class); - $relationshipsObject->addRelationshipObject($key='foo', $relationshipObject); + $relationshipsObject->addRelationshipObject('foo', $relationshipObject); } - public function testToArray_EmptyRelationship() { + public function testToArray_EmptyRelationship(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); $relationshipsObject = new RelationshipsObject(); - $relationshipsObject->addRelationshipObject($key='foo', $relationshipObject); + $relationshipsObject->addRelationshipObject('foo', $relationshipObject); $array = $relationshipsObject->toArray(); - $this->assertFalse($relationshipsObject->isEmpty()); - $this->assertCount(1, $array); - $this->assertArrayHasKey('foo', $array); - $this->assertArrayHasKey('data', $array['foo']); - $this->assertNull($array['foo']['data']); + parent::assertFalse($relationshipsObject->isEmpty()); + parent::assertCount(1, $array); + parent::assertArrayHasKey('foo', $array); + parent::assertArrayHasKey('data', $array['foo']); + parent::assertNull($array['foo']['data']); } } diff --git a/tests/objects/ResourceIdentifierObjectTest.php b/tests/objects/ResourceIdentifierObjectTest.php index 6383aa20..64e65ff2 100644 --- a/tests/objects/ResourceIdentifierObjectTest.php +++ b/tests/objects/ResourceIdentifierObjectTest.php @@ -4,26 +4,26 @@ namespace alsvanzelf\jsonapiTests\objects; -use alsvanzelf\jsonapi\exceptions\Exception; use alsvanzelf\jsonapi\exceptions\DuplicateException; +use alsvanzelf\jsonapi\exceptions\Exception; +use alsvanzelf\jsonapi\interfaces\ExtensionInterface; use alsvanzelf\jsonapi\objects\ResourceIdentifierObject; -use alsvanzelf\jsonapiTests\extensions\TestExtension; use PHPUnit\Framework\TestCase; class ResourceIdentifierObjectTest extends TestCase { - public function testSetId_HappyPath() { + public function testSetId_HappyPath(): void { $resourceIdentifierObject = new ResourceIdentifierObject(); $resourceIdentifierObject->setType('test'); $resourceIdentifierObject->setId('1'); $array = $resourceIdentifierObject->toArray(); - $this->assertArrayHasKey('id', $array); - $this->assertArrayNotHasKey('lid', $array); - $this->assertSame('1', $array['id']); + parent::assertArrayHasKey('id', $array); + parent::assertArrayNotHasKey('lid', $array); + parent::assertSame('1', $array['id']); } - public function testSetId_WithLocalIdAlreadySet() { + public function testSetId_WithLocalIdAlreadySet(): void { $resourceIdentifierObject = new ResourceIdentifierObject(); $resourceIdentifierObject->setType('test'); $resourceIdentifierObject->setLocalId('uuid-1'); @@ -33,19 +33,19 @@ public function testSetId_WithLocalIdAlreadySet() { $resourceIdentifierObject->setId('1'); } - public function testSetLocalId_HappyPath() { + public function testSetLocalId_HappyPath(): void { $resourceIdentifierObject = new ResourceIdentifierObject(); $resourceIdentifierObject->setType('test'); $resourceIdentifierObject->setLocalId('uuid-1'); $array = $resourceIdentifierObject->toArray(); - $this->assertArrayHasKey('lid', $array); - $this->assertArrayNotHasKey('id', $array); - $this->assertSame('uuid-1', $array['lid']); + parent::assertArrayHasKey('lid', $array); + parent::assertArrayNotHasKey('id', $array); + parent::assertSame('uuid-1', $array['lid']); } - public function testSetLocalId_WithIdAlreadySet() { + public function testSetLocalId_WithIdAlreadySet(): void { $resourceIdentifierObject = new ResourceIdentifierObject(); $resourceIdentifierObject->setType('test'); $resourceIdentifierObject->setId('1'); @@ -55,16 +55,16 @@ public function testSetLocalId_WithIdAlreadySet() { $resourceIdentifierObject->setLocalId('uuid-1'); } - public function testEquals_HappyPath() { + public function testEquals_HappyPath(): void { $one = new ResourceIdentifierObject('test', 1); $two = new ResourceIdentifierObject('test', 2); $new = new ResourceIdentifierObject('test', 1); - $this->assertFalse($one->equals($two)); - $this->assertTrue($one->equals($new)); + parent::assertFalse($one->equals($two)); + parent::assertTrue($one->equals($new)); } - public function testEquals_WithoutIdentification() { + public function testEquals_WithoutIdentification(): void { $one = new ResourceIdentifierObject('test', 1); $two = new ResourceIdentifierObject(); @@ -73,7 +73,7 @@ public function testEquals_WithoutIdentification() { $one->equals($two); } - public function testEquals_WithLocalId() { + public function testEquals_WithLocalId(): void { $one = new ResourceIdentifierObject('test'); $two = new ResourceIdentifierObject('test'); $new = new ResourceIdentifierObject('test'); @@ -82,46 +82,46 @@ public function testEquals_WithLocalId() { $two->setLocalId('uuid-2'); $new->setLocalId('uuid-1'); - $this->assertFalse($one->equals($two)); - $this->assertTrue($one->equals($new)); + parent::assertFalse($one->equals($two)); + parent::assertTrue($one->equals($new)); } - public function testGetIdentificationKey_HappyPath() { + public function testGetIdentificationKey_HappyPath(): void { $resourceIdentifierObject = new ResourceIdentifierObject('user', 42); $array = $resourceIdentifierObject->toArray(); - $this->assertArrayHasKey('type', $array); - $this->assertArrayHasKey('id', $array); - $this->assertArrayNotHasKey('lid', $array); - $this->assertSame('user', $array['type']); - $this->assertSame('42', $array['id']); - $this->assertTrue($resourceIdentifierObject->hasIdentification()); - $this->assertSame('user|42', $resourceIdentifierObject->getIdentificationKey()); + parent::assertArrayHasKey('type', $array); + parent::assertArrayHasKey('id', $array); + parent::assertArrayNotHasKey('lid', $array); + parent::assertSame('user', $array['type']); + parent::assertSame('42', $array['id']); + parent::assertTrue($resourceIdentifierObject->hasIdentification()); + parent::assertSame('user|42', $resourceIdentifierObject->getIdentificationKey()); } - public function testGetIdentificationKey_SetAfterwards() { + public function testGetIdentificationKey_SetAfterwards(): void { $resourceIdentifierObject = new ResourceIdentifierObject(); - $this->assertFalse($resourceIdentifierObject->hasIdentification()); + parent::assertFalse($resourceIdentifierObject->hasIdentification()); $resourceIdentifierObject->setType('user'); - $this->assertFalse($resourceIdentifierObject->hasIdentification()); + parent::assertFalse($resourceIdentifierObject->hasIdentification()); $resourceIdentifierObject->setId(42); $array = $resourceIdentifierObject->toArray(); - $this->assertArrayHasKey('type', $array); - $this->assertArrayHasKey('id', $array); - $this->assertSame('user', $array['type']); - $this->assertSame('42', $array['id']); - $this->assertTrue($resourceIdentifierObject->hasIdentification()); - $this->assertSame('user|42', $resourceIdentifierObject->getIdentificationKey()); + parent::assertArrayHasKey('type', $array); + parent::assertArrayHasKey('id', $array); + parent::assertSame('user', $array['type']); + parent::assertSame('42', $array['id']); + parent::assertTrue($resourceIdentifierObject->hasIdentification()); + parent::assertSame('user|42', $resourceIdentifierObject->getIdentificationKey()); } - public function testGetIdentificationKey_WithLocalId() { + public function testGetIdentificationKey_WithLocalId(): void { $resourceIdentifierObject = new ResourceIdentifierObject(); $resourceIdentifierObject->setType('user'); @@ -129,65 +129,65 @@ public function testGetIdentificationKey_WithLocalId() { $array = $resourceIdentifierObject->toArray(); - $this->assertArrayHasKey('type', $array); - $this->assertArrayHasKey('lid', $array); - $this->assertArrayNotHasKey('id', $array); - $this->assertSame('user', $array['type']); - $this->assertSame('uuid-42', $array['lid']); - $this->assertTrue($resourceIdentifierObject->hasIdentification()); - $this->assertSame('user|uuid-42', $resourceIdentifierObject->getIdentificationKey()); + parent::assertArrayHasKey('type', $array); + parent::assertArrayHasKey('lid', $array); + parent::assertArrayNotHasKey('id', $array); + parent::assertSame('user', $array['type']); + parent::assertSame('uuid-42', $array['lid']); + parent::assertTrue($resourceIdentifierObject->hasIdentification()); + parent::assertSame('user|uuid-42', $resourceIdentifierObject->getIdentificationKey()); } - public function testGetIdentificationKey_NoIdentification() { + public function testGetIdentificationKey_NoIdentification(): void { $resourceIdentifierObject = new ResourceIdentifierObject(); $array = $resourceIdentifierObject->toArray(); - $this->assertArrayNotHasKey('type', $array); - $this->assertArrayNotHasKey('id', $array); - $this->assertSame([], $array); - $this->assertFalse($resourceIdentifierObject->hasIdentification()); + parent::assertArrayNotHasKey('type', $array); + parent::assertArrayNotHasKey('id', $array); + parent::assertSame([], $array); + parent::assertFalse($resourceIdentifierObject->hasIdentification()); $this->expectException(Exception::class); $resourceIdentifierObject->getIdentificationKey(); } - public function testGetIdentificationKey_NoFullIdentification() { + public function testGetIdentificationKey_NoFullIdentification(): void { $resourceIdentifierObject = new ResourceIdentifierObject('user'); $array = $resourceIdentifierObject->toArray(); - $this->assertArrayHasKey('type', $array); - $this->assertArrayNotHasKey('id', $array); - $this->assertSame('user', $array['type']); - $this->assertFalse($resourceIdentifierObject->hasIdentification()); + parent::assertArrayHasKey('type', $array); + parent::assertArrayNotHasKey('id', $array); + parent::assertSame('user', $array['type']); + parent::assertFalse($resourceIdentifierObject->hasIdentification()); $this->expectException(Exception::class); $resourceIdentifierObject->getIdentificationKey(); } - public function testIsEmpty_WithAtMembers() { + public function testIsEmpty_WithAtMembers(): void { $resourceIdentifierObject = new ResourceIdentifierObject(); - $this->assertTrue($resourceIdentifierObject->isEmpty()); + parent::assertTrue($resourceIdentifierObject->isEmpty()); $resourceIdentifierObject->addAtMember('context', 'test'); - $this->assertFalse($resourceIdentifierObject->isEmpty()); + parent::assertFalse($resourceIdentifierObject->isEmpty()); } /** * @group Extensions */ - public function testIsEmpty_WithExtensionMembers() { + public function testIsEmpty_WithExtensionMembers(): void { $resourceIdentifierObject = new ResourceIdentifierObject(); - $this->assertTrue($resourceIdentifierObject->isEmpty()); + parent::assertTrue($resourceIdentifierObject->isEmpty()); - $resourceIdentifierObject->addExtensionMember(new TestExtension(), 'foo', 'bar'); + $resourceIdentifierObject->addExtensionMember(parent::createStub(ExtensionInterface::class), 'foo', 'bar'); - $this->assertFalse($resourceIdentifierObject->isEmpty()); + parent::assertFalse($resourceIdentifierObject->isEmpty()); } } diff --git a/tests/objects/ResourceObjectTest.php b/tests/objects/ResourceObjectTest.php index 693c8595..0b1410f9 100644 --- a/tests/objects/ResourceObjectTest.php +++ b/tests/objects/ResourceObjectTest.php @@ -15,17 +15,17 @@ use PHPUnit\Framework\TestCase; class ResourceObjectTest extends TestCase { - public function testConstructor_ClientDocumentWithoutId() { + public function testConstructor_ClientDocumentWithoutId(): void { $resourceObject = new ResourceObject('user'); $resourceObject->add('foo', 'bar'); $array = $resourceObject->toArray(); - $this->assertArrayNotHasKey('id', $array); - $this->assertArrayHasKey('attributes', $array); + parent::assertArrayNotHasKey('id', $array); + parent::assertArrayHasKey('attributes', $array); } - public function testFromArray_WithoutId() { + public function testFromArray_WithoutId(): void { $type = 'user'; $id = null; $attributes = [ @@ -36,13 +36,13 @@ public function testFromArray_WithoutId() { $array = $resourceObject->toArray(); - $this->assertArrayNotHasKey('id', $array); - $this->assertArrayHasKey('attributes', $array); - $this->assertArrayHasKey('foo', $array['attributes']); - $this->assertSame('bar', $array['attributes']['foo']); + parent::assertArrayNotHasKey('id', $array); + parent::assertArrayHasKey('attributes', $array); + parent::assertArrayHasKey('foo', $array['attributes']); + parent::assertSame('bar', $array['attributes']['foo']); } - public function testFromArray_IdViaArgument() { + public function testFromArray_IdViaArgument(): void { $type = 'user'; $id = 42; $attributes = [ @@ -52,14 +52,14 @@ public function testFromArray_IdViaArgument() { $array = $resourceObject->toArray(); - $this->assertArrayHasKey('id', $array); - $this->assertArrayHasKey('attributes', $array); - $this->assertArrayHasKey('foo', $array['attributes']); - $this->assertSame('42', $array['id']); - $this->assertSame('bar', $array['attributes']['foo']); + parent::assertArrayHasKey('id', $array); + parent::assertArrayHasKey('attributes', $array); + parent::assertArrayHasKey('foo', $array['attributes']); + parent::assertSame('42', $array['id']); + parent::assertSame('bar', $array['attributes']['foo']); } - public function testFromArray_IdViaAttributes() { + public function testFromArray_IdViaAttributes(): void { $type = 'user'; $id = null; $attributes = [ @@ -70,66 +70,66 @@ public function testFromArray_IdViaAttributes() { $array = $resourceObject->toArray(); - $this->assertArrayHasKey('id', $array); - $this->assertArrayHasKey('attributes', $array); - $this->assertArrayHasKey('foo', $array['attributes']); - $this->assertArrayNotHasKey('id', $array['attributes']); - $this->assertSame('42', $array['id']); - $this->assertSame('bar', $array['attributes']['foo']); + parent::assertArrayHasKey('id', $array); + parent::assertArrayHasKey('attributes', $array); + parent::assertArrayHasKey('foo', $array['attributes']); + parent::assertArrayNotHasKey('id', $array['attributes']); + parent::assertSame('42', $array['id']); + parent::assertSame('bar', $array['attributes']['foo']); } - public function testHasIdentifierPropertiesOnly_Yes() { + public function testHasIdentifierPropertiesOnly_Yes(): void { $resourceObject = new ResourceObject('user', 42); - $this->assertTrue($resourceObject->hasIdentifierPropertiesOnly()); + parent::assertTrue($resourceObject->hasIdentifierPropertiesOnly()); $resourceObject = new ResourceObject(); - $this->assertTrue($resourceObject->hasIdentifierPropertiesOnly()); + parent::assertTrue($resourceObject->hasIdentifierPropertiesOnly()); $resourceObject = new ResourceObject('user', 42); $resourceObject->setAttributesObject(new AttributesObject()); - $this->assertTrue($resourceObject->hasIdentifierPropertiesOnly()); + parent::assertTrue($resourceObject->hasIdentifierPropertiesOnly()); $resourceObject = new ResourceObject('user', 42); $resourceObject->setRelationshipsObject(new RelationshipsObject()); - $this->assertTrue($resourceObject->hasIdentifierPropertiesOnly()); + parent::assertTrue($resourceObject->hasIdentifierPropertiesOnly()); $resourceObject = new ResourceObject('user', 42); $resourceObject->setLinksObject(new LinksObject()); - $this->assertTrue($resourceObject->hasIdentifierPropertiesOnly()); + parent::assertTrue($resourceObject->hasIdentifierPropertiesOnly()); $resourceObject = new ResourceObject('user', 42); $resourceObject->setAttributesObject(new AttributesObject()); $resourceObject->setRelationshipsObject(new RelationshipsObject()); $resourceObject->setLinksObject(new LinksObject()); - $this->assertTrue($resourceObject->hasIdentifierPropertiesOnly()); + parent::assertTrue($resourceObject->hasIdentifierPropertiesOnly()); } - public function testHasIdentifierPropertiesOnly_No() { + public function testHasIdentifierPropertiesOnly_No(): void { $resourceObject = new ResourceObject('user', 42); $resourceObject->add('foo', 'bar'); - $this->assertFalse($resourceObject->hasIdentifierPropertiesOnly()); + parent::assertFalse($resourceObject->hasIdentifierPropertiesOnly()); $resourceObject = new ResourceObject('user', 42); $resourceObject->addRelationship('foo', new ResourceObject('user', 24)); - $this->assertFalse($resourceObject->hasIdentifierPropertiesOnly()); + parent::assertFalse($resourceObject->hasIdentifierPropertiesOnly()); $resourceObject = new ResourceObject('user', 42); $resourceObject->addLink('foo', 'https://jsonapi.org'); - $this->assertFalse($resourceObject->hasIdentifierPropertiesOnly()); + parent::assertFalse($resourceObject->hasIdentifierPropertiesOnly()); $resourceObject = new ResourceObject('user', 42); $resourceObject->addLinkObject('foo', new LinkObject()); - $this->assertFalse($resourceObject->hasIdentifierPropertiesOnly()); + parent::assertFalse($resourceObject->hasIdentifierPropertiesOnly()); $resourceObject = new ResourceObject('user', 42); $resourceObject->add('foo', 'bar'); $resourceObject->addRelationship('baz', new ResourceObject('user', 24)); $resourceObject->addLink('foo', 'https://jsonapi.org'); $resourceObject->addLinkObject('bar', new LinkObject()); - $this->assertFalse($resourceObject->hasIdentifierPropertiesOnly()); + parent::assertFalse($resourceObject->hasIdentifierPropertiesOnly()); } - public function testAddRelationshipObject_HappyPath() { + public function testAddRelationshipObject_HappyPath(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); $relationshipObject->setResource(new ResourceObject('user', 42)); @@ -138,22 +138,22 @@ public function testAddRelationshipObject_HappyPath() { $array = $resourceObject->toArray(); - $this->assertArrayHasKey('type', $array); - $this->assertArrayHasKey('id', $array); - $this->assertSame('user', $array['type']); - $this->assertSame('24', $array['id']); - - $this->assertArrayHasKey('relationships', $array); - $this->assertCount(1, $array['relationships']); - $this->assertArrayHasKey('foo', $array['relationships']); - $this->assertArrayHasKey('data', $array['relationships']['foo']); - $this->assertArrayHasKey('type', $array['relationships']['foo']['data']); - $this->assertArrayHasKey('id', $array['relationships']['foo']['data']); - $this->assertSame('user', $array['relationships']['foo']['data']['type']); - $this->assertSame('42', $array['relationships']['foo']['data']['id']); + parent::assertArrayHasKey('type', $array); + parent::assertArrayHasKey('id', $array); + parent::assertSame('user', $array['type']); + parent::assertSame('24', $array['id']); + + parent::assertArrayHasKey('relationships', $array); + parent::assertCount(1, $array['relationships']); + parent::assertArrayHasKey('foo', $array['relationships']); + parent::assertArrayHasKey('data', $array['relationships']['foo']); + parent::assertArrayHasKey('type', $array['relationships']['foo']['data']); + parent::assertArrayHasKey('id', $array['relationships']['foo']['data']); + parent::assertSame('user', $array['relationships']['foo']['data']['type']); + parent::assertSame('42', $array['relationships']['foo']['data']['id']); } - public function testAddRelationshipObject_BlockDrosteEffect() { + public function testAddRelationshipObject_BlockDrosteEffect(): void { $relationshipObject = new RelationshipObject(RelationshipTypeEnum::ToOne); $relationshipObject->setResource(new ResourceObject('user', 42)); @@ -164,23 +164,23 @@ public function testAddRelationshipObject_BlockDrosteEffect() { $resourceObject->addRelationshipObject('foo', $relationshipObject); } - public function testIsEmpty_All() { + public function testIsEmpty_All(): void { $resourceObject = new ResourceObject(); - $this->assertTrue($resourceObject->isEmpty()); + parent::assertTrue($resourceObject->isEmpty()); $resourceObject = new ResourceObject('user', 42); - $this->assertFalse($resourceObject->isEmpty()); + parent::assertFalse($resourceObject->isEmpty()); $resourceObject = new ResourceObject(); $resourceObject->add('foo', 'bar'); - $this->assertFalse($resourceObject->isEmpty()); + parent::assertFalse($resourceObject->isEmpty()); $resourceObject = new ResourceObject('test', 1); $resourceObject->addRelationship('foo', new ResourceObject('user', 24)); - $this->assertFalse($resourceObject->isEmpty()); + parent::assertFalse($resourceObject->isEmpty()); $resourceObject = new ResourceObject(); $resourceObject->addLink('foo', 'https://jsonapi.org'); - $this->assertFalse($resourceObject->isEmpty()); + parent::assertFalse($resourceObject->isEmpty()); } } diff --git a/tests/profiles/CursorPaginationProfileTest.php b/tests/profiles/CursorPaginationProfileTest.php index 5b9a8c2a..42250a6d 100644 --- a/tests/profiles/CursorPaginationProfileTest.php +++ b/tests/profiles/CursorPaginationProfileTest.php @@ -15,7 +15,7 @@ * @group Profiles */ class CursorPaginationProfileTest extends TestCase { - public function testSetLinks_HappyPath() { + public function testSetLinks_HappyPath(): void { $profile = new CursorPaginationProfile(); $collection = new CollectionDocument(); $baseOrCurrentUrl = '/people?page[size]=10'; @@ -27,22 +27,22 @@ public function testSetLinks_HappyPath() { $array = $collection->toArray(); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayHasKey('profile', $array['jsonapi']); - $this->assertCount(1, $array['jsonapi']['profile']); - $this->assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); - - $this->assertArrayHasKey('links', $array); - $this->assertCount(2, $array['links']); - $this->assertArrayHasKey('prev', $array['links']); - $this->assertArrayHasKey('next', $array['links']); - $this->assertArrayHasKey('href', $array['links']['prev']); - $this->assertArrayHasKey('href', $array['links']['next']); - $this->assertSame('/people?page[size]=10&page[before]='.$firstCursor, $array['links']['prev']['href']); - $this->assertSame('/people?page[size]=10&page[after]='.$lastCursor, $array['links']['next']['href']); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayHasKey('profile', $array['jsonapi']); + parent::assertCount(1, $array['jsonapi']['profile']); + parent::assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); + + parent::assertArrayHasKey('links', $array); + parent::assertCount(2, $array['links']); + parent::assertArrayHasKey('prev', $array['links']); + parent::assertArrayHasKey('next', $array['links']); + parent::assertArrayHasKey('href', $array['links']['prev']); + parent::assertArrayHasKey('href', $array['links']['next']); + parent::assertSame('/people?page[size]=10&page[before]='.$firstCursor, $array['links']['prev']['href']); + parent::assertSame('/people?page[size]=10&page[after]='.$lastCursor, $array['links']['next']['href']); } - public function test_WithRelationship() { + public function test_WithRelationship(): void { $profile = new CursorPaginationProfile(); $document = new ResourceDocument('test', 1); $document->applyProfile($profile); @@ -68,32 +68,32 @@ public function test_WithRelationship() { $array = $document->toArray(); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayHasKey('profile', $array['jsonapi']); - $this->assertCount(1, $array['jsonapi']['profile']); - $this->assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); - - $this->assertArrayHasKey('data', $array); - $this->assertArrayHasKey('relationships', $array['data']); - $this->assertArrayHasKey('people', $array['data']['relationships']); - $this->assertArrayHasKey('links', $array['data']['relationships']['people']); - $this->assertArrayHasKey('data', $array['data']['relationships']['people']); - $this->assertArrayHasKey('meta', $array['data']['relationships']['people']); - $this->assertArrayHasKey('prev', $array['data']['relationships']['people']['links']); - $this->assertArrayHasKey('next', $array['data']['relationships']['people']['links']); - $this->assertArrayHasKey('page', $array['data']['relationships']['people']['meta']); - $this->assertArrayHasKey('href', $array['data']['relationships']['people']['links']['prev']); - $this->assertArrayHasKey('href', $array['data']['relationships']['people']['links']['next']); - $this->assertArrayHasKey('total', $array['data']['relationships']['people']['meta']['page']); - $this->assertArrayHasKey('estimatedTotal', $array['data']['relationships']['people']['meta']['page']); - $this->assertArrayHasKey('bestGuess', $array['data']['relationships']['people']['meta']['page']['estimatedTotal']); - $this->assertCount(3, $array['data']['relationships']['people']['data']); - $this->assertArrayHasKey('meta', $array['data']['relationships']['people']['data'][0]); - $this->assertArrayHasKey('page', $array['data']['relationships']['people']['data'][0]['meta']); - $this->assertArrayHasKey('cursor', $array['data']['relationships']['people']['data'][0]['meta']['page']); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayHasKey('profile', $array['jsonapi']); + parent::assertCount(1, $array['jsonapi']['profile']); + parent::assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); + + parent::assertArrayHasKey('data', $array); + parent::assertArrayHasKey('relationships', $array['data']); + parent::assertArrayHasKey('people', $array['data']['relationships']); + parent::assertArrayHasKey('links', $array['data']['relationships']['people']); + parent::assertArrayHasKey('data', $array['data']['relationships']['people']); + parent::assertArrayHasKey('meta', $array['data']['relationships']['people']); + parent::assertArrayHasKey('prev', $array['data']['relationships']['people']['links']); + parent::assertArrayHasKey('next', $array['data']['relationships']['people']['links']); + parent::assertArrayHasKey('page', $array['data']['relationships']['people']['meta']); + parent::assertArrayHasKey('href', $array['data']['relationships']['people']['links']['prev']); + parent::assertArrayHasKey('href', $array['data']['relationships']['people']['links']['next']); + parent::assertArrayHasKey('total', $array['data']['relationships']['people']['meta']['page']); + parent::assertArrayHasKey('estimatedTotal', $array['data']['relationships']['people']['meta']['page']); + parent::assertArrayHasKey('bestGuess', $array['data']['relationships']['people']['meta']['page']['estimatedTotal']); + parent::assertCount(3, $array['data']['relationships']['people']['data']); + parent::assertArrayHasKey('meta', $array['data']['relationships']['people']['data'][0]); + parent::assertArrayHasKey('page', $array['data']['relationships']['people']['data'][0]['meta']); + parent::assertArrayHasKey('cursor', $array['data']['relationships']['people']['data'][0]['meta']['page']); } - public function testSetLinksFirstPage_HappyPath() { + public function testSetLinksFirstPage_HappyPath(): void { $profile = new CursorPaginationProfile(); $collection = new CollectionDocument(); $baseOrCurrentUrl = '/people?page[size]=10'; @@ -104,21 +104,21 @@ public function testSetLinksFirstPage_HappyPath() { $array = $collection->toArray(); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayHasKey('profile', $array['jsonapi']); - $this->assertCount(1, $array['jsonapi']['profile']); - $this->assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); - - $this->assertArrayHasKey('links', $array); - $this->assertCount(2, $array['links']); - $this->assertArrayHasKey('prev', $array['links']); - $this->assertArrayHasKey('next', $array['links']); - $this->assertNull($array['links']['prev']); - $this->assertArrayHasKey('href', $array['links']['next']); - $this->assertSame('/people?page[size]=10&page[after]='.$lastCursor, $array['links']['next']['href']); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayHasKey('profile', $array['jsonapi']); + parent::assertCount(1, $array['jsonapi']['profile']); + parent::assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); + + parent::assertArrayHasKey('links', $array); + parent::assertCount(2, $array['links']); + parent::assertArrayHasKey('prev', $array['links']); + parent::assertArrayHasKey('next', $array['links']); + parent::assertNull($array['links']['prev']); + parent::assertArrayHasKey('href', $array['links']['next']); + parent::assertSame('/people?page[size]=10&page[after]='.$lastCursor, $array['links']['next']['href']); } - public function testSetLinksLastPage_HappyPath() { + public function testSetLinksLastPage_HappyPath(): void { $profile = new CursorPaginationProfile(); $collection = new CollectionDocument(); $baseOrCurrentUrl = '/people?page[size]=10'; @@ -129,21 +129,21 @@ public function testSetLinksLastPage_HappyPath() { $array = $collection->toArray(); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayHasKey('profile', $array['jsonapi']); - $this->assertCount(1, $array['jsonapi']['profile']); - $this->assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); - - $this->assertArrayHasKey('links', $array); - $this->assertCount(2, $array['links']); - $this->assertArrayHasKey('prev', $array['links']); - $this->assertArrayHasKey('next', $array['links']); - $this->assertArrayHasKey('href', $array['links']['prev']); - $this->assertNull($array['links']['next']); - $this->assertSame('/people?page[size]=10&page[before]='.$firstCursor, $array['links']['prev']['href']); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayHasKey('profile', $array['jsonapi']); + parent::assertCount(1, $array['jsonapi']['profile']); + parent::assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); + + parent::assertArrayHasKey('links', $array); + parent::assertCount(2, $array['links']); + parent::assertArrayHasKey('prev', $array['links']); + parent::assertArrayHasKey('next', $array['links']); + parent::assertArrayHasKey('href', $array['links']['prev']); + parent::assertNull($array['links']['next']); + parent::assertSame('/people?page[size]=10&page[before]='.$firstCursor, $array['links']['prev']['href']); } - public function testSetCursor() { + public function testSetCursor(): void { $profile = new CursorPaginationProfile(); $resourceDocument = new ResourceDocument('user', 42); @@ -152,19 +152,19 @@ public function testSetCursor() { $array = $resourceDocument->toArray(); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayHasKey('profile', $array['jsonapi']); - $this->assertCount(1, $array['jsonapi']['profile']); - $this->assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayHasKey('profile', $array['jsonapi']); + parent::assertCount(1, $array['jsonapi']['profile']); + parent::assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); - $this->assertArrayHasKey('data', $array); - $this->assertArrayHasKey('meta', $array['data']); - $this->assertArrayHasKey('page', $array['data']['meta']); - $this->assertArrayHasKey('cursor', $array['data']['meta']['page']); - $this->assertSame('foo', $array['data']['meta']['page']['cursor']); + parent::assertArrayHasKey('data', $array); + parent::assertArrayHasKey('meta', $array['data']); + parent::assertArrayHasKey('page', $array['data']['meta']); + parent::assertArrayHasKey('cursor', $array['data']['meta']['page']); + parent::assertSame('foo', $array['data']['meta']['page']['cursor']); } - public function testSetPaginationLinkObjectsExplicitlyEmpty_HapptPath() { + public function testSetPaginationLinkObjectsExplicitlyEmpty_HapptPath(): void { $profile = new CursorPaginationProfile(); $collection = new CollectionDocument(); @@ -173,20 +173,20 @@ public function testSetPaginationLinkObjectsExplicitlyEmpty_HapptPath() { $array = $collection->toArray(); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayHasKey('profile', $array['jsonapi']); - $this->assertCount(1, $array['jsonapi']['profile']); - $this->assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); - - $this->assertArrayHasKey('links', $array); - $this->assertCount(2, $array['links']); - $this->assertArrayHasKey('prev', $array['links']); - $this->assertArrayHasKey('next', $array['links']); - $this->assertNull($array['links']['prev']); - $this->assertNull($array['links']['next']); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayHasKey('profile', $array['jsonapi']); + parent::assertCount(1, $array['jsonapi']['profile']); + parent::assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); + + parent::assertArrayHasKey('links', $array); + parent::assertCount(2, $array['links']); + parent::assertArrayHasKey('prev', $array['links']); + parent::assertArrayHasKey('next', $array['links']); + parent::assertNull($array['links']['prev']); + parent::assertNull($array['links']['next']); } - public function testSetPaginationMeta() { + public function testSetPaginationMeta(): void { $profile = new CursorPaginationProfile(); $collection = new CollectionDocument(); $exactTotal = 42; @@ -198,23 +198,23 @@ public function testSetPaginationMeta() { $array = $collection->toArray(); - $this->assertArrayHasKey('jsonapi', $array); - $this->assertArrayHasKey('profile', $array['jsonapi']); - $this->assertCount(1, $array['jsonapi']['profile']); - $this->assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); - - $this->assertArrayHasKey('meta', $array); - $this->assertArrayHasKey('page', $array['meta']); - $this->assertArrayHasKey('total', $array['meta']['page']); - $this->assertArrayHasKey('estimatedTotal', $array['meta']['page']); - $this->assertArrayHasKey('bestGuess', $array['meta']['page']['estimatedTotal']); - $this->assertArrayHasKey('rangeTruncated', $array['meta']['page']); - $this->assertSame(42, $array['meta']['page']['total']); - $this->assertSame(100, $array['meta']['page']['estimatedTotal']['bestGuess']); - $this->assertTrue($array['meta']['page']['rangeTruncated']); + parent::assertArrayHasKey('jsonapi', $array); + parent::assertArrayHasKey('profile', $array['jsonapi']); + parent::assertCount(1, $array['jsonapi']['profile']); + parent::assertSame($profile->getOfficialLink(), $array['jsonapi']['profile'][0]); + + parent::assertArrayHasKey('meta', $array); + parent::assertArrayHasKey('page', $array['meta']); + parent::assertArrayHasKey('total', $array['meta']['page']); + parent::assertArrayHasKey('estimatedTotal', $array['meta']['page']); + parent::assertArrayHasKey('bestGuess', $array['meta']['page']['estimatedTotal']); + parent::assertArrayHasKey('rangeTruncated', $array['meta']['page']); + parent::assertSame(42, $array['meta']['page']['total']); + parent::assertSame(100, $array['meta']['page']['estimatedTotal']['bestGuess']); + parent::assertTrue($array['meta']['page']['rangeTruncated']); } - public function testGetUnsupportedSortErrorObject_HappyPath() { + public function testGetUnsupportedSortErrorObject_HappyPath(): void { $profile = new CursorPaginationProfile(); $genericTitle = 'foo'; $specificDetails = 'bar'; @@ -223,23 +223,23 @@ public function testGetUnsupportedSortErrorObject_HappyPath() { $array = $errorObject->toArray(); - $this->assertArrayHasKey('status', $array); - $this->assertArrayHasKey('code', $array); - $this->assertArrayHasKey('title', $array); - $this->assertArrayHasKey('detail', $array); - $this->assertArrayHasKey('links', $array); - $this->assertArrayHasKey('type', $array['links']); - $this->assertArrayHasKey('source', $array); - $this->assertArrayHasKey('parameter', $array['source']); - $this->assertSame('400', $array['status']); - $this->assertSame('Unsupported sort', $array['code']); - $this->assertSame($genericTitle, $array['title']); - $this->assertSame($specificDetails, $array['detail']); - $this->assertSame('https://jsonapi.org/profiles/ethanresnick/cursor-pagination/unsupported-sort', $array['links']['type']); - $this->assertSame('sort', $array['source']['parameter']); + parent::assertArrayHasKey('status', $array); + parent::assertArrayHasKey('code', $array); + parent::assertArrayHasKey('title', $array); + parent::assertArrayHasKey('detail', $array); + parent::assertArrayHasKey('links', $array); + parent::assertArrayHasKey('type', $array['links']); + parent::assertArrayHasKey('source', $array); + parent::assertArrayHasKey('parameter', $array['source']); + parent::assertSame('400', $array['status']); + parent::assertSame('Unsupported sort', $array['code']); + parent::assertSame($genericTitle, $array['title']); + parent::assertSame($specificDetails, $array['detail']); + parent::assertSame('https://jsonapi.org/profiles/ethanresnick/cursor-pagination/unsupported-sort', $array['links']['type']); + parent::assertSame('sort', $array['source']['parameter']); } - public function testGetMaxPageSizeExceededErrorObject_HappyPath() { + public function testGetMaxPageSizeExceededErrorObject_HappyPath(): void { $profile = new CursorPaginationProfile(); $maxSize = 42; $genericTitle = 'foo'; @@ -249,27 +249,27 @@ public function testGetMaxPageSizeExceededErrorObject_HappyPath() { $array = $errorObject->toArray(); - $this->assertArrayHasKey('status', $array); - $this->assertArrayHasKey('code', $array); - $this->assertArrayHasKey('title', $array); - $this->assertArrayHasKey('detail', $array); - $this->assertArrayHasKey('links', $array); - $this->assertArrayHasKey('type', $array['links']); - $this->assertArrayHasKey('source', $array); - $this->assertArrayHasKey('parameter', $array['source']); - $this->assertArrayHasKey('meta', $array); - $this->assertArrayHasKey('page', $array['meta']); - $this->assertArrayHasKey('maxSize', $array['meta']['page']); - $this->assertSame('400', $array['status']); - $this->assertSame('Max page size exceeded', $array['code']); - $this->assertSame($genericTitle, $array['title']); - $this->assertSame($specificDetails, $array['detail']); - $this->assertSame('page[size]', $array['source']['parameter']); - $this->assertSame('https://jsonapi.org/profiles/ethanresnick/cursor-pagination/max-size-exceeded', $array['links']['type']); - $this->assertSame(42, $array['meta']['page']['maxSize']); + parent::assertArrayHasKey('status', $array); + parent::assertArrayHasKey('code', $array); + parent::assertArrayHasKey('title', $array); + parent::assertArrayHasKey('detail', $array); + parent::assertArrayHasKey('links', $array); + parent::assertArrayHasKey('type', $array['links']); + parent::assertArrayHasKey('source', $array); + parent::assertArrayHasKey('parameter', $array['source']); + parent::assertArrayHasKey('meta', $array); + parent::assertArrayHasKey('page', $array['meta']); + parent::assertArrayHasKey('maxSize', $array['meta']['page']); + parent::assertSame('400', $array['status']); + parent::assertSame('Max page size exceeded', $array['code']); + parent::assertSame($genericTitle, $array['title']); + parent::assertSame($specificDetails, $array['detail']); + parent::assertSame('page[size]', $array['source']['parameter']); + parent::assertSame('https://jsonapi.org/profiles/ethanresnick/cursor-pagination/max-size-exceeded', $array['links']['type']); + parent::assertSame(42, $array['meta']['page']['maxSize']); } - public function testGetInvalidParameterValueErrorObject_HappyPath() { + public function testGetInvalidParameterValueErrorObject_HappyPath(): void { $profile = new CursorPaginationProfile(); $queryParameter = 'page[size]'; $typeLink = 'https://jsonapi.org'; @@ -280,23 +280,23 @@ public function testGetInvalidParameterValueErrorObject_HappyPath() { $array = $errorObject->toArray(); - $this->assertArrayHasKey('status', $array); - $this->assertArrayHasKey('code', $array); - $this->assertArrayHasKey('title', $array); - $this->assertArrayHasKey('detail', $array); - $this->assertArrayHasKey('links', $array); - $this->assertArrayHasKey('type', $array['links']); - $this->assertArrayHasKey('source', $array); - $this->assertArrayHasKey('parameter', $array['source']); - $this->assertSame('400', $array['status']); - $this->assertSame('Invalid parameter value', $array['code']); - $this->assertSame($genericTitle, $array['title']); - $this->assertSame($specificDetails, $array['detail']); - $this->assertSame('page[size]', $array['source']['parameter']); - $this->assertSame('https://jsonapi.org', $array['links']['type']); + parent::assertArrayHasKey('status', $array); + parent::assertArrayHasKey('code', $array); + parent::assertArrayHasKey('title', $array); + parent::assertArrayHasKey('detail', $array); + parent::assertArrayHasKey('links', $array); + parent::assertArrayHasKey('type', $array['links']); + parent::assertArrayHasKey('source', $array); + parent::assertArrayHasKey('parameter', $array['source']); + parent::assertSame('400', $array['status']); + parent::assertSame('Invalid parameter value', $array['code']); + parent::assertSame($genericTitle, $array['title']); + parent::assertSame($specificDetails, $array['detail']); + parent::assertSame('page[size]', $array['source']['parameter']); + parent::assertSame('https://jsonapi.org', $array['links']['type']); } - public function testGetRangePaginationNotSupportedErrorObject_HappyPath() { + public function testGetRangePaginationNotSupportedErrorObject_HappyPath(): void { $profile = new CursorPaginationProfile(); $genericTitle = 'foo'; $specificDetails = 'bar'; @@ -305,20 +305,20 @@ public function testGetRangePaginationNotSupportedErrorObject_HappyPath() { $array = $errorObject->toArray(); - $this->assertArrayHasKey('status', $array); - $this->assertArrayHasKey('code', $array); - $this->assertArrayHasKey('title', $array); - $this->assertArrayHasKey('detail', $array); - $this->assertArrayHasKey('links', $array); - $this->assertArrayHasKey('type', $array['links']); - $this->assertSame('400', $array['status']); - $this->assertSame('Range pagination not supported', $array['code']); - $this->assertSame($genericTitle, $array['title']); - $this->assertSame($specificDetails, $array['detail']); - $this->assertSame('https://jsonapi.org/profiles/ethanresnick/cursor-pagination/range-pagination-not-supported', $array['links']['type']); + parent::assertArrayHasKey('status', $array); + parent::assertArrayHasKey('code', $array); + parent::assertArrayHasKey('title', $array); + parent::assertArrayHasKey('detail', $array); + parent::assertArrayHasKey('links', $array); + parent::assertArrayHasKey('type', $array['links']); + parent::assertSame('400', $array['status']); + parent::assertSame('Range pagination not supported', $array['code']); + parent::assertSame($genericTitle, $array['title']); + parent::assertSame($specificDetails, $array['detail']); + parent::assertSame('https://jsonapi.org/profiles/ethanresnick/cursor-pagination/range-pagination-not-supported', $array['links']['type']); } - public function testSetQueryParameter_HappyPath() { + public function testSetQueryParameter_HappyPath(): void { $profile = new CursorPaginationProfile(); $method = new \ReflectionMethod($profile, 'setQueryParameter'); @@ -328,10 +328,10 @@ public function testSetQueryParameter_HappyPath() { $newUrl = $method->invoke($profile, $url, $key, $value); - $this->assertSame('/people?sort=x&page[size]=10&page[after]=bar', $newUrl); + parent::assertSame('/people?sort=x&page[size]=10&page[after]=bar', $newUrl); } - public function testSetQueryParameter_EncodedUrl() { + public function testSetQueryParameter_EncodedUrl(): void { $profile = new CursorPaginationProfile(); $method = new \ReflectionMethod($profile, 'setQueryParameter'); @@ -341,6 +341,6 @@ public function testSetQueryParameter_EncodedUrl() { $newUrl = $method->invoke($profile, $url, $key, $value); - $this->assertSame('/people?sort=x&page%5Bsize%5D=10&page%5Bafter%5D=bar', $newUrl); + parent::assertSame('/people?sort=x&page%5Bsize%5D=10&page%5Bafter%5D=bar', $newUrl); } } diff --git a/tests/profiles/TestProfile.php b/tests/profiles/TestProfile.php deleted file mode 100644 index 6b0b5d27..00000000 --- a/tests/profiles/TestProfile.php +++ /dev/null @@ -1,19 +0,0 @@ -officialLink = $officialLink; - } - - public function getOfficialLink(): string { - return $this->officialLink; - } -}