mvieira/collection-json

PHP implementation of the Collection+JSON Media Type

v2.1.0 2017-10-17 19:40 UTC

This package is auto-updated.

Last update: 2024-12-05 19:06:42 UTC


README

Software License Latest Stable Version Build Status Coverage Status

PHP implementation of the Collection+JSON Media Type

Specification:

Installation

CollectionJson requires php >= 7.0

Install CollectionJson with Composer

{
    "require": {
        "mvieira/collection-json": "dev-master"
    }
}

or

$ composer require mvieira/collection-json

Contributing

Please see CONTRIBUTING for details.

License

The MIT License (MIT). Please see License File for more information.

Documentation

Creating a collection

$collection = (new Collection())
    ->withItem((new Item('https://example.co/item/1'))
        ->withDataSet([
            new Data('data 1'),
            new Data('data 2', 'value 2')
        ])
        ->withLink(
            new Link('https://example.co/item/1', Relation::ITEM)
        )
    );

print json_encode($collection);
{
    "collection": {
        "version": "1.0",
        "items": [
            {
                "data": [
                    {
                        "name": "data 1",
                        "value": null
                    },
                    {
                        "name": "data 2",
                        "value": "value 2"
                    }
                ],
                "href": "http:\/\/example.com\/item\/1",
                "links": [
                    {
                        "href": "https:\/\/example.co\/item\/1",
                        "rel": "item",
                        "render": "link"
                    }
                ]
            }
        ]
    }
}

Creating an entity

All entities Collection, Data, Error, Item, Link, Query, Template can be created by using the static method fromArray...

$data = Data::fromArray([
    'name' => 'email',
    'value' => 'hello@example.co'
]);

...or by using the accessors (Note that entities are immutable)

$data = (new Data('email'))
    ->withValue('hello@example.co');

...or via the constructor

$data = new Data('email', 'hello@example.co');

Printing the data

Note: Apart from the data's value property, which allows having a NULL value (see. specification), All NULL properties and empty arrays will be excluded from the JSON and Array representation.

Printing a JSON representation

All entities implement the JsonSerializable interface, you can therefore call at any time the method json_encode().

print json_encode($collection);
{
    "collection": {
        "version": "1.0",
        "items": [
            ...
        ],
        "links": [
            ...
        ]
    }
}

Printing an Array representation

All entities implement a custom interface named ArrayConvertible, so you can call at any time the method toArray(). This method will be called recursively on all nested entities.

print_r($collection->toArray());
Array
(
    [collection] => Array
        (
            [version] => 1.0
            [items] => Array
                ...

            [links] => Array
                ...

        )

)

Wrapping

The CollectionJson\Entity\Collection entity will be wrapped...

echo json_encode($collection);
{
    "collection": {
        "version": "1.0"
     }
}

...however others entities will not be wrapped when they are converted in a JSON or an Array.

$template = new Template();
echo json_encode($template);
{
    "data": [
        ...
    ]
}

But you can wrap the json or the array representation by calling the method wrap()

$template->wrap();
echo json_encode($template);
{
    "template": {
        "data": [
            ...
        ]
    }
}

Examples

Examples are available in the directory ./examples/, you can execute them on the command line by running:

$ make examples

Or separately

$ php ./examples/client-collection.php

Working with data and links

In order to work with CollectionJson Arrays Data, Links, the API provides 2 interfaces that implement a similar logic.

  • The interface DataAware implemented by Item, Query and Template entities, provides the methods withData, withoutData, withDataSet, getDataSet, getFirstData and getLastData
  • The interface LinkAware implemented by Collection and Item entities, provides the methods withLink, withoutLink, withLinkSet, getLinks, getFirstLink and getLastLink

They allows you to add the corresponding entities to objects that implement them.

// this...
$item = (new Item('https://example.co/item/1'))
    ->withData([
        'name' => 'email',
        'value' => 'email value'
    ]);

// ...is similar to
$data = Data::fromArray([
    'name' => 'email',
    'value' => 'email value'
]);

$item = (new Item('https://example.co/item/1'))
    ->withData($data);

// and that...
$item = (new Item('https://example.co/item/1'))
    ->withDataSet([
        new Data('email', 'hello@example.co'),
        new Data('tel', '0000000000')
    ]);

// ...is similar to
$data1 = Data::fromArray([
    'name' => 'email',
    'value' => 'hello@example.co'
]);
$data2 = Data::fromArray([
    'name' => 'tel',
    'value' => '0000000000'
]);
$item = (new Item('https://example.co/item/1'))
    ->withDataSet([
        $data1,
        $data2
    ]);

Validation

It is now possible to validate the data entering your API by using the Symfony validator.

use CollectionJson\Validator\Dataset as DatasetValidator;
use Symfony\Component\Validator\Constraints;

$constraints = [
    'id' => [
        new Constraints\NotBlank(),
    ],
    'url' => [
        new Constraints\NotBlank(),
        new Constraints\Url(),
    ],
    'email' => [
        new Constraints\NotBlank(),
        new Constraints\Email(),
    ],
];

$template = (new Template())
    ->withData(new Data('id', '123'))
    ->withData(new Data('url', 'http://example.co'))
    ->withData(new Data('email', 'test@example.co'));

$errors = (new DatasetValidator())
    ->validate($template->getDataSet(), $constraints);

It will return the list of errors.