PHP code example of celestriode / json-utils

1. Go to this page and download the library: Download celestriode/json-utils 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/ */

    

celestriode / json-utils example snippets


use Celestriode\JsonUtils\JsonUtils;

$string = '{"key": "value"}';

$json = JsonUtils::deserialize($string);

use Celestriode\JsonUtils\Json;

$null = Json::NULL; // NULL fields
$bool = Json::BOOLEAN; // Boolean fields
$int = Json::INTEGER; // Integer fields
$double = Json::DOUBLE; // Double fields
$string = Json::STRING; // String fields
$object = Json::OBJECT; // Object fields
$array = Json::ARRAY

$any = Json::ANY; // Any of the above
$number = Json::NUMBER; // Matches Json::INTEGER and Json::DOUBLE
$scalar = Json::SCALAR; // Matches Json::BOOL, Json::NUMBER, and Json::STRING

use Celestriode\JsonUtils\Json;

$json = new Json('key', 'value that will be parsed as a string');

var_dump($json->isType(Json::STRING)); // true
var_dump($json->isType(Json::OBJECT)); // false
var_dump($json->isType(Json::NUMBER)); // false
var_dump($json->isType(Json::SCALAR)); // true
var_dump($json->isType(Json::ANY)); // true
var_dump($json->isType(Json::BOOLEAN | Json::STRING)); // true

use Celestriode\JsonUtils\Json;
use Celestriode\JsonUtils\JsonCollection;

$jsonCollection = $json->getElements(); // Returns all children of a JSON array as a JsonCollection

$collection = $jsonCollection->getCollection(); // Returns the list of Json classes in the collection.
$count = $jsonCollection->count(); // Returns the number of Json classes in the collection.

use Celestriode\JsonUtils\JsonUtils;

$string = JsonUtils::normalizeTypeInteger(Json::ARRAY); // result: "array"
$integer = JsonUtils::normalizeTypeString('array'); // result: 16 AKA Json::ARRAY

use Celestriode\JsonUtils\IPredicate;
use Celestriode\JsonUtils\Json;
use Celestriode\JsonUtils\Structure\Report;

class JsonIsArray implements IPredicate
{
    /**
     * Will only return true if the JSON is an array.
     *
     * @param Json $json The Json to test with.
     * @return boolean
     */
    public function test(Json $json): bool
    {
        return $json->isType(Json::ARRAY);
    }

    /**
     * Returns a helpful error message to optionally use if the predicate fails.
     *
     * @return string
     */
    public function getReport(): Report
    {
        return Report::warning('Predicate failed because it was not an array');
    }
}

$json = new Json('key', []);
$json->checkJson(new JsonIsArray()); // Result: true

use Celestriode\JsonUtils\Predicates\Predicate;
use Celestriode\JsonUtils\Json;

class ATestCase extends Predicate
{
    public function test(Json $json): bool
    {
        return $json->hasField('key');
    }
}

use Celestriode\JsonUtils\Json;
use Celestriode\JsonUtils\Predicates\HasValue;

$json = new Json('key', 'value');
$json->checkJson(new HasValue('test', 'another', 'value', 'blah')); // Result: true
$json->checkJson(new HasValue('test', 'hello', 'goodbye')); // Result: false

use Celestriode\JsonUtils\Json;
use Celestriode\JsonUtils\Predicates\AlwaysTrue;

$json = new Json('key', 'value');
$json->checkJson(AlwaysTrue::instance()); // Do this
$json->checkJson(new AlwaysTrue()); // DO NOT do this

use Celestriode\JsonUtils\Structure;

