giadc / json-api-request
A package for handling JSON API requests
Installs: 7 770
Dependents: 2
Suggesters: 0
Security: 0
Stars: 2
Watchers: 3
Forks: 0
Open Issues: 0
Requires
- php: ^8.0.2
- symfony/http-foundation: ^6.0|^7.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- mockery/mockery: ^1.3
- phpunit/phpunit: ^10
README
A package for automating pagination, filtering, sorting, and includes when working with the JSON API standard.
Installation
composer install giadc/json-api-request
Basic Usage
RequestParams
Request Params provides objects for pulling/modifying HttpFoundation Requests that compile with JSON API V1.0.
Example:
GET /articles?include=author,comments.author&page[number]=3&page[size]=20&filter[author]=frank&sort=-created,title&fields[author]=name,age
use Giadc\JsonApiRequest\Requests\RequestParams; // By default it creates params from Globals $request = new RequestParams(); // Get Includes $request->getIncludes()->toArray(); // outputs: ['author', 'comments.author'] // Get Page Details $request->getPageDetails()->toArray(); // outputs: ['page' => ['number => 3, 'size' => 20]] // Get Sorting $request->getSortDetails()->toArray(); // outputs: [['field' => 'title', 'direction' => 'ASC'], ['field' => 'created', 'direction' => 'DESC']] // Get Filters $request->getFiltersDetails()->toArray(); // outputs: ['author' => ['frank']] // Get Full Pagination $request->getFullPagination(); // outputs: [{Pagination}, {Includes}, {Sorting}, {Filters}] // Get Fields $request->getFields()->toArray(); // outputs: ['author' => ['name', 'age']]
Request Objects
All Objects implements the RequestInterface and give access the following methods: getParamsArray()
, getQueryString()
Includes
$includes = new Includes(['author', 'comments.author'); $includes->add('site'); $includes->getQueryString(); //outputs: 'include=author,comments.author,site'
Pagination
Pagination sets a defaults the pages size if not provided. It will Also allow you to set max it is able to return by settings the PAGINATION_DEFAULT
and PAGINATION_MAX
env variables.
$pagination = new Pagination(2, 20); $pagination->getQueryString(); //outputs: 'page[number]=2&page[size]=20' // PAGINATION_MAX=25 $pagination = new Pagination(2, 1000); $pagination->getQueryString(); //outputs: 'page[number]=2&page[size]=25'
Sorting
$sorting = new Sorting('-created,title'); $sorting->setSorting(); $sorting->getQueryString('created,-title'); //outputs: 'sort=created,title'
Filters
$filters = new Filters(['author' => 'frank'); $filters->addFilter('author', 'bob'); $filters->getQueryString(); //outputs: 'filter[author]=frank,bob'
Excludes
$filters = new Excludes(['author' => 'country'); $filters->add('author', 'age'); $filters->getQueryString(); //outputs: 'excludes[author]=country,age'
Fields
$filters = new Fields(['author' => 'name'); $filters->add('author', 'age'); $filters->getQueryString(); //outputs: 'fields[author]=name,age'