PHP code example of mvieira / collection-json

1. Go to this page and download the library: Download mvieira/collection-json library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mvieira / collection-json example snippets


$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);

$data = Data::fromArray([
    'name' => 'email',
    'value' => '[email protected]'
]);

$data = (new Data('email'))
    ->withValue('[email protected]');

$data = new Data('email', '[email protected]');

print json_encode($collection);

print_r($collection->toArray());

Array
(
    [collection] => Array
        (
            [version] => 1.0
            [items] => Array
                ...

            [links] => Array
                ...

        )

)

echo json_encode($collection);

$template = new Template();
echo json_encode($template);

$template->wrap();
echo json_encode($template);

// 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', '[email protected]'),
        new Data('tel', '0000000000')
    ]);

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

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', '[email protected]'));

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

$ php ./examples/client-collection.php