Compare commits

..

No commits in common. "master" and "v0.1.0-beta.1" have entirely different histories.

76 changed files with 3075 additions and 18404 deletions

View File

@ -1,88 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.2.0] - 2022-06-21
### Fixed
- Fix `EloquentAdapter::filterByIds()` getting key name from query model instead of adapter model
- Fix deprecation notice on PHP 8.1
## [0.2.0-beta.6] - 2022-04-22
### Changed
- Add support for `doctrine/inflector:^2.0`
## [0.2.0-beta.5] - 2022-01-03
### Added
- `Context::getBody()` method to retrieve the parsed JSON:API payload from the request
- `Context::sortRequested()` method to determine if a sort field has been requested
### Fixed
- `Laravel\rules()`: Fix regression disallowing use of advanced validation rules like callbacks and `Rule` instances. (@SychO9)
## [0.2.0-beta.4] - 2021-09-05
### Added
- `Laravel\rules()`: Replace `{id}` placeholder in rules with the model's key.
- This is useful for the `unique` rule, for example: `unique:users,email,{id}`
- `Laravel\can()`: Pass through additional arguments to Gate check.
- This is needed to use policy methods without models, for example: `can('create', Post::class)`
### Changed
- Get a fresh copy of the model to display after create/update to ensure consistency
- Respond with `400 Bad Request` when attempting to filter on an attribute of a polymorphic relationship
## [0.2.0-beta.3] - 2021-09-03
### Fixed
- Fix dependency on `http-accept` now that a version has been tagged
- Change `EloquentAdapter` to load relationships using `load` instead of `loadMissing`, as they may need API-specific scopes applied
## [0.2.0-beta.2] - 2021-09-01
### Added
- Content-Type validation and Accept negotiation
- Include `jsonapi` object with `version` member in response
- Validate implementation-specific query parameters according to specification
- Added `Location` header to `201 Created` responses
- Improved error responses when creating and updating resources
- `Context::filter()` method to get the value of a filter
- `ResourceType::applyScope()`, `applyFilter()` and `applySort()` methods
- `ResourceType::url()` method to get the URL for a model
- `Forbidden` error details for CRUD actions, useful when running Atomic Operations
- `JsonApi::getExtensions()` method to get all registered extensions
- `ConflictException` class
### Changed
- Renamed `$linkage` parameter in `AdapterInterface` methods to `$linkageOnly`
- Renamed `Type::newModel()` to `model()` to be consistent with Adapter
### Fixed
- Properly respond with meta information added to `Context` instance
## [0.2.0-beta.1] - 2021-08-27
### Added
- Preliminary support for Extensions
- Support filtering by nested relationships/attributes (eg. `filter[relationship.attribute]=value`)
- Add new methods to Context object: `getApi`, `getPath`, `fieldRequested`, `meta`
- Eloquent adapter: apply scopes when including polymorphic relationships
- Laravel validation helper: support nested validation messages
- Allow configuration of sort and filter visibility
- Add new `setId` method to `AdapterInterface`
### Changed
- Change paradigm for eager loading relationships; allow fields to return `Deferred` values to be evaluated after all other fields, so that resource loading can be buffered.
- Remove `on` prefix from field event methods
### Removed
- Removed `load` and `dontLoad` field methods
### Fixed
- Fix pagination next link appearing when it shouldn't
[0.2.0]: https://github.com/tobyzerner/json-api-server/compare/v0.2.0...v0.2.0-beta.6
[0.2.0-beta.6]: https://github.com/tobyzerner/json-api-server/compare/v0.2.0-beta.6...v0.2.0-beta.5
[0.2.0-beta.5]: https://github.com/tobyzerner/json-api-server/compare/v0.2.0-beta.5...v0.2.0-beta.4
[0.2.0-beta.4]: https://github.com/tobyzerner/json-api-server/compare/v0.2.0-beta.4...v0.2.0-beta.3
[0.2.0-beta.3]: https://github.com/tobyzerner/json-api-server/compare/v0.2.0-beta.3...v0.2.0-beta.2
[0.2.0-beta.2]: https://github.com/tobyzerner/json-api-server/compare/v0.2.0-beta.2...v0.2.0-beta.1
[0.2.0-beta.1]: https://github.com/tobyzerner/json-api-server/compare/v0.2.0-beta.1...v0.1.0-beta.1

View File

