focus/json-api

A collection of tools for working with JSON:API data.

2.0.0 2023-11-15 22:04 UTC

This package is auto-updated.

Last update: 2024-11-16 00:04:07 UTC


README

Minimum PHP Version Latest Stable Version CI Status Code Coverage

A collection of tools for working with JSON:API data. This package is an extension of focus/data.

Installation

The best way to install and use this package is with composer:

composer require focus/json-api

Basic Usage

This package provides some structure to reading JSON:API formatted data. Both resource and resource collections are supported.

The typical entry point will be DocumentData:

use Focus\JsonApi\DocumentData;

$data = DocumentData::fromRequest($request);

Note: Like JsonData, this package supports reading JSON from strings and PSR-7 request and response objects.

Once the document is created, the primary data can be accessed as a resource:

$book = $data->resource();

var_dump($book->attribute(path: 'title'));
var_dump($book->attribute(path: 'subtitle'));
var_dump($book->relation(name: 'author'));

Or a collection of resources:

$books = $data->collection();

var_dump($books->ids());

Or the included resources:

$publishers = $data->included(type: 'publisher');

var_dump($publishers->ids());

Types

Identifiers

The Identifier object extends Data and adds helper methods to read the type and identifier value:

$id = $data->id();
$type = $data->type();

Resources

The Resource object extends from Identifier and adds helper methods to read attributes and relationships:

$id = $data->id();
$topics = $data->attribute(path: 'topics');
$author = $data->relation(name: 'author');
$publishers = $data->relations(name: 'publishers');
  • The value of relation() is an identifier of a to-one relationship. When the relationship is undefined, null will be returned. When the relationship is defined as null, a blank Identifier will be returned.
  • The value of relations() is an identifier collection of a to-many relationship. When the relationship is undefined, null will be returned. When the relationship is defined as null, an empty IdentifierCollection will be returned.

The return values of relation() and relations() are structured this way to allow determining when a relationship is not present (undefined) versus being unset (null).

Identifier Collections

The IdentifierCollection object represents a collection of Identifier objects and adds helper methods to read the identifier values:

var_dump($publishers->ids());

The collection can also be iterated:

foreach ($publishers as $publisher) {
    var_dump($publisher->id());
    var_dump($publisher->type());
}

Resource Collections

The ResourceCollection object represents a collection of Resource objects and adds helper methods to read the identifier values:

var_dump($publishers->ids());

The collection can also be iterated:

foreach ($publishers as $publisher) {
    var_dump($publisher->id());
    var_dump($publisher->attribute(path: 'name'));
}