# Guide
JsonApiReader is a PHP library that can help you consume {json:api}- formatted data. Besides providing an object-oriented interface into {json:api} documents, it can also fill your own backing objects with the parsed contents. It is, in any case, NOT an API client. This means, that this library expects raw json strings as input and does not and will not care how you obtained them.
# Installation
composer require efrane/json-api-reader
# A note on frameworks
This package does not provide any direct Framework integration as parsing is a rather self-contained process. However, the Hydration component has been designed with Doctrine (opens new window) and Eloquent (opens new window) in mind.
# Quick Start
The easiest use case is to simply parse a document into a
traversable object structure. To do so, it is typically enough to
just hand a raw {json:api} string to the DocumentNormalizer:
use EFrane\JsonApiReader\Normalization\DocumentNormalizer;
$normalizer = new DocumentNormalizer();
$normalizedDocument = $normalizer->normalize($yourDocumentString);
Error Handling
There are two distinct error states to handle during normalization:
- A syntactic or semantic error in the {json:api}-document
prevents the Normalizer from completion. In these cases, exceptions
are thrown:
JsonException, if the JSON itself is not parsableNormalizationException, if a semantic error prevents further normalization
- The document may be an {json:api} error document, this can be
determined by either an interface check for the
EFrane\JsonApiReader\Normalization\Document\ErrorDocumentInterface, or by checking that$normalizedDocument->getDocumentType()returns an instance ofEFrane\JsonApiReader\Normalization\DocumentType\Error.
TIP
Errors are mapped into \EFrane\JsonApiReader\Normalization\ErrorInfoInterface objects and
as such readable via the document tree navigation methods.
Normalization? Explain!
A detailed explanation is in the deep dive on Normalization, however, the basic idea is to map the contained resources into an associate array of item lists keyed by types.
Navigating the tree
The resulting normalized document implements \ArrayAccess, \Countable, and \Iterator to provide
easy access into the document's data.
Differences between Error and TopLevel documents
| TopLevelDocument | ErrorDocument | |
|---|---|---|
| Iteration mode | Iterates over resources of primary type | Iterates over error objects |
| Item access mode | Access by ids of primary resources | Access by index of error object in errors list |