@ -5,20 +5,7 @@
json-api-server is a [JSON:API](http://jsonapi.org) server implementation in PHP.
It allows you to define your API's schema, and then use an [adapter](adapters.md) to connect it to your application's database layer. You don't have to worry about any of the server boilerplate, routing, query parameters, or JSON:API document formatting.
Based on your schema definition, the package will serve a **complete JSON:API that conforms to the [spec](https://jsonapi.org/format/)**, including support for:
- **Showing** individual resources (`GET /api/articles/1`)
- **Listing** resource collections (`GET /api/articles`)
- **Sorting**, **filtering**, **pagination**, and **sparse fieldsets**
- **Compound documents** with inclusion of related resources
- **Creating** resources (`POST /api/articles`)
- **Updating** resources (`PATCH /api/articles/1`)
- **Deleting** resources (`DELETE /api/articles/1`)
- **Error handling**
The schema definition is extremely powerful and lets you easily apply [permissions](visibility.md), [transformations](writing.md#transformers), [validation](writing.md#validation), and custom [filtering](filtering.md) and [sorting](sorting.md) logic to build a fully functional API with ease.
Build an API in minutes by defining your API's schema and connecting it to your application's models. json-api-server takes care of all the boilerplate stuff like routing, query parameters, and building a valid JSON:API document.
## Documentation

View File

@ -3,13 +3,11 @@
"description": "A fully automated JSON:API server implementation in PHP.",
"require": {
"php": ">=7.1",
"ext-json": "*",
"doctrine/inflector": "^1.4 || ^2.0",
"doctrine/inflector": "^1.3",
"json-api-php/json-api": "^2.2",
"nyholm/psr7": "^1.3",
"psr/http-message": "^1.0",
"psr/http-server-handler": "^1.0",
"hnet/http-accept": "^0.1"
"psr/http-server-handler": "^1.0"
},
"license": "MIT",
"authors": [

View File

@ -50,12 +50,11 @@ module.exports = {
collapsable: false,
children: [
'errors',
'extensions',
'laravel',
]
}
],
repo: 'tobyzerner/json-api-server',
repo: 'tobyz/json-api-server',
editLinks: true,
docsDir: 'docs'
}

View File

@ -1 +0,0 @@
$accentColor = #0000ff

View File

@ -7,7 +7,7 @@ You'll need to supply an adapter for each [resource type](https://jsonapi.org/fo
```php
use Tobyz\JsonApiServer\Schema\Type;
$api->resourceType('users', $adapter, function (Type $type) {
$api->resource('users', $adapter, function (Type $type) {
// define your schema
});
```
@ -26,12 +26,12 @@ $adapter = new EloquentAdapter(User::class);
When using the Eloquent Adapter, the `$model` passed around in the schema will be an instance of the given model, and the `$query` will be a `Illuminate\Database\Eloquent\Builder` instance querying the model's table:
```php
$type->scope(function (Builder $query) {});
$type->scope(function (Builder $query) { });
$type->attribute('name')
->get(function (User $user) {});
->get(function (User $user) { });
```
### Custom Adapters
For other ORMs or data persistence layers, you can [implement your own adapter](https://github.com/tobyzerner/json-api-server/blob/master/src/Adapter/AdapterInterface.php).
For other ORMs or data persistence layers, you can [implement your own adapter](https://github.com/tobyz/json-api-server/blob/master/src/Adapter/AdapterInterface.php).

View File

@ -14,32 +14,32 @@ $type->creatable(function (Context $context) {
## Customizing the Model
When creating a resource, an empty model is supplied by the adapter. You may wish to override this and provide a custom model in special circumstances. You can do so using the `model` method:
When creating a resource, an empty model is supplied by the adapter. You may wish to override this and provide a custom model in special circumstances. You can do so using the `newModel` method:
```php
$type->model(function (Context $context) {
$type->newModel(function (Context $context) {
return new CustomModel;
});
```
## Events
### `creating`
### `onCreating`
Run after values have been set on the model, but before it is saved.
Run before the model is saved.
```php
$type->creating(function (&$model, Context $context) {
$type->onCreating(function (&$model, Context $context) {
// do something
});
```
### `created`
### `onCreated`
Run after the model is saved, and before it is shown in a JSON:API document.
Run after the model is saved.
```php
$type->created(function (&$model, Context $context) {
$type->onCreated(function (&$model, Context $context) {
$context->meta('foo', 'bar');
});
```

View File

@ -14,22 +14,22 @@ $type->deletable(function (Context $context) {
## Events
### `deleting`
### `onDeleting`
Run before the model is deleted.
```php
$type->deleting(function (&$model, Context $context) {
$type->onDeleting(function (&$model, Context $context) {
// do something
});
```
### `deleted`
### `onDeleted`
Run after the model is deleted.
```php
$type->deleted(function (&$model, Context $context) {
$type->onDeleted(function (&$model, Context $context) {
// do something
});
```

View File

@ -1,79 +0,0 @@
# Extensions
[Extensions](https://jsonapi.org/format/1.1/#extensions) allow your API to support additional functionality that is not part of the base specification.
## Defining Extensions
Extensions can be defined by extending the `Tobyz\JsonApiServer\Extension\Extension` class and implementing two methods: `uri` and `process`.
You must return your extension's unique URI from `uri`.
For every request that includes your extension in the media type, the `handle` method will be called. If your extension is able to handle the request, it should return a PSR-7 response. Otherwise, return null to let the normal handling of the request take place.
```php
use Tobyz\JsonApiServer\Extension\Extension;
use Psr\Http\Message\ResponseInterface;
use function Tobyz\JsonApiServer\json_api_response;
class MyExtension extends Extension
{
public function uri(): string
{
return 'https://example.org/my-extension';
}
public function handle(Context $context): ?ResponseInterface;
{
if ($context->getPath() === '/my-extension') {
return json_api_response([
'my-extension:greeting' => 'Hello world!'
]);
}
return null;
}
}
```
::: warning
The current implementation of extensions has no support for augmentation of standard API responses. This API may change dramatically in the future. Please [create an issue](https://github.com/tobyzerner/json-api-server/issues/new) if you have a specific use-case you want to achieve.
:::
## Registering Extensions
Extensions can be registered on your `JsonApi` instance using the `extension` method:
```php
use Tobyz\JsonApiServer\JsonApi;
$api = new JsonApi('/api');
$api->extension(new MyExtension());
```
The `JsonApi` class will automatically perform appropriate [content negotiation](https://jsonapi.org/format/1.1/#content-negotiation-servers) and activate the specified extensions on each request.
## Atomic Operations
An implementation of the [Atomic Operations](https://jsonapi.org/ext/atomic/) extension is available at `Tobyz\JsonApi\Extension\Atomic`.
When using this extension, you are responsible for wrapping the `$api->handle` call in a transaction to ensure any database (or other) operations performed are actually atomic in nature. For example, in Laravel:
```php
use Illuminate\Support\Facades\DB;
use Tobyz\JsonApiServer\Extension\Atomic;
use Tobyz\JsonApiServer\JsonApi;
$api = new JsonApi('/api');
$api->extension(new Atomic());
/** @var Psr\Http\Message\ServerRequestInterface $request */
/** @var Psr\Http\Message\ResponseInterface $response */
try {
return DB::transaction(fn() => $api->handle($request));
} catch (Exception $e) {
$response = $api->error($e);
}
```

View File

@ -23,7 +23,7 @@ GET /users?filter[postCount]=5..15
## Custom Filters
To define filters with custom logic, or ones that do not correspond to a field, use the `filter` method:
To define filters with custom logic, or ones that do not correspond to an attribute, use the `filter` method:
```php
$type->filter('minPosts', function ($query, $value, Context $context) {
@ -34,7 +34,7 @@ $type->filter('minPosts', function ($query, $value, Context $context) {
Just like [fields](visibility.md), filters can be made conditionally `visible` or `hidden`:
```php
$type->filter('minPosts', $callback)
$type->filter('email', $callback)
->visible(function (Context $context) {
return $context->getRequest()->getAttribute('isAdmin');
});

View File

@ -2,7 +2,7 @@
json-api-server is a [JSON:API](http://jsonapi.org) server implementation in PHP.
It allows you to define your API's schema, and then use an [adapter](adapters.md) to connect it to your application's database layer. You don't have to worry about any of the server boilerplate, routing, query parameters, or JSON:API document formatting.
It allows you to define your API's schema, and then use an [adapter](adapters.md) to connect it to your application's models and database layer, without having to worry about any of the server boilerplate, routing, query parameters, or JSON:API document formatting.
Based on your schema definition, the package will serve a **complete JSON:API that conforms to the [spec](https://jsonapi.org/format/)**, including support for:
@ -15,7 +15,7 @@ Based on your schema definition, the package will serve a **complete JSON:API th
- **Deleting** resources (`DELETE /api/articles/1`)
- **Error handling**
The schema definition is extremely powerful and lets you easily apply [permissions](visibility.md), [transformations](writing.md#transformers), [validation](writing.md#validation), and custom [filtering](filtering.md) and [sorting](sorting.md) logic to build a fully functional API with ease.
The schema definition is extremely powerful and lets you easily apply [permissions](visibility.md), [transformations](writing.md#transformers), [validation](writing.md#validation), and custom [filtering](filtering.md) and [sorting](sorting.md) logic to build a fully functional API in minutes.
### Example
@ -25,18 +25,17 @@ The following example uses Eloquent models in a Laravel application. However, js
use App\Models\{Article, Comment, User};
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\Schema\Type;
use Tobyz\JsonApiServer\Adapter\EloquentAdapter;
use Tobyz\JsonApiServer\Laravel\EloquentAdapter;
use Tobyz\JsonApiServer\Laravel;
$api = new JsonApi('http://example.com/api');
$api->resourceType('articles', new EloquentAdapter(Article::class), function (Type $type) {
$api->resource('articles', new EloquentAdapter(Article::class), function (Type $type) {
$type->attribute('title')
->writable()
->validate(Laravel\rules('required'));
$type->hasOne('author')
->type('users')
$type->hasOne('author')->type('users')
->includable()
->filterable();
@ -44,7 +43,7 @@ $api->resourceType('articles', new EloquentAdapter(Article::class), function (Ty
->includable();
});
$api->resourceType('comments', new EloquentAdapter(Comment::class), function (Type $type) {
$api->resource('comments', new EloquentAdapter(Comment::class), function (Type $type) {
$type->creatable(Laravel\authenticated());
$type->updatable(Laravel\can('update-comment'));
$type->deletable(Laravel\can('delete-comment'));
@ -57,13 +56,12 @@ $api->resourceType('comments', new EloquentAdapter(Comment::class), function (Ty
->writable()->once()
->validate(Laravel\rules('required'));
$type->hasOne('author')
->type('users')
$type->hasOne('author')->type('users')
->writable()->once()
->validate(Laravel\rules('required'));
});
$api->resourceType('users', new EloquentAdapter(User::class), function (Type $type) {
$api->resource('users', new EloquentAdapter(User::class), function (Type $type) {
$type->attribute('firstName')->sortable();
$type->attribute('lastName')->sortable();
});

View File

@ -1,7 +1,5 @@
# Laravel Helpers
These helpers improve the ergonomics of your API resource definitions when using the Laravel framework.
## Validation
### `rules`
@ -12,20 +10,10 @@ Use Laravel's [Validation component](https://laravel.com/docs/8.x/validation) as
use Tobyz\JsonApiServer\Laravel;
$type->attribute('name')
->validate(Laravel\rules(['required', 'min:3', 'max:20']));
->validate(Laravel\rules('required|min:3|max:20'));
```
Pass a string or array of validation rules to be applied to the value. Validating array contents is also supported:
```php
$type->attribute('jobs')
->validate(Laravel\rules([
'required', 'array',
'*' => ['string', 'min:3', 'max:255']
]));
```
You can also pass an array of custom messages and custom attribute names as the second and third arguments.
Pass a string or array of validation rules to be applied to the value. You can also pass an array of custom messages and custom attribute names as the second and third arguments.
## Authentication

View File

@ -14,22 +14,22 @@ $type->listable(function (Context $context) {
## Events
### `listing`
### `onListing`
Run before [scopes](scopes.md) are applied to the `$query` and results are retrieved.
```php
$type->listing(function ($query, Context $context) {
$type->onListing(function ($query, Context $context) {
// do something
});
```
### `listed`
### `onListed`
Run after models and relationships have been retrieved, but before they are serialized into a JSON:API document.
```php
$type->listed(function ($models, Context $context) {
$type->onListed(function ($models, Context $context) {
// do something
});
```

View File

@ -6,10 +6,10 @@ You can add meta information at various levels of the document using the `meta`
To add meta information at the top-level of a document, you can call the `meta` method on the `Context` instance which is available inside any of your schema's callbacks.
For example, to add meta information to a resource listing, you might call this inside of an `listed` listener:
For example, to add meta information to a resource listing, you might call this inside of an `onListed` listener:
```php
$type->listed(function ($models, Context $context) {
$type->onListed(function ($models, Context $context) {
$context->meta('foo', 'bar');
});
```

View File

@ -59,6 +59,14 @@ $type->hasOne('users')
});
```
To prevent a relationship from being eager-loaded, use the `dontLoad` method:
```php
$type->hasOne('user')
->includable()
->dontLoad();
```
## Polymorphic Relationships
Define a polymorphic relationship using the `polymorphic` method. Optionally you may provide an array of allowed resource types:
@ -71,6 +79,10 @@ $type->hasMany('taggable')
->polymorphic(['photos', 'videos']);
```
::: warning
Note that nested includes cannot be requested on polymorphic relationships.
:::
## Meta Information
You can add meta information to a relationship using the `meta` method:

View File

@ -31,43 +31,3 @@ Often you will need to access information about the authenticated user inside of
```php
$request = $request->withAttribute('user', $user);
```
## Context
An instance of `Tobyz\JsonApi\Context` is passed into callbacks throughout your API's resource definitions for example, when defining [scopes](scopes):
```php
use Tobyz\JsonApiServer\Context;
$type->scope(function ($query, Context $context) {
$user = $context->getRequest()->getAttribute('user');
$query->where('user_id', $user?->id);
});
```
This object contains a number of useful methods:
* `getApi(): Tobyz\JsonApi\JsonApi`
Get the JsonApi instance.
* `getRequest(): Psr\Http\Message\ServerRequestInterface`
Get the PSR-7 request instance.
* `getPath(): string`
Get the request path relative to the API's base path.
* `getBody(): ?array`
Get the parsed JSON:API payload.
* `fieldRequested(string $type, string $field, bool $default = true): bool`
Determine whether a field has been requested in a [sparse fieldset](https://jsonapi.org/format/1.1/#fetching-sparse-fieldsets).
* `sortRequested(string $field): bool`
Determine whether a sort field has been requested.
* `filter(string $name): ?string`
Get the value of a filter.
* `meta(string $name, $value): Tobyz\JsonApi\Schema\Meta`
Add a meta attribute to the response document.

View File

@ -4,12 +4,12 @@ For each resource type, a `GET /{type}/{id}` endpoint is exposed to show an indi
## Events
### `show`
### `onShow`
Run after the model has been retrieved, but before it is serialized into a JSON:API document.
Run after models and relationships have been retrieved, but before they are serialized into a JSON:API document.
```php
$type->show(function (&$model, Context $context) {
$type->onShow(function (&$model, Context $context) {
// do something
});
```

View File

@ -18,8 +18,6 @@ You can set a default sort string to be used when the consumer has not supplied
$type->defaultSort('-updatedAt,-createdAt');
```
## Custom Sorts
To define sort fields with custom logic, or ones that do not correspond to an attribute, use the `sort` method:
```php
@ -27,12 +25,3 @@ $type->sort('relevance', function ($query, string $direction, Context $context)
$query->orderBy('relevance', $direction);
});
```
Just like [fields](visibility.md), sorts can be made conditionally `visible` or `hidden`:
```php
$type->sort('relevance', $callback)
->visible(function (Context $context) {
return $context->getRequest()->getAttribute('isAdmin');
});
```

View File

@ -14,22 +14,22 @@ $type->updatable(function (Context $context) {
## Events
### `updating`
### `onUpdating`
Run after values have been set on the model, but before it is saved.
Run before the model is saved.
```php
$type->updating(function (&$model, Context $context) {
$type->onUpdating(function (&$model, Context $context) {
// do something
});
```
### `updated`
### `onUpdated`
Run after the model is saved, and before it is shown in a JSON:API document.
Run after the model is saved.
```php
$type->updated(function (&$model, Context $context) {
$type->onUpdated(function (&$model, Context $context) {
// do something
});
```

View File

@ -114,13 +114,13 @@ $type->attribute('locale')
## Events
### `saved`
### `onSaved`
Run after a field has been successfully saved.
```php
$type->attribute('email')
->saved(function ($value, $model, Context $context) {
->onSaved(function ($value, $model, Context $context) {
event(new EmailWasChanged($model));
});
```

17377
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -11,13 +11,9 @@
namespace Tobyz\JsonApiServer\Adapter;
use Closure;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Deferred;
use Tobyz\JsonApiServer\Schema\Attribute;
use Tobyz\JsonApiServer\Schema\HasMany;
use Tobyz\JsonApiServer\Schema\HasOne;
use Tobyz\JsonApiServer\Schema\Relationship;
interface AdapterInterface
{
@ -28,11 +24,17 @@ interface AdapterInterface
* or list a resource index. It will be passed around through the relevant
* scopes, filters, and sorting methods before finally being passed into
* the `find` or `get` methods.
*
* @return mixed
*/
public function query();
public function newQuery();
/**
* Manipulate the query to only include resources with the given IDs.
*
* @param $query
* @param array $ids
* @return mixed
*/
public function filterByIds($query, array $ids): void;
@ -40,123 +42,194 @@ interface AdapterInterface
* Manipulate the query to only include resources with a certain attribute
* value.
*
* @param $query
* @param Attribute $attribute
* @param $value
* @param string $operator The operator to use for comparison: = < > <= >=
* @return mixed
*/
public function filterByAttribute($query, Attribute $attribute, $value, string $operator = '='): void;
/**
* Manipulate the query to only include resources with a relationship within
* the given scope.
* Manipulate the query to only include resources with any one of the given
* resource IDs in a has-one relationship.
*
* @param $query
* @param HasOne $relationship
* @param array $ids
* @return mixed
*/
public function filterByRelationship($query, Relationship $relationship, Closure $scope): void;
public function filterByHasOne($query, HasOne $relationship, array $ids): void;
/**
* Manipulate the query to only include resources appropriate to given filter expression.
* Manipulate the query to only include resources with any one of the given
* resource IDs in a has-many relationship.
*
* @param string $expression The filter expression
* @param $query
* @param HasMany $relationship
* @param array $ids
* @return mixed
*/
public function filterByExpression($query, string $expression): void;
/**
* Manipulate the query to only include specific fields.
*
* @param string|array $fields Comma-separated list of field names to include or array of such lists for every resource type
*/
public function sparseFieldset($query, $fields): void;
public function filterByHasMany($query, HasMany $relationship, array $ids): void;
/**
* Manipulate the query to sort by the given attribute in the given direction.
*
* @param $query
* @param Attribute $attribute
* @param string $direction
* @return mixed
*/
public function sortByAttribute($query, Attribute $attribute, string $direction): void;
/**
* Manipulate the query to only include a certain number of results,
* starting from the given offset.
*
* @param $query
* @param int $limit
* @param int $offset
* @return mixed
*/
public function paginate($query, int $limit, int $offset): void;
/**
* Find a single resource by ID from the query.
*
* @param $query
* @param string $id
* @return mixed
*/
public function find($query, string $id);
/**
* Get a list of resources from the query.
*
* @param $query
* @return array
*/
public function get($query): array;
/**
* Get the number of results from the query.
*
* @param $query
* @return int
*/
public function count($query): int;
/**
* Determine whether or not this resource type represents the given model.
*
* This is used for polymorphic relationships, where there are one or many
* related models of unknown type. The first resource type with an adapter
* that responds positively from this method will be used.
*
* @param mixed $model
* @return bool
*/
public function represents($model): bool;
/**
* Create a new model instance.
*
* @return mixed
*/
public function newModel();
/**
* Get the ID from the model.
*
* @param $model
* @return string
*/
public function getId($model): string;
/**
* Get the value of an attribute from the model.
*
* @return mixed|Deferred
* @param $model
* @param Attribute $attribute
* @return mixed
*/
public function getAttribute($model, Attribute $attribute);
/**
* Get the model for a has-one relationship for the model.
*
* @return mixed|null|Deferred
* @param $model
* @param HasOne $relationship
* @param bool $linkage
* @return mixed|null
*/
public function getHasOne($model, HasOne $relationship, bool $linkageOnly, Context $context);
public function getHasOne($model, HasOne $relationship, bool $linkage);
/**
* Get a list of models for a has-many relationship for the model.
*
* @return array|Deferred
* @param $model
* @param HasMany $relationship
* @param bool $linkage
* @return array
*/
public function getHasMany($model, HasMany $relationship, bool $linkageOnly, Context $context);
/**
* Determine whether this resource type represents the given model.
*
* This is used for polymorphic relationships, where there are one or many
* related models of unknown type. The first resource type with an adapter
* that responds positively from this method will be used.
*/
public function represents($model): bool;
/**
* Create a new model instance.
*/
public function model();
/**
* Apply a user-generated ID to the model.
*/
public function setId($model, string $id): void;
public function getHasMany($model, HasMany $relationship, bool $linkage): array;
/**
* Apply an attribute value to the model.
*
* @param $model
* @param Attribute $attribute
* @param $value
* @return mixed
*/
public function setAttribute($model, Attribute $attribute, $value): void;
/**
* Apply a has-one relationship value to the model.
*
* @param $model
* @param HasOne $relationship
* @param $related
* @return mixed
*/
public function setHasOne($model, HasOne $relationship, $related): void;
/**
* Save the model.
*
* @param $model
* @return mixed
*/
public function save($model): void;
/**
* Save a has-many relationship for the model.
*
* @param $model
* @param HasMany $relationship
* @param array $related
* @return mixed
*/
public function saveHasMany($model, HasMany $relationship, array $related): void;
/**
* Delete the model.
*
* @param $model
* @return mixed
*/
public function delete($model): void;
/**
* Load information about related resources onto a collection of models.
*
* @param array $models
* @param array $relationships
* @param mixed $scope Should be called to give the deepest relationship
* an opportunity to scope the query that will fetch related resources
* @param bool $linkage true if we just need the IDs of the related
* resources and not their full data
* @return mixed
*/
public function load(array $models, array $relationships, $scope, bool $linkage): void;
}

View File

@ -12,14 +12,12 @@
namespace Tobyz\JsonApiServer\Adapter;
use Closure;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
use Illuminate\Database\Eloquent\Relations\MorphOneOrMany;
use InvalidArgumentException;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Deferred;
use Tobyz\JsonApiServer\Schema\Attribute;
use Tobyz\JsonApiServer\Schema\HasMany;
use Tobyz\JsonApiServer\Schema\HasOne;
@ -41,44 +39,21 @@ class EloquentAdapter implements AdapterInterface
}
}
public function query(): Builder
public function represents($model): bool
{
return $model instanceof $this->model;
}
public function newModel()
{
return $this->model->newInstance();
}
public function newQuery()
{
return $this->model->query();
}
public function filterByIds($query, array $ids): void
{
$query->whereIn($this->model->getQualifiedKeyName(), $ids);
}
public function filterByAttribute($query, Attribute $attribute, $value, string $operator = '='): void
{
$query->where($this->getAttributeProperty($attribute), $operator, $value);
}
public function filterByRelationship($query, Relationship $relationship, Closure $scope): void
{
$query->whereHas($this->getRelationshipProperty($relationship), $scope);
}
public function filterByExpression($query, string $expression): void
{
}
public function sparseFieldset($query, $fields): void
{
}
public function sortByAttribute($query, Attribute $attribute, string $direction): void
{
$query->orderBy($this->getAttributeProperty($attribute), $direction);
}
public function paginate($query, int $limit, int $offset): void
{
$query->take($limit)->skip($offset);
}
public function find($query, string $id)
{
return $query->find($id);
@ -101,83 +76,47 @@ class EloquentAdapter implements AdapterInterface
public function getAttribute($model, Attribute $attribute)
{
return $model->getAttribute($this->getAttributeProperty($attribute));
return $model->{$this->getAttributeProperty($attribute)};
}
public function getHasOne($model, HasOne $relationship, bool $linkageOnly, Context $context)
public function getHasOne($model, HasOne $relationship, bool $linkage)
{
// If this is a belongs-to relationship, and we only need to get the ID
// for linkage, then we don't have to actually load the relation because
// the ID is stored in a column directly on the model. We will mock up a
// related model with the value of the ID filled.
if ($linkageOnly) {
// If it's a belongs-to relationship and we only need to get the ID,
// then we don't have to actually load the relation because the ID is
// stored in a column directly on the model. We will mock up a related
// model with the value of the ID filled.
if ($linkage) {
$relation = $this->getEloquentRelation($model, $relationship);
if ($relation instanceof BelongsTo) {
if ($key = $model->getAttribute($relation->getForeignKeyName())) {
if ($key = $model->{$relation->getForeignKeyName()}) {
$related = $relation->getRelated();
return $related->newInstance()->forceFill([
$related->getKeyName() => $key
]);
return $related->newInstance()->forceFill([$related->getKeyName() => $key]);
}
return null;
}
}
return $this->getRelationship($model, $relationship, $context);
return $this->getRelationValue($model, $relationship);
}
public function getHasMany($model, HasMany $relationship, bool $linkageOnly, Context $context)
public function getHasMany($model, HasMany $relationship, bool $linkage): array
{
return $this->getRelationship($model, $relationship, $context);
}
$collection = $this->getRelationValue($model, $relationship);
protected function getRelationship($model, Relationship $relationship, Context $context): Deferred
{
$name = $this->getRelationshipProperty($relationship);
EloquentBuffer::add($model, $name);
return new Deferred(function () use ($model, $name, $relationship, $context) {
EloquentBuffer::load($model, $name, $relationship, $context);
$data = $model->getRelation($name);
return $data instanceof Collection ? $data->all() : $data;
});
}
public function represents($model): bool
{
return $model instanceof $this->model;
}
public function model(): Model
{
return $this->model->newInstance();
}
public function setId($model, string $id): void
{
$model->setAttribute($model->getKeyName(), $id);
return $collection ? $collection->all() : [];
}
public function setAttribute($model, Attribute $attribute, $value): void
{
$model->setAttribute($this->getAttributeProperty($attribute), $value);
$model->{$this->getAttributeProperty($attribute)} = $value;
}
public function setHasOne($model, HasOne $relationship, $related): void
{
$relation = $this->getEloquentRelation($model, $relationship);
// If this is a belongs-to relationship, then the ID is stored on the
// model itself so we can set it here.
if ($relation instanceof BelongsTo) {
$relation->associate($related);
}
$this->getEloquentRelation($model, $relationship)->associate($related);
}
public function save($model): void
@ -187,11 +126,7 @@ class EloquentAdapter implements AdapterInterface
public function saveHasMany($model, HasMany $relationship, array $related): void
{
$relation = $this->getEloquentRelation($model, $relationship);
if ($relation instanceof BelongsToMany) {
$relation->sync(new Collection($related));
}
$this->getEloquentRelation($model, $relationship)->sync(new Collection($related));
}
public function delete($model): void
@ -199,7 +134,79 @@ class EloquentAdapter implements AdapterInterface
// For models that use the SoftDeletes trait, deleting the resource from
// the API implies permanent deletion. Non-permanent deletion should be
// achieved by manipulating a resource attribute.
$model->forceDelete();
if (method_exists($model, 'forceDelete')) {
$model->forceDelete();
} else {
$model->delete();
}
}
public function filterByIds($query, array $ids): void
{
$key = $query->getModel()->getQualifiedKeyName();
$query->whereIn($key, $ids);
}
public function filterByAttribute($query, Attribute $attribute, $value, string $operator = '='): void
{
$column = $this->getAttributeColumn($attribute);
$query->where($column, $operator, $value);
}
public function filterByHasOne($query, HasOne $relationship, array $ids): void
{
$relation = $this->getEloquentRelation($query->getModel(), $relationship);
$column = $relation instanceof HasOneThrough ? $relation->getQualifiedParentKeyName() : $relation->getQualifiedForeignKeyName();
$query->whereIn($column, $ids);
}
public function filterByHasMany($query, HasMany $relationship, array $ids): void
{
$property = $this->getRelationshipProperty($relationship);
$relation = $this->getEloquentRelation($query->getModel(), $relationship);
$relatedKey = $relation->getRelated()->getQualifiedKeyName();
if (count($ids)) {
$query->whereHas($property, function ($query) use ($relatedKey, $ids) {
$query->whereIn($relatedKey, $ids);
});
} else {
$query->whereDoesntHave($property);
}
}
public function sortByAttribute($query, Attribute $attribute, string $direction): void
{
$query->orderBy($this->getAttributeColumn($attribute), $direction);
}
public function paginate($query, int $limit, int $offset): void
{
$query->take($limit)->skip($offset);
}
public function load(array $models, array $relationships, $scope, bool $linkage): void
{
// TODO: Find the relation on the model that we're after. If it's a
// belongs-to relation, and we only need linkage, then we won't need
// to load anything as the related ID is store directly on the model.
(new Collection($models))->loadMissing([
$this->getRelationshipPath($relationships) => function ($relation) use ($relationships, $scope) {
$query = $relation->getQuery();
if (is_array($scope)) {
// Eloquent doesn't support polymorphic loading constraints,
// so for now we just won't do anything.
// https://github.com/laravel/framework/pull/35190
} else {
$scope($query);
}
}
]);
}
private function getAttributeProperty(Attribute $attribute): string
@ -207,13 +214,28 @@ class EloquentAdapter implements AdapterInterface
return $attribute->getProperty() ?: strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $attribute->getName()));
}
private function getAttributeColumn(Attribute $attribute): string
{
return $this->model->getTable().'.'.$this->getAttributeProperty($attribute);
}
private function getRelationshipProperty(Relationship $relationship): string
{
return $relationship->getProperty() ?: $relationship->getName();
}
private function getRelationshipPath(array $trail): string
{
return implode('.', array_map([$this, 'getRelationshipProperty'], $trail));
}
private function getEloquentRelation($model, Relationship $relationship)
{
return $model->{$this->getRelationshipProperty($relationship)}();
}
private function getRelationValue($model, Relationship $relationship)
{
return $model->{$this->getRelationshipProperty($relationship)};
}
}

View File

@ -1,86 +0,0 @@
<?php
/*
* This file is part of tobyz/json-api-server.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tobyz\JsonApiServer\Adapter;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Schema\Relationship;
use function Tobyz\JsonApiServer\run_callbacks;
abstract class EloquentBuffer
{
private static $buffer = [];
public static function add(Model $model, string $relationName): void
{
static::$buffer[get_class($model)][$relationName][] = $model;
}
public static function load(Model $model, string $relationName, Relationship $relationship, Context $context): void
{
if (! $models = static::$buffer[get_class($model)][$relationName] ?? null) {
return;
}
Collection::make($models)->load([
$relationName => function ($relation) use ($model, $relationName, $relationship, $context) {
$query = $relation->getQuery();
// When loading the relationship, we need to scope the query
// using the scopes defined in the related API resource there
// may be multiple if this is a polymorphic relationship. We
// start by getting the resource types this relationship
// could possibly contain.
$resourceTypes = $context->getApi()->getResourceTypes();
if ($type = $relationship->getType()) {
if (is_string($type)) {
$resourceTypes = [$resourceTypes[$type]];
} else {
$resourceTypes = array_intersect_key($resourceTypes, array_flip($type));
}
}
// Now, construct a map of model class names -> scoping
// functions. This will be provided to the MorphTo::constrain
// method in order to apply type-specific scoping.
$constrain = [];
foreach ($resourceTypes as $resourceType) {
if ($model = $resourceType->getAdapter()->model()) {
$constrain[get_class($model)] = function ($query) use ($resourceType, $context) {
$resourceType->applyScopes($query, $context);
};
}
}
if ($relation instanceof MorphTo) {
$relation->constrain($constrain);
} else {
reset($constrain)($query);
}
// Also apply any local scopes that have been defined on this
// relationship.
run_callbacks(
$relationship->getListeners('scope'),
[$query, $context]
);
}
]);
static::$buffer[get_class($model)][$relationName] = [];
}
}

View File

@ -1,109 +0,0 @@
<?php
namespace Tobyz\JsonApiServer\Adapter;
use Closure;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Schema\Attribute;
use Tobyz\JsonApiServer\Schema\HasMany;
use Tobyz\JsonApiServer\Schema\HasOne;
use Tobyz\JsonApiServer\Schema\Relationship;
class NullAdapter implements AdapterInterface
{
public function query()
{
}
public function filterByIds($query, array $ids): void
{
}
public function filterByAttribute($query, Attribute $attribute, $value, string $operator = '='): void
{
}
public function filterByRelationship($query, Relationship $relationship, Closure $scope): void
{
}
public function filterByExpression($query, string $expression): void
{
}
public function sparseFieldset($query, $fields): void
{
}
public function sortByAttribute($query, Attribute $attribute, string $direction): void
{
}
public function paginate($query, int $limit, int $offset): void
{
}
public function find($query, string $id)
{
}
public function get($query): array
{
return [];
}
public function count($query): int
{
return 0;
}
public function getId($model): string
{
return '';
}
public function getAttribute($model, Attribute $attribute)
{
}
public function getHasOne($model, HasOne $relationship, bool $linkageOnly, Context $context)
{
}
public function getHasMany($model, HasMany $relationship, bool $linkageOnly, Context $context)
{
}
public function represents($model): bool
{
return false;
}
public function model()
{
}
public function setId($model, string $id): void
{
}
public function setAttribute($model, Attribute $attribute, $value): void
{
}
public function setHasOne($model, HasOne $relationship, $related): void
{
}
public function save($model): void
{
}
public function saveHasMany($model, HasMany $relationship, array $related): void
{
}
public function delete($model): void
{
}
}

View File

@ -20,94 +20,20 @@ class Context
use HasMeta;
use HasListeners;
private $api;
private $request;
public function __construct(JsonApi $api, ServerRequestInterface $request)
public function __construct(ServerRequestInterface $request)
{
$this->api = $api;
$this->request = $request;
}
/**
* Get the JsonApi instance.
*/
public function getApi(): JsonApi
{
return $this->api;
}
/**
* Get the PSR-7 request instance.
*/
public function getRequest(): ServerRequestInterface
{
return $this->request;
}
public function withRequest(ServerRequestInterface $request): Context
{
return new static($this->api, $request);
}
/**
* Get the request path relative to the API's base path.
*/
public function getPath(): string
{
return $this->api->stripBasePath(
$this->request->getUri()->getPath()
);
}
/**
* Get the parsed JSON:API payload.
*/
public function getBody(): ?array
{
return $this->request->getParsedBody() ?: json_decode($this->request->getBody()->getContents(), true);
}
public function response(callable $callback): void
public function response(callable $callback)
{
$this->listeners['response'][] = $callback;
}
/**
* Determine whether a field has been requested in a sparse fieldset.
*/
public function fieldRequested(string $type, string $field, bool $default = true): bool
{
$queryParams = $this->request->getQueryParams();
if (! isset($queryParams['fields'][$type])) {
return $default;
}
return in_array($field, explode(',', $queryParams['fields'][$type]));
}
/**
* Determine whether a sort field has been requested.
*/
public function sortRequested(string $field): bool
{
if ($sortString = $this->getRequest()->getQueryParams()['sort'] ?? null) {
foreach (parse_sort_string($sortString) as [$name, $direction]) {
if ($name === $field) {
return true;
}
}
}
return false;
}
/**
* Get the value of a filter.
*/
public function filter(string $name): ?string
{
return $this->request->getQueryParams()['filter'][$name] ?? null;
}
}

View File

@ -1,29 +0,0 @@
<?php
/*
* This file is part of tobyz/json-api-server.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tobyz\JsonApiServer;
use Closure;
class Deferred
{
private $callback;
public function __construct(Closure $callback)
{
$this->callback = $callback;
}
public function resolve()
{
return ($this->callback)();
}
}

View File

@ -1,35 +0,0 @@
<?php
/*
* This file is part of tobyz/json-api-server.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tobyz\JsonApiServer\Endpoint\Concerns;
use JsonApiPhp\JsonApi\JsonApi;
use JsonApiPhp\JsonApi\Meta;
use Tobyz\JsonApiServer\Context;
trait BuildsMeta
{
private function buildMeta(Context $context): array
{
$meta = [];
foreach ($context->getMeta() as $item) {
$meta[] = new Meta($item->getName(), $item->getValue()($context));
}
return $meta;
}
private function buildJsonApiObject(Context $context): JsonApi
{
return new JsonApi('1.1');
}
}

View File

@ -23,17 +23,17 @@ trait FindsResources
*
* @throws ResourceNotFoundException if the resource is not found.
*/
private function findResource(ResourceType $resourceType, string $id, Context $context)
private function findResource(ResourceType $resource, string $id, Context $context)
{
$adapter = $resourceType->getAdapter();
$query = $adapter->query();
$adapter = $resource->getAdapter();
$query = $adapter->newQuery();
run_callbacks($resourceType->getSchema()->getListeners('scope'), [$query, $context]);
run_callbacks($resource->getSchema()->getListeners('scope'), [$query, $context]);
$model = $adapter->find($query, $id);
if (! $model) {
throw new ResourceNotFoundException($resourceType->getType(), $id);
throw new ResourceNotFoundException($resource->getType(), $id);
}
return $model;

View File

@ -11,21 +11,27 @@
namespace Tobyz\JsonApiServer\Endpoint\Concerns;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Exception\BadRequestException;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\ResourceType;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Schema\Relationship;
use function Tobyz\JsonApiServer\run_callbacks;
/**
* @property JsonApi $api
* @property ResourceType $resource
*/
trait IncludesData
{
private function getInclude(Context $context, ResourceType $resourceType): array
private function getInclude(Context $context): array
{
$queryParams = $context->getRequest()->getQueryParams();
if (! empty($queryParams['include'])) {
$include = $this->parseInclude($queryParams['include']);
$this->validateInclude($context, [$resourceType], $include);
$this->validateInclude($this->resource, $include);
return $include;
}
@ -33,11 +39,11 @@ trait IncludesData
return [];
}
private function parseInclude($include): array
private function parseInclude(string $include): array
{
$tree = [];
foreach (is_array($include) ? $include : explode(',', $include) as $path) {
foreach (explode(',', $include) as $path) {
$array = &$tree;
foreach (explode('.', $path) as $key) {
@ -52,38 +58,87 @@ trait IncludesData
return $tree;
}
private function validateInclude(Context $context, array $resourceTypes, array $include, string $path = '')
private function validateInclude(ResourceType $resource, array $include, string $path = '')
{
$fields = $resource->getSchema()->getFields();
foreach ($include as $name => $nested) {
foreach ($resourceTypes as $resource) {
$fields = $resource->getSchema()->getFields();
if (
! isset($fields[$name])
|| ! $fields[$name] instanceof Relationship
|| ! $fields[$name]->isIncludable()
) {
continue;
}
$type = $fields[$name]->getType();
if (is_string($type)) {
$relatedResource = $context->getApi()->getResourceType($type);
$this->validateInclude($context, [$relatedResource], $nested, $name.'.');
} else {
$relatedResources = is_array($type) ? array_map(function ($type) use ($context) {
return $context->getApi()->getResourceType($type);
}, $type) : array_values($context->getApi()->getResourceTypes());
$this->validateInclude($context, $relatedResources, $nested, $name.'.');
}
continue 2;
if (
! isset($fields[$name])
|| ! $fields[$name] instanceof Relationship
|| ! $fields[$name]->isIncludable()
) {
throw new BadRequestException("Invalid include [{$path}{$name}]", 'include');
}
throw (new BadRequestException("Invalid include [{$path}{$name}]"))->setSourceParameter('include');
if (($type = $fields[$name]->getType()) && is_string($type)) {
$relatedResource = $this->api->getResource($type);
$this->validateInclude($relatedResource, $nested, $name.'.');
} elseif ($nested) {
throw new BadRequestException("Invalid include [{$path}{$name}.*]", 'include');
}
}
}
private function loadRelationships(array $models, array $include, Context $context)
{
$this->loadRelationshipsAtLevel($models, [], $this->resource, $include, $context);
}
private function loadRelationshipsAtLevel(array $models, array $relationshipPath, ResourceType $resource, array $include, Context $context)
{
$adapter = $resource->getAdapter();
$schema = $resource->getSchema();
$fields = $schema->getFields();
foreach ($fields as $name => $field) {
if (
! $field instanceof Relationship
|| (! $field->hasLinkage() && ! isset($include[$name]))
|| $field->getVisible() === false
) {
continue;
}
$nextRelationshipPath = array_merge($relationshipPath, [$field]);
if ($field->shouldLoad()) {
$type = $field->getType();
if (is_string($type)) {
$relatedResource = $this->api->getResource($type);
$scope = function ($query) use ($context, $field, $relatedResource) {
run_callbacks($relatedResource->getSchema()->getListeners('scope'), [$query, $context]);
run_callbacks($field->getListeners('scope'), [$query, $context]);
};
} else {
$relatedResources = is_array($type) ? array_map(function ($type) {
return $this->api->getResource($type);
}, $type) : $this->api->getResources();
$scope = array_combine(
array_map(function ($relatedResource) {
return $relatedResource->getType();
}, $relatedResources),
array_map(function ($relatedResource) use ($context, $field) {
return function ($query) use ($context, $field, $relatedResource) {
run_callbacks($relatedResource->getSchema()->getListeners('scope'), [$query, $context]);
run_callbacks($field->getListeners('scope'), [$query, $context]);
};
}, $relatedResources)
);
}
$adapter->load($models, $nextRelationshipPath, $scope, $field->hasLinkage());
if (isset($include[$name]) && is_string($type)) {
$relatedResource = $this->api->getResource($type);
$this->loadRelationshipsAtLevel($models, $nextRelationshipPath, $relatedResource, $include[$name] ?? [], $context);
}
}
}
}
}

View File

@ -11,23 +11,25 @@
namespace Tobyz\JsonApiServer\Endpoint\Concerns;
use Tobyz\JsonApiServer\Context;
use Psr\Http\Message\ServerRequestInterface;
use Tobyz\JsonApiServer\Exception\BadRequestException;
use Tobyz\JsonApiServer\Exception\ConflictException;
use Tobyz\JsonApiServer\Exception\ForbiddenException;
use Tobyz\JsonApiServer\Exception\UnprocessableEntityException;
use Tobyz\JsonApiServer\ResourceType;
use Tobyz\JsonApiServer\Schema\Attribute;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Schema\HasMany;
use Tobyz\JsonApiServer\Schema\HasOne;
use Tobyz\JsonApiServer\Schema\Relationship;
use function Tobyz\JsonApiServer\evaluate;
use function Tobyz\JsonApiServer\get_value;
use function Tobyz\JsonApiServer\has_value;
use function Tobyz\JsonApiServer\run_callbacks;
use function Tobyz\JsonApiServer\set_value;
/**
* @property JsonApi $api
* @property ResourceType $resource
*/
trait SavesData
{
use FindsResources;
@ -37,7 +39,7 @@ trait SavesData
*
* @throws BadRequestException if the `data` member is invalid.
*/
private function parseData(ResourceType $resourceType, $body, $model = null): array
private function parseData($body, $model = null): array
{
$body = (array) $body;
@ -45,24 +47,16 @@ trait SavesData
throw new BadRequestException('data must be an object');
}
if (! isset($body['data']['type'])) {
throw new BadRequestException('data.type must be present');
if (! isset($body['data']['type']) || $body['data']['type'] !== $this->resource->getType()) {
throw new BadRequestException('data.type does not match the resource type');
}
if ($model) {
if (! isset($body['data']['id'])) {
throw new BadRequestException('data.id must be present');
}
$id = $this->resource->getAdapter()->getId($model);
if ($body['data']['id'] !== $resourceType->getAdapter()->getId($model)) {
throw new ConflictException('data.id does not match the resource ID');
if (! isset($body['data']['id']) || $body['data']['id'] !== $id) {
throw new BadRequestException('data.id does not match the resource ID');
}
} elseif (isset($body['data']['id'])) {
throw new ForbiddenException('Client-generated IDs are not supported');
}
if ($body['data']['type'] !== $resourceType->getType()) {
throw new ConflictException('data.type does not match the resource type');
}
if (isset($body['data']['attributes']) && ! is_array($body['data']['attributes'])) {
@ -98,18 +92,18 @@ trait SavesData
throw new BadRequestException("type [{$identifier['type']}] not allowed");
}
$resourceType = $context->getApi()->getResourceType($identifier['type']);
$resource = $this->api->getResource($identifier['type']);
return $this->findResource($resourceType, $identifier['id'], $context);
return $this->findResource($resource, $identifier['id'], $context);
}
/**
* Assert that the fields contained within a data object are valid.
*/
private function validateFields(ResourceType $resourceType, array $data, $model, Context $context)
private function validateFields(array $data, $model, Context $context)
{
$this->assertFieldsExist($resourceType, $data);
$this->assertFieldsWritable($resourceType, $data, $model, $context);
$this->assertFieldsExist($data);
$this->assertFieldsWritable($data, $model, $context);
}
/**
@ -117,9 +111,9 @@ trait SavesData
*
* @throws BadRequestException if a field is unknown.
*/
private function assertFieldsExist(ResourceType $resourceType, array $data)
private function assertFieldsExist(array $data)
{
$fields = $resourceType->getSchema()->getFields();
$fields = $this->resource->getSchema()->getFields();
foreach (['attributes', 'relationships'] as $location) {
foreach ($data[$location] as $name => $value) {
@ -135,9 +129,10 @@ trait SavesData
*
* @throws BadRequestException if a field is not writable.
*/
private function assertFieldsWritable(ResourceType $resourceType, array $data, $model, Context $context)
private function assertFieldsWritable(array $data, $model, Context $context)
{
foreach ($resourceType->getSchema()->getFields() as $field) {
foreach ($this->resource->getSchema()->getFields() as $field) {
if (! has_value($data, $field)) {
continue;
}
@ -157,20 +152,16 @@ trait SavesData
/**
* Replace relationship linkage within a data object with models.
*/
private function loadRelatedResources(ResourceType $resourceType, array &$data, Context $context)
private function loadRelatedResources(array &$data, Context $context)
{
foreach ($resourceType->getSchema()->getFields() as $field) {
foreach ($this->resource->getSchema()->getFields() as $field) {
if (! $field instanceof Relationship || ! has_value($data, $field)) {
continue;
}
$value = get_value($data, $field);
if (! array_key_exists('data', $value)) {
throw new BadRequestException('relationship does not include data key');
}
if ($value['data'] !== null) {
if (isset($value['data'])) {
$allowedTypes = (array) $field->getType();
if ($field instanceof HasOne) {
@ -191,11 +182,11 @@ trait SavesData
*
* @throws UnprocessableEntityException if any fields do not pass validation.
*/
private function assertDataValid(ResourceType $resourceType, array $data, $model, Context $context, bool $validateAll): void
private function assertDataValid(array $data, $model, Context $context, bool $validateAll): void
{
$failures = [];
foreach ($resourceType->getSchema()->getFields() as $field) {
foreach ($this->resource->getSchema()->getFields() as $field) {
if (! $validateAll && ! has_value($data, $field)) {
continue;
}
@ -218,11 +209,11 @@ trait SavesData
/**
* Set field values from a data object to the model instance.
*/
private function setValues(ResourceType $resourceType, array $data, $model, Context $context)
private function setValues(array $data, $model, Context $context)
{
$adapter = $resourceType->getAdapter();
$adapter = $this->resource->getAdapter();
foreach ($resourceType->getSchema()->getFields() as $field) {
foreach ($this->resource->getSchema()->getFields() as $field) {
if (! has_value($data, $field)) {
continue;
}
@ -249,32 +240,32 @@ trait SavesData
/**
* Save the model and its fields.
*/
private function save(ResourceType $resourceType, array $data, $model, Context $context)
private function save(array $data, $model, Context $context)
{
$this->saveModel($resourceType, $model, $context);
$this->saveFields($resourceType, $data, $model, $context);
$this->saveModel($model, $context);
$this->saveFields($data, $model, $context);
}
/**
* Save the model.
*/
private function saveModel(ResourceType $resourceType, $model, Context $context)
private function saveModel($model, Context $context)
{
if ($saveCallback = $resourceType->getSchema()->getSaveCallback()) {
if ($saveCallback = $this->resource->getSchema()->getSaveCallback()) {
$saveCallback($model, $context);
} else {
$resourceType->getAdapter()->save($model);
$this->resource->getAdapter()->save($model);
}
}
/**
* Save any fields that were not saved with the model.
*/
private function saveFields(ResourceType $resourceType, array $data, $model, Context $context)
private function saveFields(array $data, $model, Context $context)
{
$adapter = $resourceType->getAdapter();
$adapter = $this->resource->getAdapter();
foreach ($resourceType->getSchema()->getFields() as $field) {
foreach ($this->resource->getSchema()->getFields() as $field) {
if (! has_value($data, $field)) {
continue;
}
@ -288,16 +279,16 @@ trait SavesData
}
}
$this->runSavedCallbacks($resourceType, $data, $model, $context);
$this->runSavedCallbacks($data, $model, $context);
}
/**
* Run field saved listeners.
*/
private function runSavedCallbacks(ResourceType $resourceType, array $data, $model, Context $context)
private function runSavedCallbacks(array $data, $model, Context $context)
{
foreach ($resourceType->getSchema()->getFields() as $field) {
foreach ($this->resource->getSchema()->getFields() as $field) {
if (! has_value($data, $field)) {
continue;
}
@ -308,14 +299,4 @@ trait SavesData
);
}
}
/**
* Get a fresh copy of the model for display.
*/
private function freshModel(ResourceType $resourceType, $model, Context $context)
{
$id = $resourceType->getAdapter()->getId($model);
return $this->findResource($resourceType, $id, $context);
}
}

View File

@ -13,11 +13,9 @@ namespace Tobyz\JsonApiServer\Endpoint;
use Psr\Http\Message\ResponseInterface;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Endpoint\Concerns\BuildsMeta;
use Tobyz\JsonApiServer\Endpoint\Concerns\SavesData;
use Tobyz\JsonApiServer\Exception\ForbiddenException;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\ResourceType;
use function Tobyz\JsonApiServer\evaluate;
use function Tobyz\JsonApiServer\has_value;
use function Tobyz\JsonApiServer\run_callbacks;
@ -25,57 +23,61 @@ use function Tobyz\JsonApiServer\set_value;
class Create
{
use SavesData;
use Concerns\SavesData;
private $api;
private $resource;
public function __construct(JsonApi $api, ResourceType $resource)
{
$this->api = $api;
$this->resource = $resource;
}
/**
* @throws ForbiddenException if the resource is not creatable.
*/
public function handle(Context $context, ResourceType $resourceType): ResponseInterface
public function handle(Context $context): ResponseInterface
{
$schema = $resourceType->getSchema();
$schema = $this->resource->getSchema();
if (! evaluate($schema->isCreatable(), [$context])) {
throw new ForbiddenException(sprintf(
'Cannot create resource type %s',
$resourceType->getType()
));
throw new ForbiddenException;
}
$model = $this->newModel($resourceType, $context);
$data = $this->parseData($resourceType, $context->getBody());
$model = $this->newModel($context);
$data = $this->parseData($context->getRequest()->getParsedBody());
$this->validateFields($resourceType, $data, $model, $context);
$this->fillDefaultValues($resourceType, $data, $context);
$this->loadRelatedResources($resourceType, $data, $context);
$this->assertDataValid($resourceType, $data, $model, $context, true);
$this->setValues($resourceType, $data, $model, $context);
$this->validateFields($data, $model, $context);
$this->fillDefaultValues($data, $context);
$this->loadRelatedResources($data, $context);
$this->assertDataValid($data, $model, $context, true);
$this->setValues($data, $model, $context);
run_callbacks($schema->getListeners('creating'), [&$model, $context]);
$this->save($resourceType, $data, $model, $context);
$this->save($data, $model, $context);
run_callbacks($schema->getListeners('created'), [&$model, $context]);
$model = $this->freshModel($resourceType, $model, $context);
return (new Show())
->handle($context, $resourceType, $model)
->withStatus(201)
->withHeader('Location', $resourceType->url($model, $context));
return (new Show($this->api, $this->resource, $model))
->handle($context)
->withStatus(201);
}
private function newModel(ResourceType $resourceType, Context $context)
private function newModel(Context $context)
{
$newModel = $resourceType->getSchema()->getModelCallback();
$resource = $this->resource;
$newModel = $resource->getSchema()->getNewModelCallback();
return $newModel
? $newModel($context)
: $resourceType->getAdapter()->model();
: $resource->getAdapter()->newModel();
}
private function fillDefaultValues(ResourceType $resourceType, array &$data, Context $context)
private function fillDefaultValues(array &$data, Context $context)
{
foreach ($resourceType->getSchema()->getFields() as $field) {
foreach ($this->resource->getSchema()->getFields() as $field) {
if (! has_value($data, $field) && ($defaultCallback = $field->getDefaultCallback())) {
set_value($data, $field, $defaultCallback($context));
}

View File

@ -11,55 +11,48 @@
namespace Tobyz\JsonApiServer\Endpoint;
use JsonApiPhp\JsonApi\Meta;
use JsonApiPhp\JsonApi\MetaDocument;
use Nyholm\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Endpoint\Concerns\BuildsMeta;
use Tobyz\JsonApiServer\Exception\ForbiddenException;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\ResourceType;
use Tobyz\JsonApiServer\Context;
use function Tobyz\JsonApiServer\evaluate;
use function Tobyz\JsonApiServer\json_api_response;
use function Tobyz\JsonApiServer\run_callbacks;
class Delete
{
use BuildsMeta;
private $api;
private $resource;
private $model;
public function __construct(JsonApi $api, ResourceType $resource, $model)
{
$this->api = $api;
$this->resource = $resource;
$this->model = $model;
}
/**
* @throws ForbiddenException if the resource is not deletable.
*/
public function handle(Context $context, ResourceType $resourceType, $model): ResponseInterface
public function handle(Context $context): ResponseInterface
{
$schema = $resourceType->getSchema();
$schema = $this->resource->getSchema();
if (! evaluate($schema->isDeletable(), [$model, $context])) {
throw new ForbiddenException(sprintf(
'Cannot delete resource %s:%s',
$resourceType->getType(),
$resourceType->getAdapter()->getId($model)
));
if (! evaluate($schema->isDeletable(), [$this->model, $context])) {
throw new ForbiddenException;
}
run_callbacks($schema->getListeners('deleting'), [&$model, $context]);
run_callbacks($schema->getListeners('deleting'), [&$this->model, $context]);
if ($deleteCallback = $schema->getDeleteCallback()) {
$deleteCallback($model, $context);
$deleteCallback($this->model, $context);
} else {
$resourceType->getAdapter()->delete($model);
$this->resource->getAdapter()->delete($this->model);
}
run_callbacks($schema->getListeners('deleted'), [&$model, $context]);
if (count($meta = $this->buildMeta($context))) {
$meta[] = $this->buildJsonApiObject($context);
return json_api_response(
new MetaDocument(...$meta)
);
}
run_callbacks($schema->getListeners('deleted'), [&$this->model, $context]);
return new Response(204);
}

View File

@ -17,103 +17,80 @@ use JsonApiPhp\JsonApi\Link\NextLink;
use JsonApiPhp\JsonApi\Link\PrevLink;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Endpoint\Concerns\BuildsMeta;
use Tobyz\JsonApiServer\Endpoint\Concerns\IncludesData;
use Tobyz\JsonApiServer\Adapter\AdapterInterface;
use Tobyz\JsonApiServer\Exception\BadRequestException;
use Tobyz\JsonApiServer\Exception\ForbiddenException;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\ResourceType;
use Tobyz\JsonApiServer\Schema\Attribute;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Schema\HasMany;
use Tobyz\JsonApiServer\Schema\HasOne;
use Tobyz\JsonApiServer\Serializer;
use function Tobyz\JsonApiServer\evaluate;
use function Tobyz\JsonApiServer\json_api_response;
use function Tobyz\JsonApiServer\run_callbacks;
class Index
{
use IncludesData;
use BuildsMeta;
use Concerns\IncludesData;
private $api;
private $resource;
public function __construct(JsonApi $api, ResourceType $resource)
{
$this->api = $api;
$this->resource = $resource;
}
/**
* Handle a request to show a resource listing.
*/
public function handle(Context $context, ResourceType $resourceType): ResponseInterface
public function handle(Context $context): ResponseInterface
{
$adapter = $resourceType->getAdapter();
$schema = $resourceType->getSchema();
$adapter = $this->resource->getAdapter();
$schema = $this->resource->getSchema();
if (! evaluate($schema->isListable(), [$context])) {
throw new ForbiddenException(sprintf(
'Cannot list resource type %s',
$resourceType->getType()
));
throw new ForbiddenException;
}
$query = $adapter->query();
$resourceType->applyScopes($query, $context);
$include = $this->getInclude($context, $resourceType);
[$offset, $limit] = $this->paginate($resourceType, $query, $context);
if ($sortString = $context->getRequest()->getQueryParams()['sort'] ?? $schema->getDefaultSort()) {
$resourceType->applySort($query, $sortString, $context);
}
if ($filter = $context->getRequest()->getQueryParams()['filter'] ?? null) {
$resourceType->applyFilters($query, $filter, $context);
}
if ($fields = $context->getRequest()->getQueryParams()['fields'] ?? null) {
$resourceType->applySparseFieldset($query, $fields, $context);
}
$query = $adapter->newQuery();
run_callbacks($schema->getListeners('listing'), [$query, $context]);
run_callbacks($schema->getListeners('scope'), [$query, $context]);
$include = $this->getInclude($context);
[$offset, $limit] = $this->paginate($query, $context);
$this->sort($query, $context);
$this->filter($query, $context);
$total = $schema->isCountable() ? $adapter->count($query) : null;
$models = $adapter->get($query);
$this->loadRelationships($models, $include, $context);
run_callbacks($schema->getListeners('listed'), [$models, $context]);
$serializer = new Serializer($context);
$serializer = new Serializer($this->api, $context);
foreach ($models as $model) {
$serializer->add($resourceType, $model, $include);
$serializer->add($this->resource, $model, $include);
}
[$primary, $included] = $serializer->serialize();
$paginationLinks = $this->buildPaginationLinks(
$resourceType,
$context->getRequest(),
$offset,
$limit,
count($models),
$total
);
$meta = [
new Structure\Meta('offset', $offset),
new Structure\Meta('limit', $limit),
];
if ($total !== null) {
$meta[] = new Structure\Meta('total', $total);
}
$meta = array_merge($meta, $this->buildMeta($context));
return json_api_response(
new Structure\CompoundDocument(
new Structure\PaginatedCollection(
new Structure\Pagination(...$paginationLinks),
new Structure\ResourceCollection(...$primary)
new Structure\Pagination(...$this->buildPaginationLinks($context->getRequest(), $offset, $limit, count($models), $total)),
new Structure\ResourceCollection(...$serializer->primary())
),
new Structure\Included(...$included),
new Structure\Included(...$serializer->included()),
new Structure\Link\SelfLink($this->buildUrl($context->getRequest())),
$this->buildJsonApiObject($context),
...$meta
new Structure\Meta('offset', $offset),
new Structure\Meta('limit', $limit),
...($total !== null ? [new Structure\Meta('total', $total)] : [])
)
);
}
@ -134,17 +111,15 @@ class Index
}
}
ksort($queryParams);
$queryString = http_build_query($queryParams, '', '&', PHP_QUERY_RFC3986);
return $selfUrl.($queryString ? '?'.$queryString : '');
}
private function buildPaginationLinks(ResourceType $resourceType, Request $request, int $offset, ?int $limit, int $count, ?int $total): array
private function buildPaginationLinks(Request $request, int $offset, ?int $limit, int $count, ?int $total)
{
$paginationLinks = [];
$schema = $resourceType->getSchema();
$schema = $this->resource->getSchema();
if ($offset > 0) {
$paginationLinks[] = new Structure\Link\FirstLink($this->buildUrl($request, ['page' => ['offset' => 0]]));
@ -160,20 +135,69 @@ class Index
$paginationLinks[] = new PrevLink($this->buildUrl($request, $params));
}
if ($schema->isCountable() && $schema->getPerPage() && $limit && $offset + $limit < $total) {
if ($schema->isCountable() && $schema->getPerPage() && $offset + $limit < $total) {
$paginationLinks[] = new LastLink($this->buildUrl($request, ['page' => ['offset' => floor(($total - 1) / $limit) * $limit]]));
}
if (($total === null && $count === $limit) || $offset + $count < $total) {
if (($total === null && $count === $limit) || $offset + $limit < $total) {
$paginationLinks[] = new NextLink($this->buildUrl($request, ['page' => ['offset' => $offset + $limit]]));
}
return $paginationLinks;
}
private function paginate(ResourceType $resourceType, $query, Context $context): array
private function sort($query, Context $context)
{
$schema = $resourceType->getSchema();
$schema = $this->resource->getSchema();
if (! $sort = $context->getRequest()->getQueryParams()['sort'] ?? $schema->getDefaultSort()) {
return;
}
$adapter = $this->resource->getAdapter();
$sortFields = $schema->getSortFields();
$fields = $schema->getFields();
foreach ($this->parseSort($sort) as $name => $direction) {
if (isset($sortFields[$name])) {
$sortFields[$name]($query, $direction, $context);
continue;
}
if (
isset($fields[$name])
&& $fields[$name] instanceof Attribute
&& evaluate($fields[$name]->getSortable(), [$context])
) {
$adapter->sortByAttribute($query, $fields[$name], $direction);
continue;
}
throw new BadRequestException("Invalid sort field [$name]", 'sort');
}
}
private function parseSort(string $string): array
{
$sort = [];
foreach (explode(',', $string) as $field) {
if ($field[0] === '-') {
$field = substr($field, 1);
$direction = 'desc';
} else {
$direction = 'asc';
}
$sort[$field] = $direction;
}
return $sort;
}
private function paginate($query, Context $context)
{
$schema = $this->resource->getSchema();
$queryParams = $context->getRequest()->getQueryParams();
$limit = $schema->getPerPage();
@ -181,7 +205,7 @@ class Index
$limit = $queryParams['page']['limit'];
if (! ctype_digit(strval($limit)) || $limit < 1) {
throw (new BadRequestException('page[limit] must be a positive integer'))->setSourceParameter('page[limit]');
throw new BadRequestException('page[limit] must be a positive integer', 'page[limit]');
}
$limit = min($schema->getLimit(), $limit);
@ -193,14 +217,81 @@ class Index
$offset = $queryParams['page']['offset'];
if (! ctype_digit(strval($offset)) || $offset < 0) {
throw (new BadRequestException('page[offset] must be a non-negative integer'))->setSourceParameter('page[offset]');
throw new BadRequestException('page[offset] must be a non-negative integer', 'page[offset]');
}
}
if ($limit || $offset) {
$resourceType->getAdapter()->paginate($query, $limit, $offset);
$this->resource->getAdapter()->paginate($query, $limit, $offset);
}
return [$offset, $limit];
}
private function filter($query, Context $context)
{
if (! $filter = $context->getRequest()->getQueryParams()['filter'] ?? null) {
return;
}
if (! is_array($filter)) {
throw new BadRequestException('filter must be an array', 'filter');
}
$schema = $this->resource->getSchema();
$adapter = $this->resource->getAdapter();
$filters = $schema->getFilters();
$fields = $schema->getFields();
foreach ($filter as $name => $value) {
if ($name === 'id') {
$adapter->filterByIds($query, explode(',', $value));
continue;
}
if (isset($filters[$name]) && evaluate($filters[$name]->getVisible(), [$context])) {
$filters[$name]->getCallback()($query, $value, $context);
continue;
}
if (isset($fields[$name]) && evaluate($fields[$name]->getFilterable(), [$context])) {
if ($fields[$name] instanceof Attribute) {
$this->filterByAttribute($adapter, $query, $fields[$name], $value);
} elseif ($fields[$name] instanceof HasOne) {
$value = array_filter(explode(',', $value));
$adapter->filterByHasOne($query, $fields[$name], $value);
} elseif ($fields[$name] instanceof HasMany) {
$value = array_filter(explode(',', $value));
$adapter->filterByHasMany($query, $fields[$name], $value);
}
continue;
}
throw new BadRequestException("Invalid filter [$name]", "filter[$name]");
}
}
private function filterByAttribute(AdapterInterface $adapter, $query, Attribute $attribute, $value)
{
if (preg_match('/(.+)\.\.(.+)/', $value, $matches)) {
if ($matches[1] !== '*') {
$adapter->filterByAttribute($query, $attribute, $value, '>=');
}
if ($matches[2] !== '*') {
$adapter->filterByAttribute($query, $attribute, $value, '<=');
}
return;
}
foreach (['>=', '>', '<=', '<'] as $operator) {
if (strpos($value, $operator) === 0) {
$adapter->filterByAttribute($query, $attribute, substr($value, strlen($operator)), $operator);
return;
}
}
$adapter->filterByAttribute($query, $attribute, $value);
}
}

View File

@ -14,37 +14,43 @@ namespace Tobyz\JsonApiServer\Endpoint;
use JsonApiPhp\JsonApi\CompoundDocument;
use JsonApiPhp\JsonApi\Included;
use Psr\Http\Message\ResponseInterface;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Endpoint\Concerns\BuildsMeta;
use Tobyz\JsonApiServer\Endpoint\Concerns\IncludesData;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\ResourceType;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Serializer;
use function Tobyz\JsonApiServer\json_api_response;
use function Tobyz\JsonApiServer\run_callbacks;
class Show
{
use IncludesData;
use BuildsMeta;
use Concerns\IncludesData;
public function handle(Context $context, ResourceType $resourceType, $model): ResponseInterface
private $api;
private $resource;
private $model;
public function __construct(JsonApi $api, ResourceType $resource, $model)
{
run_callbacks($resourceType->getSchema()->getListeners('show'), [&$model, $context]);
$this->api = $api;
$this->resource = $resource;
$this->model = $model;
}
$include = $this->getInclude($context, $resourceType);
public function handle(Context $context): ResponseInterface
{
$include = $this->getInclude($context);
$serializer = new Serializer($context);
$serializer->add($resourceType, $model, $include);
$this->loadRelationships([$this->model], $include, $context);
[$primary, $included] = $serializer->serialize();
run_callbacks($this->resource->getSchema()->getListeners('show'), [&$this->model, $context]);
$serializer = new Serializer($this->api, $context);
$serializer->add($this->resource, $this->model, $include);
return json_api_response(
new CompoundDocument(
$primary[0],
new Included(...$included),
$this->buildJsonApiObject($context),
...$this->buildMeta($context)
$serializer->primary()[0],
new Included(...$serializer->included())
)
);
}

View File

@ -12,50 +12,53 @@
namespace Tobyz\JsonApiServer\Endpoint;
use Psr\Http\Message\ResponseInterface;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Endpoint\Concerns\BuildsMeta;
use Tobyz\JsonApiServer\Endpoint\Concerns\SavesData;
use Tobyz\JsonApiServer\Exception\ForbiddenException;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\ResourceType;
use Tobyz\JsonApiServer\Context;
use function Tobyz\JsonApiServer\evaluate;
use function Tobyz\JsonApiServer\run_callbacks;
class Update
{
use SavesData;
use Concerns\SavesData;
private $api;
private $resource;
private $model;
public function __construct(JsonApi $api, ResourceType $resource, $model)
{
$this->api = $api;
$this->resource = $resource;
$this->model = $model;
}
/**
* @throws ForbiddenException if the resource is not updatable.
*/
public function handle(Context $context, ResourceType $resourceType, $model): ResponseInterface
public function handle(Context $context): ResponseInterface
{
$schema = $resourceType->getSchema();
$schema = $this->resource->getSchema();
if (! evaluate($schema->isUpdatable(), [$model, $context])) {
throw new ForbiddenException(sprintf(
'Cannot update resource %s:%s',
$resourceType->getType(),
$resourceType->getAdapter()->getId($model)
));
if (! evaluate($schema->isUpdatable(), [$this->model, $context])) {
throw new ForbiddenException;
}
$data = $this->parseData($resourceType, $context->getBody(), $model);
$data = $this->parseData($context->getRequest()->getParsedBody(), $this->model);
$this->validateFields($resourceType, $data, $model, $context);
$this->loadRelatedResources($resourceType, $data, $context);
$this->assertDataValid($resourceType, $data, $model, $context, false);
$this->setValues($resourceType, $data, $model, $context);
$this->validateFields($data, $this->model, $context);
$this->loadRelatedResources($data, $context);
$this->assertDataValid($data, $this->model, $context, false);
$this->setValues($data, $this->model, $context);
run_callbacks($schema->getListeners('updating'), [&$model, $context]);
run_callbacks($schema->getListeners('updating'), [&$this->model, $context]);
$this->save($resourceType, $data, $model, $context);
$this->save($data, $this->model, $context);
run_callbacks($schema->getListeners('updated'), [&$model, $context]);
run_callbacks($schema->getListeners('updated'), [&$this->model, $context]);
$model = $this->freshModel($resourceType, $model, $context);
return (new Show())
->handle($context, $resourceType, $model);
return (new Show($this->api, $this->resource, $this->model))
->handle($context);
}
}

View File

@ -17,23 +17,16 @@ use Tobyz\JsonApiServer\ErrorProviderInterface;
class BadRequestException extends DomainException implements ErrorProviderInterface
{
private $sourceType;
private $source;
/**
* @var string
*/
private $sourceParameter;
public function setSourceParameter(string $parameter)
public function __construct(string $message = '', string $sourceParameter = '')
{
$this->sourceType = 'parameter';
$this->source = $parameter;
parent::__construct($message);
return $this;
}
public function setSourcePointer(string $pointer)
{
$this->sourceType = 'pointer';
$this->source = $pointer;
return $this;
$this->sourceParameter = $sourceParameter;
}
public function getJsonApiErrors(): array
@ -44,10 +37,8 @@ class BadRequestException extends DomainException implements ErrorProviderInterf
$members[] = new Error\Detail($this->message);
}
if ($this->sourceType === 'parameter') {
$members[] = new Error\SourceParameter($this->source);
} elseif ($this->sourceType === 'pointer') {
$members[] = new Error\SourcePointer($this->source);
if ($this->sourceParameter) {
$members[] = new Error\SourceParameter($this->sourceParameter);
}
return [

View File

@ -1,35 +0,0 @@
<?php
/*
* This file is part of tobyz/json-api-server.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tobyz\JsonApiServer\Exception;
use DomainException;
use JsonApiPhp\JsonApi\Error;
use Tobyz\JsonApiServer\ErrorProviderInterface;
class ConflictException extends DomainException implements ErrorProviderInterface
{
public function getJsonApiErrors(): array
{
return [
new Error(
new Error\Title('Conflict'),
new Error\Status($this->getJsonApiStatus()),
...($this->message ? [new Error\Detail($this->message)] : [])
)
];
}
public function getJsonApiStatus(): string
{
return '409';
}
}

View File

@ -22,8 +22,7 @@ class ForbiddenException extends DomainException implements ErrorProviderInterfa
return [
new Error(
new Error\Title('Forbidden'),
new Error\Status($this->getJsonApiStatus()),
...($this->message ? [new Error\Detail($this->message)] : [])
new Error\Status($this->getJsonApiStatus())
)
];
}

View File

@ -1,184 +0,0 @@
<?php
/*
* This file is part of tobyz/json-api-server.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tobyz\JsonApiServer\Extension;
use Nyholm\Psr7\Uri;
use Psr\Http\Message\ResponseInterface as Response;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Endpoint;
use Tobyz\JsonApiServer\Endpoint\Concerns\FindsResources;
use Tobyz\JsonApiServer\Exception\BadRequestException;
use Tobyz\JsonApiServer\Exception\MethodNotAllowedException;
use Tobyz\JsonApiServer\Exception\NotImplementedException;
use function Tobyz\JsonApiServer\json_api_response;
final class Atomic extends Extension
{
use FindsResources;
private $path;
public function __construct(string $path = 'operations')
{
$this->path = $path;
}
public function uri(): string
{
return 'https://jsonapi.org/ext/atomic';
}
public function handle(Context $context): ?Response
{
if ($context->getPath() !== '/operations') {
return null;
}
$request = $context->getRequest();
if ($request->getMethod() !== 'POST') {
throw new MethodNotAllowedException();
}
$body = $context->getBody();
$operations = $body['atomic:operations'] ?? null;
if (! is_array($operations)) {
throw new BadRequestException('atomic:operations must be an array of operation objects');
}
$results = [];
$lids = [];
foreach ($operations as $i => $operation) {
switch ($operation['op'] ?? null) {
case 'add':
$response = $this->add($context, $operation, $lids);
break;
case 'update':
$response = $this->update($context, $operation, $lids);
break;
case 'remove':
$response = $this->remove($context, $operation, $lids);
break;
default:
throw (new BadRequestException('Invalid operation'))->setSourcePointer("/atomic:operations/$i");
}
$results[] = json_decode($response->getBody(), true);
}
return json_api_response(
['atomic:results' => $results]
);
}
private function add(Context $context, array $operation, array &$lids): Response
{
// TODO: support href and ref
if (isset($operation['href']) || isset($operation['ref'])) {
throw new NotImplementedException('href and ref are not currently supported');
}
$type = $operation['data']['type'];
$resourceType = $context->getApi()->getResourceType($type);
$request = $context->getRequest()
->withMethod('POST')
->withUri(new Uri("/$type"))
->withQueryParams($operation['params'] ?? [])
->withParsedBody(array_diff_key($this->replaceLids($operation, $lids), ['op', 'href', 'ref', 'params']));
$context = $context->withRequest($request);
$response = (new Endpoint\Create())->handle($context, $resourceType);
if ($lid = $operation['data']['lid'] ?? null) {
if ($id = json_decode($response->getBody(), true)['data']['id'] ?? null) {
$lids[$lid] = $id;
}
}
return $response;
}
private function update(Context $context, array $operation, array $lids): Response
{
// TODO: support href and ref
if (isset($operation['href']) || isset($operation['ref'])) {
throw new NotImplementedException('href and ref are not currently supported');
}
$operation = $this->replaceLids($operation, $lids);
$type = $operation['data']['type'];
$id = $operation['data']['id'];
$resourceType = $context->getApi()->getResourceType($type);
$request = $context->getRequest()
->withMethod('PATCH')
->withUri(new Uri("/$type/$id"))
->withQueryParams($operation['params'] ?? [])
->withParsedBody(array_diff_key($operation, ['op', 'href', 'ref', 'params']));
$context = $context->withRequest($request);
$model = $this->findResource($resourceType, $id, $context);
return (new Endpoint\Update())->handle($context, $resourceType, $model);
}
private function remove(Context $context, array $operation, array $lids): Response
{
// TODO: support href
if (isset($operation['href'])) {
throw new NotImplementedException('href is not currently supported');
}
$operation = $this->replaceLids($operation, $lids);
$type = $operation['ref']['type'];
$id = $operation['ref']['id'];
$resourceType = $context->getApi()->getResourceType($type);
$request = $context->getRequest()
->withMethod('DELETE')
->withUri(new Uri("/$type/$id"))
->withQueryParams($operation['params'] ?? [])
->withParsedBody(array_diff_key($operation, ['op', 'href', 'ref', 'params']));
$context = $context->withRequest($request);
$model = $this->findResource($resourceType, $id, $context);
return (new Endpoint\Delete())->handle($context, $resourceType, $model);
}
private function replaceLids(array &$array, array $lids): array
{
foreach ($array as $k => &$v) {
if ($k === 'lid' && isset($lids[$v])) {
$array['id'] = $lids[$v];
unset($array['lid']);
continue;
}
if (is_array($v)) {
$v = $this->replaceLids($v, $lids);
}
}
return $array;
}
}

View File

@ -1,33 +0,0 @@
<?php
/*
* This file is part of tobyz/json-api-server.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tobyz\JsonApiServer\Extension;
use Psr\Http\Message\ResponseInterface as Response;
use Tobyz\JsonApiServer\Context;
abstract class Extension
{
/**
* The URI that uniquely identifies this extension.
*
* @see https://jsonapi.org/format/1.1/#media-type-parameter-rules
*/
abstract public function uri(): string;
/**
* Handle a request.
*/
public function handle(Context $context): ?Response
{
return null;
}
}

65
src/Http/MediaTypes.php Normal file
View File

@ -0,0 +1,65 @@
<?php
/*
* This file is part of tobyz/json-api-server.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tobyz\JsonApiServer\Http;
class MediaTypes
{
private $value;
public function __construct(string $value)
{
$this->value = $value;
}
/**
* Determine whether the list contains the given type without modifications
*
* This is meant to ease implementation of JSON:API rules for content
* negotiation, which demand HTTP error responses e.g. when all of the
* JSON:API media types in the "Accept" header are modified with "media type
* parameters". Therefore, this method only returns true when the requested
* media type is contained without additional parameters (except for the
* weight parameter "q" and "Accept extension parameters").
*
* @param string $mediaType
* @return bool
*/
public function containsExactly(string $mediaType): bool
{
$types = array_map('trim', explode(',', $this->value));
// Accept headers can contain multiple media types, so we need to check
// whether any of them matches.
foreach ($types as $type) {
$parts = array_map('trim', explode(';', $type));
// The actual media type needs to be an exact match
if (array_shift($parts) !== $mediaType) {
continue;
}
// The media type can optionally be followed by "media type
// parameters". Parameters after the "q" parameter are considered
// "Accept extension parameters", which we don't care about. Thus,
// we have an exact match if there are no parameters at all or if
// the first one is named "q".
// See https://tools.ietf.org/html/rfc7231#section-5.3.2.
if (empty($parts) || substr($parts[0], 0, 2) === 'q=') {
return true;
}
continue;
}
return false;
}
}

View File

@ -11,13 +11,11 @@
namespace Tobyz\JsonApiServer;
use HttpAccept\AcceptParser;
use JsonApiPhp\JsonApi\ErrorDocument;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface;
use Tobyz\JsonApiServer\Adapter\AdapterInterface;
use Tobyz\JsonApiServer\Endpoint\Concerns\FindsResources;
use Tobyz\JsonApiServer\Exception\BadRequestException;
use Tobyz\JsonApiServer\Exception\InternalServerErrorException;
use Tobyz\JsonApiServer\Exception\MethodNotAllowedException;
@ -25,58 +23,32 @@ use Tobyz\JsonApiServer\Exception\NotAcceptableException;
use Tobyz\JsonApiServer\Exception\NotImplementedException;
use Tobyz\JsonApiServer\Exception\ResourceNotFoundException;
use Tobyz\JsonApiServer\Exception\UnsupportedMediaTypeException;
use Tobyz\JsonApiServer\Extension\Extension;
use Tobyz\JsonApiServer\Endpoint\Concerns\FindsResources;
use Tobyz\JsonApiServer\Http\MediaTypes;
use Tobyz\JsonApiServer\Schema\Concerns\HasMeta;
use Tobyz\JsonApiServer\Context;
final class JsonApi implements RequestHandlerInterface
{
public const MEDIA_TYPE = 'application/vnd.api+json';
const MEDIA_TYPE = 'application/vnd.api+json';
use FindsResources;
use HasMeta;
/**
* @var string
*/
private $resources = [];
private $basePath;
/**
* @var Extension[]
*/
private $extensions = [];
/**
* @var ResourceType[]
*/
private $resourceTypes = [];
public function __construct(string $basePath)
{
$this->basePath = $basePath;
}
/**
* Register an extension.
*/
public function extension(Extension $extension)
{
$this->extensions[$extension->uri()] = $extension;
}
/**
* Get all registered extensions.
*/
public function getExtensions(): array
{
return $this->extensions;
}
/**
* Define a new resource type.
*/
public function resourceType(string $type, AdapterInterface $adapter, callable $buildSchema = null): void
public function resource(string $type, AdapterInterface $adapter, callable $buildSchema = null): void
{
$this->resourceTypes[$type] = new ResourceType($type, $adapter, $buildSchema);
$this->resources[$type] = new ResourceType($type, $adapter, $buildSchema);
}
/**
@ -84,9 +56,9 @@ final class JsonApi implements RequestHandlerInterface
*
* @return ResourceType[]
*/
public function getResourceTypes(): array
public function getResources(): array
{
return $this->resourceTypes;
return $this->resources;
}
/**
@ -94,13 +66,13 @@ final class JsonApi implements RequestHandlerInterface
*
* @throws ResourceNotFoundException if the resource type has not been defined.
*/
public function getResourceType(string $type): ResourceType
public function getResource(string $type): ResourceType
{
if (! isset($this->resourceTypes[$type])) {
if (! isset($this->resources[$type])) {
throw new ResourceNotFoundException($type);
}
return $this->resourceTypes[$type];
return $this->resources[$type];
}
/**
@ -114,184 +86,129 @@ final class JsonApi implements RequestHandlerInterface
*/
public function handle(Request $request): Response
{
$this->validateQueryParameters($request);
$this->validateRequest($request);
$context = new Context($this, $request);
$response = $this->runExtensions($context);
if (! $response) {
$response = $this->route($context);
}
return $response->withAddedHeader('Vary', 'Accept');
}
private function runExtensions(Context $context): ?Response
{
$request = $context->getRequest();
$contentTypeExtensionUris = $this->getContentTypeExtensionUris($request);
$acceptableExtensionUris = $this->getAcceptableExtensionUris($request);
$activeExtensions = array_intersect_key(
$this->extensions,
array_flip($contentTypeExtensionUris),
array_flip($acceptableExtensionUris)
$path = $this->stripBasePath(
$request->getUri()->getPath()
);
foreach ($activeExtensions as $extension) {
if ($response = $extension->handle($context)) {
return $response->withHeader('Content-Type', self::MEDIA_TYPE.'; ext='.$extension->uri());
}
}
return null;
}
private function route(Context $context): Response
{
$segments = explode('/', trim($context->getPath(), '/'));
$resourceType = $this->getResourceType($segments[0]);
$segments = explode('/', trim($path, '/'));
$resource = $this->getResource($segments[0]);
$context = new Context($request);
switch (count($segments)) {
case 1:
return $this->routeCollection($context, $resourceType);
return $this->handleCollection($context, $resource);
case 2:
return $this->routeResource($context, $resourceType, $segments[1]);
return $this->handleResource($context, $resource, $segments[1]);
case 3:
throw new NotImplementedException();
throw new NotImplementedException;
case 4:
if ($segments[2] === 'relationships') {
throw new NotImplementedException();
throw new NotImplementedException;
}
}
throw new BadRequestException();
throw new BadRequestException;
}
private function validateQueryParameters(Request $request): void
private function validateRequest(Request $request): void
{
foreach ($request->getQueryParams() as $key => $value) {
if (
! preg_match('/[^a-z]/', $key)
&& ! in_array($key, ['include', 'fields', 'filter', 'page', 'sort'])
) {
throw (new BadRequestException('Invalid query parameter: '.$key))->setSourceParameter($key);
}
}
$this->validateRequestContentType($request);
$this->validateRequestAccepts($request);
}
private function routeCollection(Context $context, ResourceType $resourceType): Response
private function validateRequestContentType(Request $request): void
{
$header = $request->getHeaderLine('Content-Type');
if (empty($header)) {
return;
}
if ((new MediaTypes($header))->containsExactly(self::MEDIA_TYPE)) {
return;
}
throw new UnsupportedMediaTypeException;
}
private function validateRequestAccepts(Request $request): void
{
$header = $request->getHeaderLine('Accept');
if (empty($header)) {
return;
}
$mediaTypes = new MediaTypes($header);
if ($mediaTypes->containsExactly('*/*') || $mediaTypes->containsExactly(self::MEDIA_TYPE)) {
return;
}
throw new NotAcceptableException;
}
private function stripBasePath(string $path): string
{
$basePath = parse_url($this->basePath, PHP_URL_PATH);
$len = strlen($basePath);
if (substr($path, 0, $len) === $basePath) {
$path = substr($path, $len);
}
return $path;
}
private function handleCollection(Context $context, ResourceType $resource): Response
{
switch ($context->getRequest()->getMethod()) {
case 'GET':
return (new Endpoint\Index())->handle($context, $resourceType);
return (new Endpoint\Index($this, $resource))->handle($context);
case 'POST':
return (new Endpoint\Create())->handle($context, $resourceType);
return (new Endpoint\Create($this, $resource))->handle($context);
default:
throw new MethodNotAllowedException();
throw new MethodNotAllowedException;
}
}
private function routeResource(Context $context, ResourceType $resourceType, string $resourceId): Response
private function handleResource(Context $context, ResourceType $resource, string $id): Response
{
$model = $this->findResource($resourceType, $resourceId, $context);
$model = $this->findResource($resource, $id, $context);
switch ($context->getRequest()->getMethod()) {
case 'PATCH':
return (new Endpoint\Update())->handle($context, $resourceType, $model);
return (new Endpoint\Update($this, $resource, $model))->handle($context);
case 'GET':
return (new Endpoint\Show())->handle($context, $resourceType, $model);
return (new Endpoint\Show($this, $resource, $model))->handle($context);
case 'DELETE':
return (new Endpoint\Delete())->handle($context, $resourceType, $model);
return (new Endpoint\Delete($this, $resource, $model))->handle($context);
default:
throw new MethodNotAllowedException();
throw new MethodNotAllowedException;
}
}
private function getContentTypeExtensionUris(Request $request): array
{
if (! $contentType = $request->getHeaderLine('Content-Type')) {
return [];
}
$mediaList = (new AcceptParser())->parse($contentType);
if ($mediaList->count() > 1) {
throw new UnsupportedMediaTypeException();
}
$mediaType = $mediaList->preferredMedia(0);
if ($mediaType->mimetype() !== JsonApi::MEDIA_TYPE) {
throw new UnsupportedMediaTypeException();
}
$parameters = $mediaType->parameter();
if (! empty(array_diff(array_keys($parameters->all()), ['ext', 'profile']))) {
throw new UnsupportedMediaTypeException();
}
$extensionUris = $parameters->has('ext') ? explode(' ', $parameters->get('ext')) : [];
if (! empty(array_diff($extensionUris, array_keys($this->extensions)))) {
throw new UnsupportedMediaTypeException();
}
return $extensionUris;
}
private function getAcceptableExtensionUris(Request $request): array
{
if (! $accept = $request->getHeaderLine('Accept')) {
return [];
}
$mediaList = (new AcceptParser())->parse($accept);
foreach ($mediaList->all() as $mediaType) {
if (! in_array($mediaType->mimetype(), [JsonApi::MEDIA_TYPE, '*/*'])) {
continue;
}
$parameters = $mediaType->parameter();
if (! empty(array_diff(array_keys($parameters->all()), ['ext', 'profile']))) {
continue;
}
$extensionUris = $parameters->has('ext') ? explode(' ', $parameters->get('ext')) : [];
if (! empty(array_diff($extensionUris, array_keys($this->extensions)))) {
continue;
}
return $extensionUris;
}
throw new NotAcceptableException();
}
/**
* Convert an exception into a JSON:API error document response.
*
* If the exception is not an instance of ErrorProviderInterface, an
* Internal Server Error response will be produced.
*/
public function error($e): Response
public function error($e)
{
if (! $e instanceof ErrorProviderInterface) {
$e = new InternalServerErrorException();
$e = new InternalServerErrorException;
}
$errors = $e->getJsonApiErrors();
@ -309,20 +226,4 @@ final class JsonApi implements RequestHandlerInterface
{
return $this->basePath;
}
/**
* Strip the API's base path from the start of the given path.
*/
public function stripBasePath(string $path): string
{
$basePath = parse_url($this->basePath, PHP_URL_PATH) ?: '';
$len = strlen($basePath);
if (substr($path, 0, $len) === $basePath) {
$path = substr($path, $len);
}
return $path;
}
}

View File

@ -12,9 +12,6 @@
namespace Tobyz\JsonApiServer;
use Tobyz\JsonApiServer\Adapter\AdapterInterface;
use Tobyz\JsonApiServer\Exception\BadRequestException;
use Tobyz\JsonApiServer\Schema\Attribute;
use Tobyz\JsonApiServer\Schema\Relationship;
use Tobyz\JsonApiServer\Schema\Type;
final class ResourceType
@ -44,7 +41,7 @@ final class ResourceType
public function getSchema(): Type
{
if (! $this->schema) {
$this->schema = new Type();
$this->schema = new Type;
if ($this->buildSchema) {
($this->buildSchema)($this->schema);
@ -53,151 +50,4 @@ final class ResourceType
return $this->schema;
}
/**
* Get the URL for a model.
*/
public function url($model, Context $context): string
{
$id = $this->adapter->getId($model);
return $context->getApi()->getBasePath()."/$this->type/$id";
}
/**
* Apply the resource type's scopes to a query.
*/
public function applyScopes($query, Context $context): void
{
run_callbacks(
$this->getSchema()->getListeners('scope'),
[$query, $context]
);
}
/**
* Apply the resource type's filters to a query.
*/
public function applySort($query, string $sortString, Context $context): void
{
$schema = $this->getSchema();
$customSorts = $schema->getSorts();
$fields = $schema->getFields();
foreach (parse_sort_string($sortString) as [$name, $direction]) {
if (
isset($customSorts[$name])
&& evaluate($customSorts[$name]->getVisible(), [$context])
) {
$customSorts[$name]->getCallback()($query, $direction, $context);
continue;
}
$field = $fields[$name] ?? null;
if (
$field instanceof Attribute
&& evaluate($field->getSortable(), [$context])
) {
$this->adapter->sortByAttribute($query, $field, $direction);
continue;
}
throw (new BadRequestException("Invalid sort field: $name"))->setSourceParameter('sort');
}
}
/**
* Apply the resource type's filters to a query.
*/
public function applyFilters($query, $filters, Context $context): void
{
$schema = $this->getSchema();
$customFilters = $schema->getFilters();
$fields = $schema->getFields();
if (is_string($filters)) {
$this->adapter->filterByExpression($query, $filters);
return;
}
foreach ($filters as $name => $value) {
if ($name === 'id') {
$this->adapter->filterByIds($query, explode(',', $value));
continue;
}
if (is_int($name)) {
$this->adapter->filterByExpression($query, $value);
continue;
}
if (
isset($customFilters[$name])
&& evaluate($customFilters[$name]->getVisible(), [$context])
) {
$customFilters[$name]->getCallback()($query, $value, $context);
continue;
}
[$name, $sub] = explode('.', $name, 2) + [null, null];
$field = $fields[$name] ?? null;
if ($field && evaluate($field->getFilterable(), [$context])) {
if ($field instanceof Attribute && $sub === null) {
$this->filterByAttribute($query, $field, $value);
continue;
}
if ($field instanceof Relationship) {
if (is_string($relatedType = $field->getType())) {
$relatedResource = $context->getApi()->getResourceType($relatedType);
$this->adapter->filterByRelationship($query, $field, function ($query) use ($relatedResource, $sub, $value, $context) {
$relatedResource->applyFilters($query, [($sub ?? 'id') => $value], $context);
});
continue;
}
throw (new BadRequestException('Cannot filter on attribute of polymorphic relationship: '.$name))
->setSourceParameter("filter[$name]");
}
}
throw (new BadRequestException("Invalid filter: $name"))->setSourceParameter("filter[$name]");
}
}
/**
* Apply the resource type's sparse fieldsets to a query.
*/
public function applySparseFieldset($query, $fields, Context $context): void
{
$this->adapter->sparseFieldset($query, $fields);
}
private function filterByAttribute($query, Attribute $attribute, $value): void
{
if (preg_match('/(.+)\.\.(.+)/', $value, $matches)) {
if ($matches[1] !== '*') {
$this->adapter->filterByAttribute($query, $attribute, $value, '>=');
}
if ($matches[2] !== '*') {
$this->adapter->filterByAttribute($query, $attribute, $value, '<=');
}
return;
}
foreach (['>=', '>', '<=', '<'] as $operator) {
if (strpos($value, $operator) === 0) {
$this->adapter->filterByAttribute($query, $attribute, substr($value, strlen($operator)), $operator);
return;
}
}
$this->adapter->filterByAttribute($query, $attribute, $value);
}
}

View File

@ -1,7 +1,7 @@
<?php
/*
* This file is part of tobyz/json-api-server.
* This file is part of Forust.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*

View File

@ -135,7 +135,7 @@ abstract class Field
/**
* Run a callback after this field has been saved.
*/
public function saved(callable $callback)
public function onSaved(callable $callback)
{
$this->listeners['saved'][] = $callback;

View File

@ -68,6 +68,26 @@ abstract class Relationship extends Field
return $this;
}
/**
* Allow the relationship data to be eager-loaded into the model collection.
*/
public function load()
{
$this->load = true;
return $this;
}
/**
* Do not eager-load relationship data into the model collection.
*/
public function dontLoad()
{
$this->load = false;
return $this;
}
/**
* Allow the relationship data to be included in a compound document.
*/
@ -133,6 +153,14 @@ abstract class Relationship extends Field
// return $this->urls;
// }
/**
* @return bool|callable
*/
public function shouldLoad()
{
return $this->load;
}
public function isIncludable(): bool
{
return $this->includable;

View File

@ -1,40 +0,0 @@
<?php
/*
* This file is part of tobyz/json-api-server.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tobyz\JsonApiServer\Schema;
use Tobyz\JsonApiServer\Schema\Concerns\HasDescription;
use Tobyz\JsonApiServer\Schema\Concerns\HasVisibility;
final class Sort
{
use HasDescription;
use HasVisibility;
private $name;
private $callback;
public function __construct(string $name, callable $callback)
{
$this->name = $name;
$this->callback = $callback;
}
public function getName(): string
{
return $this->name;
}
public function getCallback(): callable
{
return $this->callback;
}
}

View File

@ -24,14 +24,14 @@ final class Type
private $fields = [];
private $filters = [];
private $sorts = [];
private $sortFields = [];
private $perPage = 20;
private $limit = 50;
private $countable = true;
private $listable = true;
private $defaultSort;
private $saveCallback;
private $modelCallback;
private $newModelCallback;
private $creatable = false;
private $updatable = false;
private $deletable = false;
@ -118,15 +118,15 @@ final class Type
*/
public function sort(string $name, callable $callback): void
{
$this->sorts[$name] = new Sort($name, $callback);
$this->sortFields[$name] = $callback;
}
/**
* Get the resource type's sort fields.
*/
public function getSorts(): array
public function getSortFields(): array
{
return $this->sorts;
return $this->sortFields;
}
/**
@ -174,7 +174,7 @@ final class Type
* Get the maximum number of records that can be listed, or null if there
* is no limit.
*/
public function getLimit(): ?int
public function getLimit(): int
{
return $this->limit;
}
@ -214,9 +214,17 @@ final class Type
/**
* Run a callback before a resource is shown.
*/
public function show(callable $callback): void
public function onShowing(callable $callback): void
{
$this->listeners['show'][] = $callback;
$this->listeners['showing'][] = $callback;
}
/**
* Run a callback when a resource is shown.
*/
public function onShown(callable $callback): void
{
$this->listeners['shown'][] = $callback;
}
/**
@ -246,7 +254,7 @@ final class Type
/**
* Run a callback before the resource type is listed.
*/
public function listing(callable $callback): void
public function onListing(callable $callback): void
{
$this->listeners['listing'][] = $callback;
}
@ -254,7 +262,7 @@ final class Type
/**
* Run a callback when the resource type is listed.
*/
public function listed(callable $callback): void
public function onListed(callable $callback): void
{
$this->listeners['listed'][] = $callback;
}
@ -264,17 +272,17 @@ final class Type
*
* If null, the adapter will be used to create new model instances.
*/
public function model(?callable $callback): void
public function newModel(?callable $callback): void
{
$this->modelCallback = $callback;
$this->newModelCallback = $callback;
}
/**
* Get the callback to create a new model instance.
*/
public function getModelCallback(): ?callable
public function getNewModelCallback(): ?callable
{
return $this->modelCallback;
return $this->newModelCallback;
}
/**
@ -304,7 +312,7 @@ final class Type
/**
* Run a callback before a resource is created.
*/
public function creating(callable $callback): void
public function onCreating(callable $callback): void
{
$this->listeners['creating'][] = $callback;
}
@ -312,7 +320,7 @@ final class Type
/**
* Run a callback after a resource has been created.
*/
public function created(callable $callback): void
public function onCreated(callable $callback): void
{
$this->listeners['created'][] = $callback;
}
@ -344,7 +352,7 @@ final class Type
/**
* Run a callback before a resource has been updated.
*/
public function updating(callable $callback): void
public function onUpdating(callable $callback): void
{
$this->listeners['updating'][] = $callback;
}
@ -352,7 +360,7 @@ final class Type
/**
* Run a callback after a resource has been updated.
*/
public function updated(callable $callback): void
public function onUpdated(callable $callback): void
{
$this->listeners['updated'][] = $callback;
}
@ -420,7 +428,7 @@ final class Type
/**
* Run a callback before a resource has been deleted.
*/
public function deleting(callable $callback): void
public function onDeleting(callable $callback): void
{
$this->listeners['deleting'][] = $callback;
}
@ -428,7 +436,7 @@ final class Type
/**
* Run a callback after a resource has been deleted.
*/
public function deleted(callable $callback): void
public function onDeleted(callable $callback): void
{
$this->listeners['deleted'][] = $callback;
}

View File

@ -15,207 +15,185 @@ use DateTime;
use DateTimeInterface;
use JsonApiPhp\JsonApi as Structure;
use RuntimeException;
use Tobyz\JsonApiServer\Schema\Attribute;
use Tobyz\JsonApiServer\Schema\Field;
use Tobyz\JsonApiServer\Schema\HasMany;
use Tobyz\JsonApiServer\Schema\HasOne;
use Tobyz\JsonApiServer\Schema\Meta;
use Tobyz\JsonApiServer\Schema\Relationship;
final class Serializer
{
private $api;
private $context;
private $map = [];
private $primary = [];
private $deferred = [];
public function __construct(Context $context)
public function __construct(JsonApi $api, Context $context)
{
$this->api = $api;
$this->context = $context;
}
/**
* Add a primary resource to the document.
*/
public function add(ResourceType $resourceType, $model, array $include): void
public function add(ResourceType $resource, $model, array $include): void
{
$data = $this->addToMap($resourceType, $model, $include);
$data = $this->addToMap($resource, $model, $include);
$this->primary[] = $this->key($data['type'], $data['id']);
$this->primary[] = $this->key($data);
}
/**
* Serialize the primary and included resources into a JSON:API resource objects.
* Get the serialized primary resources.
*/
public function serialize(): array
public function primary(): array
{
$this->resolveDeferred();
$primary = array_map(function ($key) {
return $this->map[$key];
}, $this->primary);
$keys = array_flip($this->primary);
$primary = array_values(array_intersect_key($this->map, $keys));
$included = array_values(array_diff_key($this->map, $keys));
return [
$this->resourceObjects($primary),
$this->resourceObjects($included),
];
return $this->resourceObjects($primary);
}
private function addToMap(ResourceType $resourceType, $model, array $include): array
/**
* Get the serialized included resources.
*/
public function included(): array
{
$adapter = $resourceType->getAdapter();
$schema = $resourceType->getSchema();
$included = array_values(array_diff_key($this->map, array_flip($this->primary)));
$key = $this->key(
$type = $resourceType->getType(),
$id = $adapter->getId($model)
);
return $this->resourceObjects($included);
}
if (isset($this->map[$key])) {
return $this->map[$key];
}
private function addToMap(ResourceType $resource, $model, array $include): array
{
$adapter = $resource->getAdapter();
$schema = $resource->getSchema();
$this->map[$key] = [
'type' => $type,
'id' => $id,
$data = [
'type' => $type = $resource->getType(),
'id' => $id = $adapter->getId($model),
'fields' => [],
'links' => [
'self' => new Structure\Link\SelfLink($url = $resourceType->url($model, $this->context)),
],
'meta' => $this->meta($schema->getMeta(), $model)
'links' => [],
'meta' => []
];
$fields = $this->sparseFields($type, $schema->getFields());
$key = $this->key($data);
$url = $this->api->getBasePath()."/$type/$id";
$fields = $schema->getFields();
$queryParams = $this->context->getRequest()->getQueryParams();
if (isset($queryParams['fields'][$type])) {
$fields = array_intersect_key($fields, array_flip(explode(',', $queryParams['fields'][$type])));
}
foreach ($fields as $name => $field) {
if (isset($this->map[$key]['fields'][$name])) {
continue;
}
foreach ($fields as $field) {
if (! evaluate($field->getVisible(), [$model, $this->context])) {
continue;
}
if ($field instanceof Attribute) {
$this->resolveAttribute($key, $field, $resourceType, $model);
} elseif ($field instanceof Relationship) {
$this->resolveRelationship($key, $field, $resourceType, $model, $include, $url);
if ($field instanceof Schema\Attribute) {
$value = $this->attribute($field, $resource, $model);
} elseif ($field instanceof Schema\Relationship) {
$isIncluded = isset($include[$name]);
$relationshipInclude = $isIncluded ? ($include[$name] ?? []) : null;
$links = $this->relationshipLinks($field, $url);
$meta = $this->meta($field->getMeta(), $model);
$members = array_merge($links, $meta);
if (! $isIncluded && ! $field->hasLinkage()) {
$value = $this->emptyRelationship($field, $members);
} elseif ($field instanceof Schema\HasOne) {
$value = $this->toOne($field, $members, $resource, $model, $relationshipInclude);
} elseif ($field instanceof Schema\HasMany) {
$value = $this->toMany($field, $members, $resource, $model, $relationshipInclude);
}
}
if (! empty($value)) {
$data['fields'][$name] = $value;
}
}
return $this->map[$key];
$data['links']['self'] = new Structure\Link\SelfLink($url);
$data['meta'] = $this->meta($schema->getMeta(), $model);
$this->merge($data);
return $data;
}
private function key(string $type, string $id): string
private function merge($data): void
{
return $type.':'.$id;
}
$key = $this->key($data);
/**
* @return Structure\Internal\RelationshipMember[]
*/
private function meta(array $items, $model): array
{
ksort($items);
return array_map(function (Meta $meta) use ($model) {
return new Structure\Meta($meta->getName(), ($meta->getValue())($model, $this->context));
}, $items);
}
private function sparseFields(string $type, array $fields): array
{
$queryParams = $this->context->getRequest()->getQueryParams();
if (isset($queryParams['fields'][$type])) {
$requested = $queryParams['fields'][$type];
$requested = is_array($requested) ? $requested : explode(',', $requested);
$fields = array_intersect_key($fields, array_flip($requested));
if (isset($this->map[$key])) {
$this->map[$key]['fields'] = array_merge($this->map[$key]['fields'], $data['fields']);
$this->map[$key]['links'] = array_merge($this->map[$key]['links'], $data['links']);
$this->map[$key]['meta'] = array_merge($this->map[$key]['meta'], $data['meta']);
} else {
$this->map[$key] = $data;
}
return $fields;
}
private function resolveAttribute(string $key, Attribute $field, ResourceType $resourceType, $model): void
{
$value = $this->getAttributeValue($field, $resourceType, $model);
$this->whenResolved($value, function ($value) use ($key, $field) {
if ($value instanceof DateTimeInterface) {
$value = $value->format(DateTime::RFC3339);
}
$this->setField($key, $field, new Structure\Attribute($field->getName(), $value));
});
}
private function resolveRelationship(string $key, Relationship $field, ResourceType $resourceType, $model, array $include, string $url): void
{
$name = $field->getName();
$linkageOnly = ! isset($include[$name]);
$nestedInclude = $include[$name] ?? null;
$members = array_merge(
$this->relationshipLinks($url, $field),
$this->meta($field->getMeta(), $model)
);
if ($linkageOnly && ! $field->hasLinkage()) {
if ($relationship = $this->emptyRelationship($field, $members)) {
$this->setField($key, $field, $relationship);
}
return;
}
$value = $this->getRelationshipValue($field, $resourceType, $model, $linkageOnly);
$this->whenResolved($value, function ($value) use ($key, $field, $nestedInclude, $members) {
if ($structure = $this->buildRelationship($field, $value, $nestedInclude, $members)) {
$this->setField($key, $field, $structure);
}
});
}
private function getAttributeValue(Attribute $field, ResourceType $resourceType, $model)
private function attribute(Schema\Attribute $field, ResourceType $resource, $model): Structure\Attribute
{
if ($getCallback = $field->getGetCallback()) {
return $getCallback($model, $this->context);
$value = $getCallback($model, $this->context);
} else {
$value = $resource->getAdapter()->getAttribute($model, $field);
}
return $resourceType->getAdapter()->getAttribute($model, $field);
}
private function whenResolved($value, $callback): void
{
if ($value instanceof Deferred) {
$this->deferred[] = function () use (&$data, $value, $callback) {
$this->whenResolved($value->resolve(), $callback);
};
return;
if ($value instanceof DateTimeInterface) {
$value = $value->format(DateTime::RFC3339);
}
$callback($value);
return new Structure\Attribute($field->getName(), $value);
}
private function setField(string $key, Field $field, $value): void
private function toOne(Schema\HasOne $field, array $members, ResourceType $resource, $model, ?array $include)
{
$this->map[$key]['fields'][$field->getName()] = $value;
$included = $include !== null;
$model = ($getCallback = $field->getGetCallback())
? $getCallback($model, $this->context)
: $resource->getAdapter()->getHasOne($model, $field, ! $included);
if (! $model) {
return new Structure\ToNull($field->getName(), ...$members);
}
$identifier = $include !== null
? $this->addRelated($field, $model, $include)
: $this->relatedResourceIdentifier($field, $model);
return new Structure\ToOne($field->getName(), $identifier, ...$members);
}
/**
* @return Structure\Internal\RelationshipMember[]
*/
private function relationshipLinks(string $url, Relationship $field): array
private function toMany(Schema\HasMany $field, array $members, ResourceType $resource, $model, ?array $include)
{
return [];
$included = $include !== null;
// if (! $field->hasUrls()) {
// return [];
// }
$models = ($getCallback = $field->getGetCallback())
? $getCallback($model, $this->context)
: $resource->getAdapter()->getHasMany($model, $field, ! $included);
// return [
// new Structure\Link\SelfLink($url.'/relationships/'.$field->getName()),
// new Structure\Link\RelatedLink($url.'/'.$field->getName())
// ];
$identifiers = [];
foreach ($models as $relatedModel) {
$identifiers[] = $included
? $this->addRelated($field, $relatedModel, $include)
: $this->relatedResourceIdentifier($field, $relatedModel);
}
return new Structure\ToMany(
$field->getName(),
new Structure\ResourceIdentifierCollection(...$identifiers),
...$members
);
}
private function emptyRelationship(Relationship $field, array $members): ?Structure\EmptyRelationship
private function emptyRelationship(Schema\Relationship $field, array $members): ?Structure\EmptyRelationship
{
if (! $members) {
return null;
@ -224,108 +202,48 @@ final class Serializer
return new Structure\EmptyRelationship($field->getName(), ...$members);
}
private function getRelationshipValue(Relationship $field, ResourceType $resourceType, $model, bool $linkageOnly)
/**
* @return Structure\Internal\RelationshipMember
*/
private function relationshipLinks(Schema\Relationship $field, string $url): array
{
if ($getCallback = $field->getGetCallback()) {
return $getCallback($model, $linkageOnly, $this->context);
}
// if (! $field->hasUrls()) {
return [];
// }
if ($field instanceof HasOne) {
return $resourceType->getAdapter()->getHasOne($model, $field, $linkageOnly, $this->context);
}
if ($field instanceof HasMany) {
return $resourceType->getAdapter()->getHasMany($model, $field, $linkageOnly, $this->context);
}
return null;
// return [
// new Structure\Link\SelfLink($url.'/relationships/'.$field->getName()),
// new Structure\Link\RelatedLink($url.'/'.$field->getName())
// ];
}
private function buildRelationship(Relationship $field, $value, ?array $nestedInclude, array $members): ?Structure\Internal\ResourceField
private function addRelated(Schema\Relationship $field, $model, array $include): Structure\ResourceIdentifier
{
$name = $field->getName();
if ($field instanceof HasOne) {
if (! $value) {
return new Structure\ToNull($name, ...$members);
}
return new Structure\ToOne(
$name,
$this->addRelatedResource($field, $value, $nestedInclude),
...$members
);
}
if ($field instanceof HasMany) {
$identifiers = array_map(function ($relatedModel) use ($field, $nestedInclude) {
return $this->addRelatedResource($field, $relatedModel, $nestedInclude);
}, $value);
return new Structure\ToMany(
$name,
new Structure\ResourceIdentifierCollection(...$identifiers),
...$members
);
}
return null;
}
private function addRelatedResource(Relationship $field, $model, ?array $include): Structure\ResourceIdentifier
{
$relatedResourceType = $this->resourceTypeForModel($field, $model);
if ($include === null) {
return $this->resourceIdentifier([
'type' => $relatedResourceType->getType(),
'id' => $relatedResourceType->getAdapter()->getId($model)
]);
}
$relatedResource = is_string($field->getType())
? $this->api->getResource($field->getType())
: $this->resourceForModel($model);
return $this->resourceIdentifier(
$this->addToMap($relatedResourceType, $model, $include)
$this->addToMap($relatedResource, $model, $include)
);
}
private function resourceTypeForModel(Relationship $field, $model): ResourceType
private function resourceForModel($model): ResourceType
{
if (is_string($type = $field->getType())) {
return $this->context->getApi()->getResourceType($type);
}
foreach ($this->context->getApi()->getResourceTypes() as $resourceType) {
if ($resourceType->getAdapter()->represents($model)) {
return $resourceType;
foreach ($this->api->getResources() as $resource) {
if ($resource->getAdapter()->represents($model)) {
return $resource;
}
}
throw new RuntimeException('No resource type defined to represent model '.get_class($model));
}
private function resourceIdentifier(array $data): Structure\ResourceIdentifier
{
return new Structure\ResourceIdentifier($data['type'], $data['id']);
}
private function resolveDeferred(): void
{
$i = 0;
while (count($this->deferred)) {
foreach ($this->deferred as $k => $resolve) {
$resolve();
unset($this->deferred[$k]);
}
if ($i++ > 10) {
throw new RuntimeException('Too many levels of deferred values');
}
}
throw new RuntimeException('No resource defined to represent model of type '.get_class($model));
}
private function resourceObjects(array $items): array
{
return array_map([$this, 'resourceObject'], $items);
return array_map(function ($data) {
return $this->resourceObject($data);
}, $items);
}
private function resourceObject(array $data): Structure\ResourceObject
@ -338,4 +256,39 @@ final class Serializer
...array_values($data['meta'])
);
}
private function resourceIdentifier(array $data): Structure\ResourceIdentifier
{
return new Structure\ResourceIdentifier($data['type'], $data['id']);
}
private function relatedResourceIdentifier(Schema\Relationship $field, $model)
{
$type = $field->getType();
$relatedResource = is_string($type)
? $this->api->getResource($type)
: $this->resourceForModel($model);
return $this->resourceIdentifier([
'type' => $relatedResource->getType(),
'id' => $relatedResource->getAdapter()->getId($model)
]);
}
/**
* @return Structure\Internal\RelationshipMember
*/
private function meta(array $items, $model): array
{
ksort($items);
return array_map(function (Schema\Meta $meta) use ($model) {
return new Structure\Meta($meta->getName(), ($meta->getValue())($model, $this->context));
}, $items);
}
private function key(array $data)
{
return $data['type'].':'.$data['id'];
}
}

View File

@ -12,25 +12,26 @@
namespace Tobyz\JsonApiServer;
use Closure;
use JsonSerializable;
use Nyholm\Psr7\Response;
use Nyholm\Psr7\Stream;
use Tobyz\JsonApiServer\Schema\Field;
function json_api_response($document, int $status = 200): Response
function json_api_response(JsonSerializable $document, int $status = 200): Response
{
return (new Response($status))
->withHeader('Content-Type', JsonApi::MEDIA_TYPE)
->withHeader('content-type', JsonApi::MEDIA_TYPE)
->withBody(Stream::create(json_encode($document, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES)));
}
function negate(Closure $condition): Closure
function negate(Closure $condition)
{
return function (...$args) use ($condition) {
return ! $condition(...$args);
};
}
function wrap($value): Closure
function wrap($value)
{
if (! $value instanceof Closure) {
$value = function () use ($value) {
@ -41,19 +42,19 @@ function wrap($value): Closure
return $value;
}
function evaluate($condition, array $params): bool
function evaluate($condition, array $params)
{
return $condition === true || (is_callable($condition) && $condition(...$params));
}
function run_callbacks(array $callbacks, array $params): void
function run_callbacks(array $callbacks, array $params)
{
foreach ($callbacks as $callback) {
$callback(...$params);
}
}
function has_value(array $data, Field $field): bool
function has_value(array $data, Field $field)
{
return array_key_exists($location = $field->getLocation(), $data)
&& array_key_exists($field->getName(), $data[$location]);
@ -64,18 +65,7 @@ function get_value(array $data, Field $field)
return $data[$field->getLocation()][$field->getName()] ?? null;
}
function set_value(array &$data, Field $field, $value): void
function set_value(array &$data, Field $field, $value)
{
$data[$field->getLocation()][$field->getName()] = $value;
}
function parse_sort_string(string $string): array
{
return array_map(function ($field) {
if ($field[0] === '-') {
return [substr($field, 1), 'desc'];
} else {
return [$field, 'asc'];
}
}, explode(',', $string));
}

View File

@ -11,7 +11,6 @@
namespace Tobyz\JsonApiServer\Laravel;
use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
@ -19,39 +18,25 @@ use Illuminate\Support\Facades\Validator;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Schema\Field;
function rules($rules, array $messages = [], array $customAttributes = []): Closure
function rules($rules, array $messages = [], array $customAttributes = [])
{
if (is_string($rules)) {
$rules = [$rules];
}
return function (callable $fail, $value, Model $model, Context $context, Field $field) use (
$rules,
$messages,
$customAttributes
) {
return function (callable $fail, $value, $model, Context $context, Field $field) use ($rules, $messages, $customAttributes) {
$key = $field->getName();
$validationRules = [$key => []];
$validatorRules = [$key => []];
foreach ($rules as $k => $rule) {
if (is_string($rule)) {
$rule = str_replace('{id}', $model->getKey(), $rule);
}
foreach ($rules as $k => $v) {
if (! is_numeric($k)) {
$validatorRules[$key.'.'.$k] = $rule;
$validationRules[$key.'.'.$k] = $v;
} else {
$validatorRules[$key][] = $rule;
$validationRules[$key][] = $v;
}
}
$validation = Validator::make(
$value !== null ? [$key => $value] : [],
$validatorRules,
$messages,
$customAttributes
);
$validation = Validator::make($value !== null ? [$key => $value] : [], $validationRules, $messages, $customAttributes);
if ($validation->fails()) {
foreach ($validation->errors()->all() as $message) {
@ -61,20 +46,16 @@ function rules($rules, array $messages = [], array $customAttributes = []): Clos
};
}
function authenticated(): Closure
function authenticated()
{
return function () {
return Auth::check();
};
}
function can(string $ability, ...$args): Closure
function can(string $ability)
{
return function ($arg) use ($ability, $args) {
if ($arg instanceof Model) {
array_unshift($args, $arg);
}
return Gate::allows($ability, $args);
return function ($arg) use ($ability) {
return Gate::allows($ability, $arg instanceof Model ? $arg : null);
};
}

View File

@ -2,14 +2,11 @@
namespace Tobyz\Tests\JsonApiServer;
use Closure;
use Tobyz\JsonApiServer\Adapter\AdapterInterface;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Schema\Attribute;
use Tobyz\JsonApiServer\Schema\Field;
use Tobyz\JsonApiServer\Schema\HasMany;
use Tobyz\JsonApiServer\Schema\HasOne;
use Tobyz\JsonApiServer\Schema\Relationship;
class MockAdapter implements AdapterInterface
{
@ -24,34 +21,24 @@ class MockAdapter implements AdapterInterface
$this->type = $type;
}
public function model()
public function newModel()
{
return $this->createdModel = (object) [];
}
public function query()
public function newQuery()
{
return $this->query = (object) [];
}
public function find($query, string $id)
{
if ($id === '404') {
return null;
}
return $this->models[$id] ?? (object) ['id' => $id];
}
public function get($query): array
{
$results = array_values($this->models);
if (isset($query->paginate)) {
$results = array_slice($results, $query->paginate['offset'], $query->paginate['limit']);
}
return $results;
return array_values($this->models);
}
public function getId($model): string
@ -64,21 +51,16 @@ class MockAdapter implements AdapterInterface
return $model->{$this->getProperty($attribute)} ?? 'default';
}
public function getHasOne($model, HasOne $relationship, bool $linkageOnly, Context $context)
public function getHasOne($model, HasOne $relationship, bool $linkage)
{
return $model->{$this->getProperty($relationship)} ?? null;
}
public function getHasMany($model, HasMany $relationship, bool $linkageOnly, Context $context): array
public function getHasMany($model, HasMany $relationship, bool $linkage): array
{
return $model->{$this->getProperty($relationship)} ?? [];
}
public function setId($model, string $id): void
{
$model->id = $id;
}
public function setAttribute($model, Attribute $attribute, $value): void
{
$model->{$this->getProperty($attribute)} = $value;
@ -118,9 +100,14 @@ class MockAdapter implements AdapterInterface
$query->filter[] = [$attribute, $operator, $value];
}
public function filterByRelationship($query, Relationship $relationship, Closure $scope): void
public function filterByHasOne($query, HasOne $relationship, array $ids): void
{
$query->filter[] = [$relationship, $scope];
$query->filter[] = [$relationship, $ids];
}
public function filterByHasMany($query, HasMany $relationship, array $ids): void
{
$query->filter[] = [$relationship, $ids];
}
public function sortByAttribute($query, Attribute $attribute, string $direction): void
@ -130,7 +117,7 @@ class MockAdapter implements AdapterInterface
public function paginate($query, int $limit, int $offset): void
{
$query->paginate = compact('limit', 'offset');
$query->paginate[] = [$limit, $offset];
}
public function load(array $models, array $relationships, $scope, bool $linkage): void
@ -148,7 +135,7 @@ class MockAdapter implements AdapterInterface
}
}
private function getProperty(Field $field): string
private function getProperty(Field $field)
{
return $field->getProperty() ?: $field->getName();
}

View File

@ -1,24 +0,0 @@
<?php
namespace Tobyz\Tests\JsonApiServer;
use JsonApiPhp\JsonApi\Error;
use Tobyz\JsonApiServer\ErrorProviderInterface;
class MockException implements ErrorProviderInterface
{
public function getJsonApiErrors(): array
{
return [
new Error(
new Error\Title('Mock Error'),
new Error\Status($this->getJsonApiStatus())
)
];
}
public function getJsonApiStatus(): string
{
return '400';
}
}

View File

@ -42,7 +42,7 @@ class CountabilityTest extends AbstractTestCase
public function test_total_number_of_resources_and_last_pagination_link_is_included_by_default()
{
$this->api->resourceType('users', $this->adapter);
$this->api->resource('users', $this->adapter);
$response = $this->api->handle(
$this->buildRequest('GET', '/users')
@ -56,7 +56,7 @@ class CountabilityTest extends AbstractTestCase
public function test_types_can_be_made_uncountable()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->uncountable();
});
@ -72,7 +72,7 @@ class CountabilityTest extends AbstractTestCase
public function test_types_can_be_made_countable()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->uncountable();
$type->countable();
});

View File

@ -11,7 +11,6 @@
namespace Tobyz\Tests\JsonApiServer\feature;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Tobyz\JsonApiServer\Adapter\AdapterInterface;
use Tobyz\JsonApiServer\Exception\ForbiddenException;
@ -42,6 +41,7 @@ class CreateTest extends AbstractTestCase
->withParsedBody([
'data' => array_merge([
'type' => 'users',
'id' => '1',
], $data)
])
);
@ -49,7 +49,7 @@ class CreateTest extends AbstractTestCase
public function test_resources_are_not_creatable_by_default()
{
$this->api->resourceType('users', new MockAdapter());
$this->api->resource('users', new MockAdapter());
$this->expectException(ForbiddenException::class);
@ -58,7 +58,7 @@ class CreateTest extends AbstractTestCase
public function test_resource_creation_can_be_explicitly_enabled()
{
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$this->api->resource('users', new MockAdapter(), function (Type $type) {
$type->creatable();
});
@ -69,7 +69,7 @@ class CreateTest extends AbstractTestCase
public function test_resource_creation_can_be_conditionally_enabled()
{
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$this->api->resource('users', new MockAdapter(), function (Type $type) {
$type->creatable(function () {
return true;
});
@ -82,7 +82,7 @@ class CreateTest extends AbstractTestCase
public function test_resource_creation_can_be_explicitly_disabled()
{
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$this->api->resource('users', new MockAdapter(), function (Type $type) {
$type->notCreatable();
});
@ -93,7 +93,7 @@ class CreateTest extends AbstractTestCase
public function test_resource_creation_can_be_conditionally_disabled()
{
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$this->api->resource('users', new MockAdapter(), function (Type $type) {
$type->creatable(function () {
return false;
});
@ -108,7 +108,7 @@ class CreateTest extends AbstractTestCase
{
$called = false;
$this->api->resourceType('users', new MockAdapter(), function (Type $type) use (&$called) {
$this->api->resource('users', new MockAdapter(), function (Type $type) use (&$called) {
$type->creatable(function ($context) use (&$called) {
$this->assertInstanceOf(Context::class, $context);
return $called = true;
@ -123,13 +123,11 @@ class CreateTest extends AbstractTestCase
public function test_new_models_are_supplied_and_saved_by_the_adapter()
{
$adapter = $this->prophesize(AdapterInterface::class);
$adapter->model()->willReturn($createdModel = (object) []);
$adapter->newModel()->willReturn($createdModel = (object) []);
$adapter->save($createdModel)->shouldBeCalled();
$adapter->getId($createdModel)->willReturn('1');
$adapter->query()->shouldBeCalled();
$adapter->find(Argument::any(), '1')->willReturn($createdModel);
$this->api->resourceType('users', $adapter->reveal(), function (Type $type) {
$this->api->resource('users', $adapter->reveal(), function (Type $type) {
$type->creatable();
});
@ -141,15 +139,13 @@ class CreateTest extends AbstractTestCase
$createdModel = (object) [];
$adapter = $this->prophesize(AdapterInterface::class);
$adapter->model()->shouldNotBeCalled();
$adapter->newModel()->shouldNotBeCalled();
$adapter->save($createdModel)->shouldBeCalled();
$adapter->getId($createdModel)->willReturn('1');
$adapter->query()->shouldBeCalled();
$adapter->find(Argument::any(), '1')->willReturn($createdModel);
$this->api->resourceType('users', $adapter->reveal(), function (Type $type) use ($createdModel) {
$this->api->resource('users', $adapter->reveal(), function (Type $type) use ($createdModel) {
$type->creatable();
$type->model(function ($context) use ($createdModel) {
$type->newModel(function ($context) use ($createdModel) {
$this->assertInstanceOf(Context::class, $context);
return $createdModel;
});
@ -163,13 +159,11 @@ class CreateTest extends AbstractTestCase
$called = false;
$adapter = $this->prophesize(AdapterInterface::class);
$adapter->model()->willReturn($createdModel = (object) []);
$adapter->newModel()->willReturn($createdModel = (object) []);
$adapter->save($createdModel)->shouldNotBeCalled();
$adapter->getId($createdModel)->willReturn('1');
$adapter->query()->shouldBeCalled();
$adapter->find(Argument::any(), '1')->willReturn($createdModel);
$this->api->resourceType('users', $adapter->reveal(), function (Type $type) use ($createdModel, &$called) {
$this->api->resource('users', $adapter->reveal(), function (Type $type) use ($createdModel, &$called) {
$type->creatable();
$type->save(function ($model, $context) use ($createdModel, &$called) {
$model->id = '1';
@ -189,20 +183,18 @@ class CreateTest extends AbstractTestCase
$called = 0;
$adapter = $this->prophesize(AdapterInterface::class);
$adapter->model()->willReturn($createdModel = (object) []);
$adapter->newModel()->willReturn($createdModel = (object) []);
$adapter->getId($createdModel)->willReturn('1');
$adapter->query()->shouldBeCalled();
$adapter->find(Argument::any(), '1')->willReturn($createdModel);
$this->api->resourceType('users', $adapter->reveal(), function (Type $type) use ($adapter, $createdModel, &$called) {
$this->api->resource('users', $adapter->reveal(), function (Type $type) use ($adapter, $createdModel, &$called) {
$type->creatable();
$type->creating(function ($model, $context) use ($adapter, $createdModel, &$called) {
$type->onCreating(function ($model, $context) use ($adapter, $createdModel, &$called) {
$this->assertSame($createdModel, $model);
$this->assertInstanceOf(Context::class, $context);
$adapter->save($createdModel)->shouldNotHaveBeenCalled();
$called++;
});
$type->created(function ($model, $context) use ($adapter, $createdModel, &$called) {
$type->onCreated(function ($model, $context) use ($adapter, $createdModel, &$called) {
$this->assertSame($createdModel, $model);
$this->assertInstanceOf(Context::class, $context);
$adapter->save($createdModel)->shouldHaveBeenCalled();

View File

@ -43,7 +43,7 @@ class DeleteTest extends AbstractTestCase
public function test_resources_are_not_deletable_by_default()
{
$this->api->resourceType('users', new MockAdapter());
$this->api->resource('users', new MockAdapter());
$this->expectException(ForbiddenException::class);
@ -52,7 +52,7 @@ class DeleteTest extends AbstractTestCase
public function test_resource_deletion_can_be_explicitly_enabled()
{
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$this->api->resource('users', new MockAdapter(), function (Type $type) {
$type->deletable();
});
@ -63,7 +63,7 @@ class DeleteTest extends AbstractTestCase
public function test_resource_deletion_can_be_conditionally_enabled()
{
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$this->api->resource('users', new MockAdapter(), function (Type $type) {
$type->deletable(function () {
return true;
});
@ -76,7 +76,7 @@ class DeleteTest extends AbstractTestCase
public function test_resource_deletion_can_be_explicitly_disabled()
{
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$this->api->resource('users', new MockAdapter(), function (Type $type) {
$type->notDeletable();
});
@ -87,7 +87,7 @@ class DeleteTest extends AbstractTestCase
public function test_resource_deletion_can_be_conditionally_disabled()
{
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$this->api->resource('users', new MockAdapter(), function (Type $type) {
$type->deletable(function () {
return false;
});
@ -103,11 +103,11 @@ class DeleteTest extends AbstractTestCase
$called = false;
$adapter = $this->prophesize(AdapterInterface::class);
$adapter->query()->willReturn($query = (object) []);
$adapter->newQuery()->willReturn($query = (object) []);
$adapter->find($query, '1')->willReturn($deletingModel = (object) []);
$adapter->delete($deletingModel);
$this->api->resourceType('users', $adapter->reveal(), function (Type $type) use ($deletingModel, &$called) {
$this->api->resource('users', $adapter->reveal(), function (Type $type) use ($deletingModel, &$called) {
$type->deletable(function ($model, $context) use ($deletingModel, &$called) {
$this->assertSame($deletingModel, $model);
$this->assertInstanceOf(Context::class, $context);
@ -123,11 +123,11 @@ class DeleteTest extends AbstractTestCase
public function test_deleting_a_resource_calls_the_delete_adapter_method()
{
$adapter = $this->prophesize(AdapterInterface::class);
$adapter->query()->willReturn($query = (object) []);
$adapter->newQuery()->willReturn($query = (object) []);
$adapter->find($query, '1')->willReturn($model = (object) []);
$adapter->delete($model)->shouldBeCalled();
$this->api->resourceType('users', $adapter->reveal(), function (Type $type) {
$this->api->resource('users', $adapter->reveal(), function (Type $type) {
$type->deletable();
});
@ -139,11 +139,11 @@ class DeleteTest extends AbstractTestCase
$called = false;
$adapter = $this->prophesize(AdapterInterface::class);
$adapter->query()->willReturn($query = (object) []);
$adapter->newQuery()->willReturn($query = (object) []);
$adapter->find($query, '1')->willReturn($deletingModel = (object) []);
$adapter->delete($deletingModel)->shouldNotBeCalled();
$this->api->resourceType('users', $adapter->reveal(), function (Type $type) use ($deletingModel, &$called) {
$this->api->resource('users', $adapter->reveal(), function (Type $type) use ($deletingModel, &$called) {
$type->deletable();
$type->delete(function ($model, $context) use ($deletingModel, &$called) {
$this->assertSame($deletingModel, $model);
@ -162,19 +162,19 @@ class DeleteTest extends AbstractTestCase
$called = 0;
$adapter = $this->prophesize(AdapterInterface::class);
$adapter->query()->willReturn($query = (object) []);
$adapter->newQuery()->willReturn($query = (object) []);
$adapter->find($query, '1')->willReturn($deletingModel = (object) []);
$adapter->delete($deletingModel)->shouldBeCalled();
$this->api->resourceType('users', $adapter->reveal(), function (Type $type) use ($adapter, $deletingModel, &$called) {
$this->api->resource('users', $adapter->reveal(), function (Type $type) use ($adapter, $deletingModel, &$called) {
$type->deletable();
$type->deleting(function ($model, $context) use ($adapter, $deletingModel, &$called) {
$type->onDeleting(function ($model, $context) use ($adapter, $deletingModel, &$called) {
$this->assertSame($deletingModel, $model);
$this->assertInstanceOf(Context::class, $context);
$adapter->delete($deletingModel)->shouldNotHaveBeenCalled();
$called++;
});
$type->deleted(function ($model, $context) use ($adapter, $deletingModel, &$called) {
$type->onDeleted(function ($model, $context) use ($adapter, $deletingModel, &$called) {
$this->assertSame($deletingModel, $model);
$this->assertInstanceOf(Context::class, $context);
$adapter->delete($deletingModel)->shouldHaveBeenCalled();

View File

@ -48,7 +48,7 @@ class FieldGettersTest extends AbstractTestCase
public function test_attribute_values_are_retrieved_via_the_adapter_by_default()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->attribute('test');
});
@ -63,7 +63,7 @@ class FieldGettersTest extends AbstractTestCase
public function test_attribute_getters_allow_a_custom_value_to_be_used()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->attribute('test')
->get(function ($model, Context $context) {
return 'custom';
@ -81,11 +81,11 @@ class FieldGettersTest extends AbstractTestCase
public function test_has_one_values_are_retrieved_via_the_adapter_by_default()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->hasOne('animal')->withLinkage();
});
$this->api->resourceType('animals', new MockAdapter());
$this->api->resource('animals', new MockAdapter);
$response = $this->api->handle(
$this->buildRequest('GET', '/users/1')
@ -98,14 +98,14 @@ class FieldGettersTest extends AbstractTestCase
public function test_has_one_getters_allow_a_custom_value_to_be_used()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->hasOne('animal')->withLinkage()
->get(function ($model, bool $linkageOnly, Context $context) {
->get(function ($model, Context $context) {
return (object) ['id' => '2'];
});
});
$this->api->resourceType('animals', new MockAdapter());
$this->api->resource('animals', new MockAdapter);
$response = $this->api->handle(
$this->buildRequest('GET', '/users/1')
@ -118,11 +118,11 @@ class FieldGettersTest extends AbstractTestCase
public function test_has_many_values_are_retrieved_via_the_adapter_by_default()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->hasMany('animals')->withLinkage();
});
$this->api->resourceType('animals', new MockAdapter());
$this->api->resource('animals', new MockAdapter);
$response = $this->api->handle(
$this->buildRequest('GET', '/users/1')
@ -136,9 +136,9 @@ class FieldGettersTest extends AbstractTestCase
public function test_has_many_getters_allow_a_custom_value_to_be_used()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->hasMany('animals')->withLinkage()
->get(function ($model, bool $linkageOnly, Context $context) {
->get(function ($model, Context $context) {
return [
(object) ['id' => '2'],
(object) ['id' => '3']
@ -146,7 +146,7 @@ class FieldGettersTest extends AbstractTestCase
});
});
$this->api->resourceType('animals', new MockAdapter());
$this->api->resource('animals', new MockAdapter);
$response = $this->api->handle(
$this->buildRequest('GET', '/users/1')

View File

@ -40,7 +40,7 @@ class FieldVisibilityTest extends AbstractTestCase
public function test_fields_are_visible_by_default()
{
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$this->api->resource('users', new MockAdapter, function (Type $type) {
$type->attribute('visible');
});
@ -58,7 +58,7 @@ class FieldVisibilityTest extends AbstractTestCase
{
$this->markTestIncomplete();
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$this->api->resource('users', new MockAdapter, function (Type $type) {
$type->attribute('visibleAttribute')->visible();
$type->hasOne('visibleHasOne')->visible();
$type->hasMany('visibleHasMany')->visible();
@ -81,7 +81,7 @@ class FieldVisibilityTest extends AbstractTestCase
{
$this->markTestIncomplete();
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$this->api->resource('users', new MockAdapter, function (Type $type) {
$type->attribute('visibleAttribute')
->visible(function () { return true; });
@ -124,7 +124,7 @@ class FieldVisibilityTest extends AbstractTestCase
$called = 0;
$this->api->resourceType('users', $this->adapter, function (Type $type) use (&$called) {
$this->api->resource('users', $this->adapter, function (Type $type) use (&$called) {
$callback = function ($model, $request) use (&$called) {
$this->assertSame($this->adapter->models['1'], $model);
$this->assertInstanceOf(RequestInterface::class, $request);
@ -152,7 +152,7 @@ class FieldVisibilityTest extends AbstractTestCase
{
$this->markTestIncomplete();
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$this->api->resource('users', new MockAdapter, function (Type $type) {
$type->attribute('hiddenAttribute')->hidden();
$type->hasOne('hiddenHasOne')->hidden();
$type->hasMany('hiddenHasMany')->hidden();
@ -175,7 +175,7 @@ class FieldVisibilityTest extends AbstractTestCase
{
$this->markTestIncomplete();
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$this->api->resource('users', new MockAdapter, function (Type $type) {
$type->attribute('visibleAttribute')
->hidden(function () { return false; });
@ -218,7 +218,7 @@ class FieldVisibilityTest extends AbstractTestCase
$called = 0;
$this->api->resourceType('users', $this->adapter, function (Type $type) use (&$called) {
$this->api->resource('users', $this->adapter, function (Type $type) use (&$called) {
$callback = function ($model, $request) use (&$called) {
$this->assertSame($this->adapter->models['1'], $model);
$this->assertInstanceOf(RequestInterface::class, $request);

View File

@ -42,7 +42,7 @@ class FieldWritabilityTest extends AbstractTestCase
public function test_attributes_are_readonly_by_default()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) use (&$called) {
$this->api->resource('users', $this->adapter, function (Type $type) use (&$called) {
$type->updatable();
$type->attribute('readonly');
});
@ -65,7 +65,7 @@ class FieldWritabilityTest extends AbstractTestCase
public function test_attributes_can_be_explicitly_writable()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->updatable();
$type->attribute('writable')->writable();
});
@ -89,7 +89,7 @@ class FieldWritabilityTest extends AbstractTestCase
public function test_attributes_can_be_conditionally_writable()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->updatable();
$type->attribute('writable')
->writable(function () { return true; });
@ -116,7 +116,7 @@ class FieldWritabilityTest extends AbstractTestCase
{
$called = false;
$this->api->resourceType('users', $this->adapter, function (Type $type) use (&$called) {
$this->api->resource('users', $this->adapter, function (Type $type) use (&$called) {
$type->updatable();
$type->attribute('writable')
->writable(function ($model, $context) use (&$called) {
@ -145,7 +145,7 @@ class FieldWritabilityTest extends AbstractTestCase
public function test_attributes_can_be_explicitly_readonly()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) use (&$called) {
$this->api->resource('users', $this->adapter, function (Type $type) use (&$called) {
$type->updatable();
$type->attribute('readonly')->readonly();
});
@ -168,7 +168,7 @@ class FieldWritabilityTest extends AbstractTestCase
public function test_attributes_can_be_conditionally_readonly()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->updatable();
$type->attribute('readonly')
->readonly(function () { return true; });
@ -194,7 +194,7 @@ class FieldWritabilityTest extends AbstractTestCase
{
$called = false;
$this->api->resourceType('users', $this->adapter, function (Type $type) use (&$called) {
$this->api->resource('users', $this->adapter, function (Type $type) use (&$called) {
$type->updatable();
$type->attribute('readonly')
->readonly(function ($model, $context) use (&$called) {
@ -225,7 +225,7 @@ class FieldWritabilityTest extends AbstractTestCase
public function test_field_is_only_writable_once_on_creation()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->creatable();
$type->updatable();
$type->attribute('writableOnce')->writable()->once();

View File

@ -44,7 +44,7 @@ class FiltersTest extends AbstractTestCase
public function test_resources_can_be_filtered_by_id()
{
$this->api->resourceType('users', $this->adapter);
$this->api->resource('users', $this->adapter);
$this->api->handle(
$this->buildRequest('GET', '/users')
@ -56,7 +56,7 @@ class FiltersTest extends AbstractTestCase
public function test_attributes_are_not_filterable_by_default()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->attribute('test');
});
@ -70,7 +70,7 @@ class FiltersTest extends AbstractTestCase
public function test_attributes_can_be_explicitly_filterable()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) use (&$attribute) {
$this->api->resource('users', $this->adapter, function (Type $type) use (&$attribute) {
$attribute = $type->attribute('test')->filterable();
});
@ -107,7 +107,7 @@ class FiltersTest extends AbstractTestCase
{
$called = false;
$this->api->resourceType('users', $this->adapter, function (Type $type) use (&$called) {
$this->api->resource('users', $this->adapter, function (Type $type) use (&$called) {
$type->filter('name', function ($query, $value, Context $context) use (&$called) {
$this->assertSame($this->adapter->query, $query);
$this->assertEquals('value', $value);

View File

@ -34,7 +34,7 @@ class MetaTest extends AbstractTestCase
{
$adapter = new MockAdapter(['1' => (object) ['id' => '1']]);
$this->api->resourceType('users', $adapter, function (Type $type) use ($adapter) {
$this->api->resource('users', $adapter, function (Type $type) use ($adapter) {
$type->meta('foo', function ($model, $context) use ($adapter) {
$this->assertSame($adapter->models['1'], $model);
$this->assertInstanceOf(Context::class, $context);

View File

@ -11,6 +11,7 @@
namespace Tobyz\Tests\JsonApiServer\feature;
use Psr\Http\Message\ServerRequestInterface;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Schema\Type;
@ -37,7 +38,7 @@ class ScopesTest extends AbstractTestCase
$this->scopeWasCalled = false;
$this->api = new JsonApi('http://example.com');
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->updatable();
$type->deletable();
$type->scope(function ($query, Context $context) {
@ -87,4 +88,44 @@ class ScopesTest extends AbstractTestCase
$this->assertTrue($this->scopeWasCalled);
}
public function test_scopes_are_applied_to_related_resources()
{
$this->api->resource('pets', new MockAdapter, function (Type $type) {
$type->hasOne('owner')
->type('users')
->includable();
});
$this->api->handle(
$this->buildRequest('GET', '/pets/1')
->withQueryParams(['include' => 'owner'])
);
$this->assertTrue($this->scopeWasCalled);
}
public function test_scopes_are_applied_to_polymorphic_related_resources()
{
$this->api->resource('pets', new MockAdapter, function (Type $type) {
$type->hasOne('owner')
->polymorphic(['users', 'organisations'])
->includable();
});
$organisationScopeWasCalled = false;
$this->api->resource('organisations', new MockAdapter, function (Type $type) use (&$organisationScopeWasCalled) {
$type->scope(function ($query, Context $context) use (&$organisationScopeWasCalled) {
$organisationScopeWasCalled = true;
});
});
$this->api->handle(
$this->buildRequest('GET', '/pets/1')
->withQueryParams(['include' => 'owner'])
);
$this->assertTrue($this->scopeWasCalled);
$this->assertTrue($organisationScopeWasCalled);
}
}

View File

@ -38,7 +38,7 @@ class SortingTest extends AbstractTestCase
public function test_attributes_are_not_sortable_by_default()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->attribute('name');
});
@ -54,7 +54,7 @@ class SortingTest extends AbstractTestCase
{
$attribute = null;
$this->api->resourceType('users', $this->adapter, function (Type $type) use (&$attribute) {
$this->api->resource('users', $this->adapter, function (Type $type) use (&$attribute) {
$attribute = $type->attribute('name')->sortable();
});
@ -73,7 +73,7 @@ class SortingTest extends AbstractTestCase
public function test_attributes_can_be_explicitly_not_sortable()
{
$this->api->resourceType('users', $this->adapter, function (Type $type) {
$this->api->resource('users', $this->adapter, function (Type $type) {
$type->attribute('name')->notSortable();
});

View File

@ -11,14 +11,15 @@
namespace Tobyz\Tests\JsonApiServer\specification;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\Exception\NotAcceptableException;
use Tobyz\JsonApiServer\Exception\UnsupportedMediaTypeException;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\Schema\Type;
use Tobyz\Tests\JsonApiServer\AbstractTestCase;
use Tobyz\Tests\JsonApiServer\MockAdapter;
/**
* @see https://jsonapi.org/format/1.1/#content-negotiation
* @see https://jsonapi.org/format/#content-negotiation
*/
class ContentNegotiationTest extends AbstractTestCase
{
@ -30,7 +31,9 @@ class ContentNegotiationTest extends AbstractTestCase
public function setUp(): void
{
$this->api = new JsonApi('http://example.com');
$this->api->resourceType('users', new MockAdapter());
$this->api->resource('users', new MockAdapter(), function (Type $type) {
// no fields
});
}
public function test_json_api_content_type_is_returned()
@ -45,36 +48,36 @@ class ContentNegotiationTest extends AbstractTestCase
);
}
public function test_success_when_request_content_type_contains_profile()
public function test_error_when_request_content_type_has_parameters()
{
$request = $this->buildRequest('PATCH', '/users/1')
->withHeader('Content-Type', 'application/vnd.api+json;profile="http://example.com/last-modified"');
$this->expectException(UnsupportedMediaTypeException::class);
$this->api->handle($request);
}
public function test_error_when_all_accepts_have_parameters()
{
$request = $this->buildRequest('GET', '/users/1')
->withHeader('Accept', 'application/vnd.api+json;profile="http://example.com/last-modified", application/vnd.api+json;profile="http://example.com/versioning"');
$this->expectException(NotAcceptableException::class);
$this->api->handle($request);
}
public function test_success_when_only_some_accepts_have_parameters()
{
$response = $this->api->handle(
$this->buildRequest('GET', '/users/1')
->withHeader('Accept', 'application/vnd.api+json; profile="http://example.com/profile"')
->withHeader('Accept', 'application/vnd.api+json;profile="http://example.com/last-modified", application/vnd.api+json')
);
$this->assertEquals(200, $response->getStatusCode());
}
public function test_error_when_request_content_type_contains_unknown_parameter()
{
$request = $this->buildRequest('PATCH', '/users/1')
->withHeader('Content-Type', 'application/vnd.api+json; unknown="parameter"');
$this->expectException(UnsupportedMediaTypeException::class);
$this->api->handle($request);
}
public function test_error_when_request_content_type_contains_unsupported_extension()
{
$request = $this->buildRequest('PATCH', '/users/1')
->withHeader('Content-Type', 'application/vnd.api+json; ext="http://example.com/extension"');
$this->expectException(UnsupportedMediaTypeException::class);
$this->api->handle($request);
}
public function test_success_when_accepts_wildcard()
{
$response = $this->api->handle(
@ -84,33 +87,4 @@ class ContentNegotiationTest extends AbstractTestCase
$this->assertEquals(200, $response->getStatusCode());
}
public function test_error_when_all_accepts_have_unknown_parameters()
{
$request = $this->buildRequest('GET', '/users/1')
->withHeader('Accept', 'application/vnd.api+json; unknown="parameter", application/vnd.api+json; unknown="parameter2"');
$this->expectException(NotAcceptableException::class);
$this->api->handle($request);
}
public function test_success_when_only_some_accepts_have_parameters()
{
$response = $this->api->handle(
$this->buildRequest('GET', '/users/1')
->withHeader('Accept', 'application/vnd.api+json; unknown="parameter", application/vnd.api+json')
);
$this->assertEquals(200, $response->getStatusCode());
}
public function test_responds_with_vary_header()
{
$response = $this->api->handle(
$this->buildRequest('GET', '/users/1')
);
$this->assertEquals('Accept', $response->getHeaderLine('vary'));
}
}

View File

@ -11,17 +11,12 @@
namespace Tobyz\Tests\JsonApiServer\specification;
use Tobyz\JsonApiServer\Exception\BadRequestException;
use Tobyz\JsonApiServer\Exception\ConflictException;
use Tobyz\JsonApiServer\Exception\ForbiddenException;
use Tobyz\JsonApiServer\Exception\ResourceNotFoundException;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\Schema\Type;
use Tobyz\Tests\JsonApiServer\AbstractTestCase;
use Tobyz\Tests\JsonApiServer\MockAdapter;
/**
* @see https://jsonapi.org/format/1.1/#crud-creating
* @see https://jsonapi.org/format/1.0/#crud-creating
*/
class CreatingResourcesTest extends AbstractTestCase
{
@ -30,116 +25,55 @@ class CreatingResourcesTest extends AbstractTestCase
*/
private $api;
/**
* @var MockAdapter
*/
private $adapter;
public function setUp(): void
{
$this->api = new JsonApi('http://example.com');
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$type->creatable();
$type->attribute('name')->writable();
$type->hasOne('pet')->writable();
});
$this->adapter = new MockAdapter();
}
public function test_bad_request_error_if_body_does_not_contain_data_type()
{
$this->expectException(BadRequestException::class);
$this->api->handle(
$this->buildRequest('POST', '/users')
->withParsedBody([
'data' => [],
])
);
$this->markTestIncomplete();
}
public function test_bad_request_error_if_relationship_does_not_contain_data()
{
$this->expectException(BadRequestException::class);
$this->api->handle(
$this->buildRequest('POST', '/users')
->withParsedBody([
'data' => [
'type' => 'users',
'relationships' => [
'pet' => [],
],
],
])
);
$this->markTestIncomplete();
}
public function test_forbidden_error_if_client_generated_id_provided()
{
$this->expectException(ForbiddenException::class);
$this->api->handle(
$this->buildRequest('POST', '/users')
->withParsedBody([
'data' => [
'type' => 'users',
'id' => '1',
],
])
);
$this->markTestIncomplete();
}
public function test_created_response_includes_created_data_and_location_header()
public function test_created_response_if_resource_successfully_created()
{
$response = $this->api->handle(
$this->buildRequest('POST', '/users')
->withParsedBody([
'data' => [
'type' => 'users',
],
])
);
$this->markTestIncomplete();
}
$this->assertEquals(201, $response->getStatusCode());
$this->assertEquals('http://example.com/users/1', $response->getHeaderLine('location'));
public function test_created_response_includes_created_data()
{
$this->markTestIncomplete();
}
$this->assertJsonApiDocumentSubset([
'data' => [
'type' => 'users',
'id' => '1',
'links' => [
'self' => 'http://example.com/users/1',
],
],
], $response->getBody());
public function test_created_response_includes_location_header_and_matches_self_link()
{
$this->markTestIncomplete();
}
public function test_not_found_error_if_references_resource_that_does_not_exist()
{
$this->expectException(ResourceNotFoundException::class);
$this->api->handle(
$this->buildRequest('POST', '/users')
->withParsedBody([
'data' => [
'type' => 'users',
'relationships' => [
'pet' => [
'data' => ['type' => 'pets', 'id' => '1'],
],
],
],
])
);
$this->markTestIncomplete();
}
public function test_conflict_error_if_type_does_not_match_endpoint()
{
$this->expectException(ConflictException::class);
$this->api->handle(
$this->buildRequest('POST', '/users')
->withParsedBody([
'data' => [
'type' => 'pets',
],
])
);
$this->markTestIncomplete();
}
}

View File

@ -11,15 +11,12 @@
namespace Tobyz\Tests\JsonApiServer\specification;
use Tobyz\JsonApiServer\Context;
use Tobyz\JsonApiServer\Exception\ResourceNotFoundException;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\Schema\Type;
use Tobyz\Tests\JsonApiServer\AbstractTestCase;
use Tobyz\Tests\JsonApiServer\MockAdapter;
/**
* @see https://jsonapi.org/format/1.1/#crud-deleting
* @see https://jsonapi.org/format/1.0/#crud-deleting
*/
class DeletingResourcesTest extends AbstractTestCase
{
@ -28,48 +25,25 @@ class DeletingResourcesTest extends AbstractTestCase
*/
private $api;
/**
* @var MockAdapter
*/
private $adapter;
public function setUp(): void
{
$this->api = new JsonApi('http://example.com');
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$type->deletable();
});
$this->adapter = new MockAdapter();
}
public function test_no_content_response_if_resource_successfully_deleted()
{
$response = $this->api->handle(
$this->buildRequest('DELETE', '/users/1')
);
$this->assertEquals(204, $response->getStatusCode());
$this->assertEmpty($response->getBody()->getContents());
}
public function test_ok_response_if_meta()
{
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$type->deletable();
$type->deleting(function ($model, Context $context) {
$context->meta('foo', 'bar');
});
});
$response = $this->api->handle(
$this->buildRequest('DELETE', '/users/1')
);
$this->assertEquals(200, $response->getStatusCode());
$this->assertJsonApiDocumentSubset(['meta' => ['foo' => 'bar']], $response->getBody());
$this->markTestIncomplete();
}
public function test_not_found_error_if_resource_does_not_exist()
{
$this->expectException(ResourceNotFoundException::class);
$this->api->handle(
$this->buildRequest('DELETE', '/users/404')
);
$this->markTestIncomplete();
}
}

View File

@ -11,13 +11,12 @@
namespace Tobyz\Tests\JsonApiServer\specification;
use Tobyz\JsonApiServer\Exception\ResourceNotFoundException;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\Tests\JsonApiServer\AbstractTestCase;
use Tobyz\Tests\JsonApiServer\MockAdapter;
/**
* @see https://jsonapi.org/format/1.1/#fetching-resources
* @see https://jsonapi.org/format/#fetching-resources
*/
class FetchingResourcesTest extends AbstractTestCase
{
@ -26,80 +25,50 @@ class FetchingResourcesTest extends AbstractTestCase
*/
private $api;
/**
* @var MockAdapter
*/
private $adapter;
public function setUp(): void
{
$this->api = new JsonApi('http://example.com');
$this->adapter = new MockAdapter();
}
public function test_data_for_resource_collection_is_array_of_resource_objects()
{
$adapter = new MockAdapter([
(object) ['id' => '1'],
(object) ['id' => '2'],
]);
$this->api->resourceType('articles', $adapter);
$response = $this->api->handle(
$this->buildRequest('GET', '/articles')
);
$this->assertJsonApiDocumentSubset([
'data' => [
['type' => 'articles', 'id' => '1'],
['type' => 'articles', 'id' => '2'],
]
], $response->getBody());
$this->markTestIncomplete();
}
public function test_data_for_empty_resource_collection_is_empty_array()
{
$this->api->resourceType('articles', new MockAdapter());
$response = $this->api->handle(
$this->buildRequest('GET', '/articles')
);
$data = json_decode($response->getBody(), true)['data'] ?? null;
$this->assertIsArray($data);
$this->assertEmpty($data);
$this->markTestIncomplete();
}
public function test_data_for_individual_resource_is_resource_object()
{
$adapter = new MockAdapter([
(object) ['id' => '1'],
]);
$this->api->resourceType('articles', $adapter);
$response = $this->api->handle(
$this->buildRequest('GET', '/articles/1')
);
$this->assertJsonApiDocumentSubset([
'data' => ['type' => 'articles', 'id' => '1'],
], $response->getBody());
$this->markTestIncomplete();
}
public function test_not_found_error_if_resource_type_does_not_exist()
{
$this->expectException(ResourceNotFoundException::class);
$this->api->handle(
$this->buildRequest('GET', '/articles/1')
);
$this->markTestIncomplete();
}
public function test_not_found_error_if_resource_does_not_exist()
{
$this->expectException(ResourceNotFoundException::class);
$this->markTestIncomplete();
}
$this->api->resourceType('articles', new MockAdapter());
public function test_resource_collection_document_contains_self_link()
{
$this->markTestIncomplete();
}
$this->api->handle(
$this->buildRequest('GET', '/articles/404')
);
public function test_resource_document_contains_self_link()
{
$this->markTestIncomplete();
}
}

View File

@ -16,32 +16,29 @@ use Tobyz\Tests\JsonApiServer\AbstractTestCase;
use Tobyz\Tests\JsonApiServer\MockAdapter;
/**
* @see https://jsonapi.org/format/1.1/#document-jsonapi-object
* @see https://jsonapi.org/format/#document-jsonapi-object
*/
class JsonApiObjectTest extends AbstractTestCase
class JsonApiTest extends AbstractTestCase
{
/**
* @var JsonApi
*/
private $api;
/**
* @var MockAdapter
*/
private $adapter;
public function setUp(): void
{
$this->api = new JsonApi('http://example.com');
$this->api->resourceType('articles', new MockAdapter());
$this->adapter = new MockAdapter();
}
public function test_document_includes_jsonapi_member_with_version_1_1()
public function test_document_includes_jsonapi_member_with_version_1_0()
{
$response = $this->api->handle(
$this->buildRequest('GET', '/articles')
);
$this->assertJsonApiDocumentSubset([
'jsonapi' => [
'version' => '1.1',
],
], $response->getBody());
$this->markTestIncomplete();
}
}

View File

@ -12,12 +12,12 @@
namespace Tobyz\Tests\JsonApiServer\specification;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\Schema\Type;
use Tobyz\Tests\JsonApiServer\AbstractTestCase;
use Tobyz\Tests\JsonApiServer\MockAdapter;
/**
* @see https://jsonapi.org/format/1.1/#fetching-pagination
* @see https://jsonapi.org/format/1.0/#fetching-pagination
* @todo Create a profile for offset pagination strategy
*/
class OffsetPaginationTest extends AbstractTestCase
{
@ -26,84 +26,60 @@ class OffsetPaginationTest extends AbstractTestCase
*/
private $api;
/**
* @var MockAdapter
*/
private $adapter;
public function setUp(): void
{
$this->api = new JsonApi('http://example.com');
$adapter = new MockAdapter(
array_map(function ($i) {
return (object) ['id' => (string) $i];
}, range(1, 100))
);
$this->api->resourceType('articles', $adapter, function (Type $type) {
$type->paginate(20);
});
$this->adapter = new MockAdapter();
}
public function test_can_request_limit_on_resource_collection()
{
$response = $this->api->handle(
$this->buildRequest('GET', '/articles')
->withQueryParams(['page' => ['limit' => '10']])
);
$data = json_decode($response->getBody(), true)['data'] ?? null;
$this->assertCount(10, $data);
$this->markTestIncomplete();
}
public function test_can_request_offset_on_resource_collection()
{
$response = $this->api->handle(
$this->buildRequest('GET', '/articles')
->withQueryParams(['page' => ['offset' => '5']])
);
$data = json_decode($response->getBody(), true)['data'] ?? null;
$this->assertEquals('6', $data[0]['id'] ?? null);
$this->markTestIncomplete();
}
public function test_pagination_links_are_correct_and_retain_query_parameters()
public function test_first_pagination_link_is_correct()
{
$response = $this->api->handle(
$this->buildRequest('GET', '/articles')
->withQueryParams([
'page' => ['offset' => '40'],
'otherParam' => 'value',
])
);
$this->markTestIncomplete();
}
$links = json_decode($response->getBody(), true)['links'] ?? null;
public function test_last_pagination_link_is_correct()
{
$this->markTestIncomplete();
}
$this->assertEquals('/articles?otherParam=value', $links['first'] ?? null);
$this->assertEquals('/articles?otherParam=value&page%5Boffset%5D=80', $links['last'] ?? null);
$this->assertEquals('/articles?otherParam=value&page%5Boffset%5D=60', $links['next'] ?? null);
$this->assertEquals('/articles?otherParam=value&page%5Boffset%5D=20', $links['prev'] ?? null);
public function test_next_pagination_link_is_correct()
{
$this->markTestIncomplete();
}
public function test_next_pagination_link_is_not_included_on_last_page()
{
$response = $this->api->handle(
$this->buildRequest('GET', '/articles')
->withQueryParams(['page' => ['offset' => '80']])
);
$links = json_decode($response->getBody(), true)['links'] ?? null;
$this->assertNull($links['next'] ?? null);
$this->markTestIncomplete();
}
public function test_prev_pagination_link_is_not_included_on_first_page()
public function test_prev_pagination_link_is_correct()
{
$response = $this->api->handle(
$this->buildRequest('GET', '/articles')
->withQueryParams(['page' => ['offset' => '0']])
);
$this->markTestIncomplete();
}
$links = json_decode($response->getBody(), true)['links'] ?? null;
public function test_prev_pagination_link_is_not_included_on_last_page()
{
$this->markTestIncomplete();
}
$this->assertNull($links['prev'] ?? null);
public function test_pagination_links_retain_other_query_parameters()
{
$this->markTestIncomplete();
}
}

View File

@ -11,13 +11,12 @@
namespace Tobyz\Tests\JsonApiServer\specification;
use Tobyz\JsonApiServer\Exception\BadRequestException;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\Tests\JsonApiServer\AbstractTestCase;
use Tobyz\Tests\JsonApiServer\MockAdapter;
/**
* @see https://jsonapi.org/format/1.1/#query-parameters
* @see https://jsonapi.org/format/#query-parameters
*/
class QueryParametersTest extends AbstractTestCase
{
@ -26,29 +25,20 @@ class QueryParametersTest extends AbstractTestCase
*/
private $api;
/**
* @var MockAdapter
*/
private $adapter;
public function setUp(): void
{
$this->api = new JsonApi('http://example.com');
$this->api->resourceType('users', new MockAdapter());
$this->adapter = new MockAdapter();
}
public function test_bad_request_error_if_unknown_query_parameters()
{
$request = $this->buildRequest('GET', '/users/1')
->withQueryParams(['unknown' => 'value']);
$this->expectException(BadRequestException::class);
$this->api->handle($request);
}
public function test_supports_custom_query_parameters()
{
$request = $this->buildRequest('GET', '/users/1')
->withQueryParams(['camelCase' => 'value']);
$response = $this->api->handle($request);
$this->assertEquals(200, $response->getStatusCode());
$this->markTestIncomplete();
}
}

View File

@ -12,12 +12,11 @@
namespace Tobyz\Tests\JsonApiServer\specification;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\Schema\Type;
use Tobyz\Tests\JsonApiServer\AbstractTestCase;
use Tobyz\Tests\JsonApiServer\MockAdapter;
/**
* @see https://jsonapi.org/format/1.1/#fetching-sparse-fieldsets
* @see https://jsonapi.org/format/1.0/#fetching-sparse-fieldsets
*/
class SparseFieldsetsTest extends AbstractTestCase
{
@ -26,56 +25,40 @@ class SparseFieldsetsTest extends AbstractTestCase
*/
private $api;
/**
* @var MockAdapter
*/
private $adapter;
public function setUp(): void
{
$this->api = new JsonApi('http://example.com');
$articlesAdapter = new MockAdapter([
'1' => (object) [
'id' => '1',
'title' => 'foo',
'body' => 'bar',
'user' => (object) [
'id' => '1',
'firstName' => 'Toby',
'lastName' => 'Zerner',
],
],
]);
$this->api->resourceType('articles', $articlesAdapter, function (Type $type) {
$type->attribute('title');
$type->attribute('body');
$type->hasOne('user')->includable();
});
$this->api->resourceType('users', new MockAdapter(), function (Type $type) {
$type->attribute('firstName');
$type->attribute('lastName');
});
$this->adapter = new MockAdapter();
}
public function test_can_request_sparse_fieldsets()
public function test_can_request_sparse_fieldsets_for_a_type()
{
$request = $this->api->handle(
$this->buildRequest('GET', '/articles/1')
->withQueryParams([
'include' => 'user',
'fields' => [
'articles' => 'title,user',
'users' => 'firstName',
],
])
);
$this->markTestIncomplete();
}
$document = json_decode($request->getBody(), true);
public function test_can_request_sparse_fieldsets_for_multiple_types()
{
$this->markTestIncomplete();
}
$article = $document['data']['attributes'] ?? [];
$user = $document['included'][0]['attributes'] ?? [];
public function test_can_request_sparse_fieldsets_on_resource_collections()
{
$this->markTestIncomplete();
}
$this->assertArrayHasKey('title', $article);
$this->assertArrayNotHasKey('body', $article);
$this->assertArrayHasKey('firstName', $user);
$this->assertArrayNotHasKey('lastName', $user);
public function test_can_request_sparse_fieldsets_on_create()
{
$this->markTestIncomplete();
}
public function test_can_request_sparse_fieldsets_on_update()
{
$this->markTestIncomplete();
}
}

View File

@ -11,16 +11,12 @@
namespace Tobyz\Tests\JsonApiServer\specification;
use Tobyz\JsonApiServer\Exception\BadRequestException;
use Tobyz\JsonApiServer\Exception\ConflictException;
use Tobyz\JsonApiServer\Exception\ResourceNotFoundException;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\JsonApiServer\Schema\Type;
use Tobyz\Tests\JsonApiServer\AbstractTestCase;
use Tobyz\Tests\JsonApiServer\MockAdapter;
/**
* @see https://jsonapi.org/format/1.1/#crud-updating
* @see https://jsonapi.org/format/1.0/#crud-updating
*/
class UpdatingResourcesTest extends AbstractTestCase
{
@ -29,122 +25,60 @@ class UpdatingResourcesTest extends AbstractTestCase
*/
private $api;
/**
* @var MockAdapter
*/
private $adapter;
public function setUp(): void
{
$this->api = new JsonApi('http://example.com');
$adapter = new MockAdapter([
'1' => (object) ['id' => '1', 'name' => 'initial'],
]);
$this->api->resourceType('users', $adapter, function (Type $type) {
$type->updatable();
$type->attribute('name')->writable();
$type->hasOne('pet')->writable();
});
$this->adapter = new MockAdapter();
}
public function test_bad_request_error_if_body_does_not_contain_data_type_and_id()
{
$this->expectException(BadRequestException::class);
$this->markTestIncomplete();
}
$this->api->handle(
$this->buildRequest('PATCH', '/users/1')
->withParsedBody([
'data' => [],
])
);
public function test_only_included_attributes_are_processed()
{
$this->markTestIncomplete();
}
public function test_only_included_relationships_are_processed()
{
$this->markTestIncomplete();
}
public function test_bad_request_error_if_relationship_does_not_contain_data()
{
$this->expectException(BadRequestException::class);
$this->api->handle(
$this->buildRequest('PATCH', '/users/1')
->withParsedBody([
'data' => [
'type' => 'users',
'id' => '1',
'relationships' => [
'pet' => [],
],
],
])
);
$this->markTestIncomplete();
}
public function test_ok_response_with_updated_data_if_resource_successfully_updated()
public function test_ok_response_if_resource_successfully_updated()
{
$response = $this->api->handle(
$this->buildRequest('PATCH', '/users/1')
->withParsedBody([
'data' => [
'type' => 'users',
'id' => '1',
'attributes' => [
'name' => 'updated'
],
],
])
);
$this->markTestIncomplete();
}
$document = json_decode($response->getBody(), true);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('updated', $document['data']['attributes']['name'] ?? null);
public function test_ok_response_includes_updated_data()
{
$this->markTestIncomplete();
}
public function test_not_found_error_if_resource_does_not_exist()
{
$this->expectException(ResourceNotFoundException::class);
$this->api->handle(
$this->buildRequest('PATCH', '/users/404')
->withParsedBody([
'data' => [
'type' => 'users',
'id' => '404',
'attributes' => [
'name' => 'bob',
],
],
])
);
$this->markTestIncomplete();
}
public function test_not_found_error_if_references_resource_that_does_not_exist()
{
$this->expectException(ResourceNotFoundException::class);
$this->api->handle(
$this->buildRequest('PATCH', '/users/1')
->withParsedBody([
'data' => [
'type' => 'users',
'id' => '1',
'relationships' => [
'pet' => [
'data' => ['type' => 'pets', 'id' => '1'],
],
],
],
])
);
$this->markTestIncomplete();
}
public function test_conflict_error_if_type_and_id_does_not_match_endpoint()
{
$this->expectException(ConflictException::class);
$this->api->handle(
$this->buildRequest('PATCH', '/users/1')
->withParsedBody([
'data' => [
'type' => 'pets',
'id' => '1',
],
])
);
$this->markTestIncomplete();
}
}

View File

@ -0,0 +1,72 @@
<?php
/*
* This file is part of JSON-API.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tobyz\Tests\JsonApiServer\unit\Http;
use PHPUnit\Framework\TestCase;
use Tobyz\JsonApiServer\Http\MediaTypes;
class MediaTypesTest extends TestCase
{
public function test_contains_on_exact_match()
{
$header = new MediaTypes('application/json');
$this->assertTrue(
$header->containsExactly('application/json')
);
}
public function test_contains_does_not_match_with_extra_parameters()
{
$header = new MediaTypes('application/json; profile=foo');
$this->assertFalse(
$header->containsExactly('application/json')
);
}
public function test_contains_matches_when_only_weight_is_provided()
{
$header = new MediaTypes('application/json; q=0.8');
$this->assertTrue(
$header->containsExactly('application/json')
);
}
public function test_contains_does_not_match_with_extra_parameters_before_weight()
{
$header = new MediaTypes('application/json; profile=foo; q=0.8');
$this->assertFalse(
$header->containsExactly('application/json')
);
}
public function test_contains_matches_with_extra_parameters_after_weight()
{
$header = new MediaTypes('application/json; q=0.8; profile=foo');
$this->assertTrue(
$header->containsExactly('application/json')
);
}
public function test_contains_matches_when_one_of_multiple_media_types_is_valid()
{
$header = new MediaTypes('application/json; profile=foo, application/json; q=0.6');
$this->assertTrue(
$header->containsExactly('application/json')
);
}
}

View File

@ -9,56 +9,19 @@
* file that was distributed with this source code.
*/
namespace Tobyz\Tests\JsonApiServer\unit;
namespace Tobyz\Tests\JsonApiServer\unit\Http;
use Exception;
use Tobyz\JsonApiServer\JsonApi;
use Tobyz\Tests\JsonApiServer\AbstractTestCase;
use Tobyz\Tests\JsonApiServer\MockException;
use PHPUnit\Framework\TestCase;
class JsonApiTest extends AbstractTestCase
class JsonApiTest extends TestCase
{
/**
* @var JsonApi
*/
private $api;
public function setUp(): void
{
$this->api = new JsonApi('http://example.com');
}
public function test_error_converts_error_provider_to_json_api_response()
{
$response = $this->api->error(
new MockException()
);
$this->assertEquals(400, $response->getStatusCode());
$this->assertJsonApiDocumentSubset([
'errors' => [
[
'title' => 'Mock Error',
'status' => '400',
],
],
], $response->getBody());
$this->markTestIncomplete();
}
public function test_error_converts_non_error_provider_to_internal_server_error()
{
$response = $this->api->error(
new Exception()
);
$this->assertEquals(500, $response->getStatusCode());
$this->assertJsonApiDocumentSubset([
'errors' => [
[
'title' => 'Internal Server Error',
'status' => '500',
],
],
], $response->getBody());
$this->markTestIncomplete();
}
}

View File

@ -18,7 +18,7 @@ class TypeTest extends TestCase
{
public function test_returns_an_existing_field_with_the_same_name_of_the_same_type()
{
$type = new Type();
$type = new Type;
$attribute = $type->attribute('dogs');
$attributeAgain = $type->attribute('dogs');
@ -30,7 +30,7 @@ class TypeTest extends TestCase
public function test_overwrites_an_existing_field_with_the_same_name_of_a_different_type()
{
$type = new Type();
$type = new Type;
$attribute = $type->attribute('dogs');
$hasOne = $type->hasOne('dogs');