$structure = Structure::root(Json::OBJECT,
    Structure::string('hello', false),
    Structure::number('goodbye)
);

/*
MATCHES:

{
    "hello": "test",
    "goodbye": 4
}

{
    "goodbye": 1
}
*/

/*
DOES NOT MATCH:

{
    "hello": "test",
    "goodbye": "string"
}

{
    "hello": 9,
    "goodbye": 5
}

{
    "hello": "9"
}
*/

Structure::root(Json::OBJECT,
    Structure::object('content', true,
        Structure::integer('id'),
        Structure::string('name')
    )
);

/*
MATCHES:

{
    "content": {
        "id": 4,
        "name": "test"
    }
}
*/

Structure::root(Json::OBJECT,
    Structure::array('stuff', true,
        Structure::string(),
        Structure::boolean(),
        Structure::object(null, true,
            Structure::integer('id'),
            Structure::string('name')
        )
    )
);

/*
MATCHES:

{
    "stuff": [
        "test",
        true,
        {
            "id": 4,
            "name": "blah"
        }
    ]
}
*/

Structure::root(Json::OBJECT,
    Structure::array('stuff', true,
        Structure::mixed(null, Json::STRING | Json::BOOLEAN | Json::OBJECT, true,
            Structure::integer('id'),
            Structure::string('name')
        )
    )
);

/*
MATCHES:

{
    "stuff": [
        "test",
        true,
        {
            "id": 4,
            "name": "blah"
        }
    ]
}
*/

Structure::root(Json::OBJECT,
    Structure::integer('id'),
    Structure::placeholder(Json::STRING)
);

/*
MATCHES:

{
    "id": 5,
    "any": "key",
    "with": "a",
    "string": "as",
    "the": "value",
    "don't": "dead",
    "open": "inside"
}
*/

$structure = Structure::root(Json::OBJECT,
    Structure::string('id'),

    // Branched if the value of "id" is "first"

    Structure::branch('Branch A', new SiblingHasValue('id', 'first'),
        Structure::integer('test')
    ),

    // Branched if the value of "id" is "second"

    Structure::branch('Branch B', new SiblingHasValue('id', 'second'),
        Structure::boolean('correct')
    )
);

/*
MATCHES:

{
    "id": "first",
    "test": 4
}

{
    "id": "second",
    "correct": true
}
/*/

use Celstriode\JsonUtils\Structure;
use Ramsey\Uuid\Uuid;

$uuid = Uuid::fromString('1533b1f4-e150-4d04-a770-b128b0eadadf');

$structure = Structure::root(Json::OBJECT,
    Structure::string('name'),
    Structure::array('children', false,
        Structure::ascend($uuid)
    )
)->setUuid($uuid);

/*
MATCHES:

{
    "name": "grandparent",
    "children": [
        {
            "name": "aunt/uncle"
        },
        {
            "name": "parent",
            "children": [
                {
                    "name": "me"
                }
            ]
        }
    ]
}
/*/

use Celestriode\JsonUtils\JsonUtils;
use Celestriode\JsonUtils\Structure;

// Deserialize raw JSON.

$json = JsonUtils::deserialize('{"string": "with this value"}');

// Define the expected structure.

$structure = Structure::root(Json::OBJECT,
    Structure::string('string')
);

// Compare it to receive reports.

$reports = $structure->compare($json);

$reports->hasAnyErrors(); // true if mismatched structure

use Celestriode\JsonUtils\Structure\Report;

$info = Report::info('this is the info message');
$warning = Report::warning('this is the warning message');
$fatal = Report::fatal('this is the fatal message');

use Celestriode\JsonUtils\Structure\Report;

$warning = Report::warning('Warning with keys %s and value %s', Report::key('key1', 'key2'), Report::value('value1'));

// Result:
// Warning with keys "key1", "key2" and value &lt;code&gt;value1&lt;/code&gt;

use Celestriode\JsonUtils\JsonUtils;
use Celestriode\JsonUtils\Structure;
use Celestriode\JsonUtils\Structure\StatisticalReports;

// Deserialize raw JSON.

$json = JsonUtils::deserialize('{"string": "with this value"}');

// Define the expected structure.

$structure = Structure::root(Json::OBJECT,
    Structure::string('string')
);

// Compare it to receive statistical reports.

$statisticalReports = $structure->compare($json, new StatisticalReports());

$statistics = $statisticalReports->getStatistics();

print_r($statistics->getStatistics());

use Celestriode\JsonUtils\Structure\Audits\Audit;
use Celestriode\JsonUtils\Structure;
use Celestriode\JsonUtils\Json;
use Celestriode\JsonUtils\Structure\Reports;

class HasValue extends Audit
{
    /**
     * Adds a warning if the value of the Json structure wasn't correct.
     *
     * @param Structure $structure The structure at the current depth.
     * @param Json $json The Json at the current depth.
     * @param Reports $reports Reports at the current depth.
     * @return void
     */
    public function audit(Structure $structure, Json $json, Reports $reports): void
    {
        if (!$json->getValue() === 'expected value') {

            $reports->addReport(Report::warning(
                'The value of %s should have been "expected value", was %s',
                Report::key($json->getKey()),
                Report::value($json->toString())
            ));
        }
    }
}

use Celestriode\JsonUtils\Structure;
use Celestriode\JsonUtils\Structure\Audits\HasValue;
use Celestriode\JsonUtils\Predicates\AlwaysFalse;

$structure = Structure::root(Json::OBJECT,
    Structure::string('test')->addAudit(new HasValue('first', 'second', 'third')),
    Structure::string('blah', false)->addAudit(new HasValue('a', 'b'), AlwaysFalse::instance())
);

/*
MATCHES:

{
    "test": "second",
    "blah": "c" // This matches because the audit was never run due to the AlwaysFalse predicate
}
*/

use Celestriode\JsonUtils\Structure;
use Celestriode\JsonUtils\Json;
use Celestriode\JsonUtils\Predicates;
use Celestriode\JsonUtils\Structure\Audits;
use Ramsey\Uuid\Uuid;

$uuid = Uuid::fromString('742a8779-2c69-4d5f-8731-19f0d4f40ff7');

$structure = Structure::root(Json::ARRAY | Json::SCALAR | Json::OBJECT)
->setUuid($uuid)
->addElements(

    // If the structure's root is an array, then its elements can be the same as the root.

    Structure::ascend($uuid)
)
->addChildren(

    // Textual

    Structure::string('text', false),
    Structure::string('selector', false),
    Structure::string('keybind', false),
    Structure::string('translate', false),
    Structure::array('with', false)->addElements(
        Structure::ascend($uuid)
    ),
    Structure::object('score', false,
        Structure::string('name'),
        Structure::string('objective'),
        Structure::string('value', false)
    ),
    Structure::string('nbt', false),
    Structure::string('block', false),
    Structure::string('entity', false),
    Structure::boolean('interpret', false),

    // Formatting

    Structure::string('color', false),
    Structure::boolean('bold', false),
    Structure::boolean('italic', false),
    Structure::boolean('underlined', false),
    Structure::boolean('obfuscated', false),
    Structure::boolean('strikethrough', false),

    // Events: click
    
    Structure::object('clickEvent', false,
        Structure::string('action')->addAudit(new Audits\HasValue('open_url', 'open_file', 'run_command', 'suggest_command', 'change_page')),

        // Branch: open_url

        Structure::branch('click: open URL', new Predicates\SiblingHasValue('action', 'open_url'), Structure::string('value')),

        // Branch: open_file

        Structure::branch('click: open file', new Predicates\SiblingHasValue('action', 'open_file'),
            Structure::string('value')
        ),

        // Branch: run_command

        Structure::branch('click: run command', new Predicates\SiblingHasValue('action', 'run_command'),
            Structure::string('value')
        ),

        // Branch: suggest_command

        Structure::branch('click: suggest command', new Predicates\SiblingHasValue('action', 'suggest_command'),
            Structure::string('value')
        ),

        // Branch: change_page

        Structure::branch('click: change page', new Predicates\SiblingHasValue('action', 'change_page'),
            Structure::string('value')
        )
    ),

    // Events: hover

    Structure::object('hoverEvent', false,
        Structure::string('action')->addAudit(new Audits\HasValue('show_text', 'show_item', 'show_entity')),

        // Branch: show_text

        Structure::branch('hover: show text', new Predicates\SiblingHasValue('action', 'show_text'),
            Structure::ascend($uuid, 'value')
        ),

        // Branch: show_item

        Structure::branch('hover: show item', new Predicates\SiblingHasValue('action', 'show_item'),
            Structure::string('value')
        ),

        // Branch: show_entity

        Structure::branch('hover: show entity', new Predicates\SiblingHasValue('action', 'show_entity'),
            Structure::string('value')
        )
    ),

    // Events: insertion

    Structure::string('insertion', false),

    // Recursive via "extra" array.

    Structure::array('extra', false,
        Structure::ascend($uuid)
    )
);