americanreading/refresolver

Resolves references to extenral files in objects

1.0.0 2014-09-17 17:54 UTC

This package is not auto-updated.

Last update: 2024-06-04 05:52:23 UTC


README

Use RefResolver to resolve references or "flatten" objects.

RefResolver works with any object, but is mostly likely to be useful for working with JSON, particularly JSON Schema documents and Swagger configuration files.

References

The format of the references follows the syntax used by JSON Schema. However, there is no restriction on where the reference exists inside the structure.

To create a reference, include a $ref property on an object that points to the path for a file describing an object. The path may be a local file path or an HTTP URI.

Example

Given this file at http://www.myjsonfile/cats.json

{
    "cats": [
        {
            "name": "Molly",
            "color": "Calico"
        },
        {
            "name": "Oscar",
            "color": "Orange"
        }
    ]
}

We can include a reference to this file inside another JSON structure.

<?php
$json = <<<JSON
{
    "dog": "Bear",
    "\$ref": "http://www.myjsonfile/cats.json"
}
JSON

$obj = json_decode($json);

$resolver new RefResolver();
$resolver->resolve($obj);

After calling $resolver->resolve($obj), $obj will contain a "flattened" structure with the contents of the http://www.myjsonfile/cats.json converted to an object and augmented onto $obj.

$obj will now look like this (shown as prettyprinted JSON):

{
    "dog": "Bear",
    "cats": [
        {
            "name": "Molly",
            "color": "Calico"
        },
        {
            "name": "Oscar",
            "color": "Orange"
        }
    ]
}

Custom resolver function

By default, the RefResolver instance will take the value of a $ref property, pass it to file_get_contents, then pass that result to json_decode, and augment the decoded object.

You may customize this behavior by passing a callable to the constructor. The callable must expect the value of the $ref property as an argument and return an object or null.

To parse the contents of the reference as XML instead of JSON, you could use a custom function like this:

<?php
$resolverFn = function ($ref) {
    $contents = @file_get_contents($ref);
    if ($contents) {
        return simplexml_load_string($contents);
    }
    return null;
};

Caveats

There is no safeguard in place to check against circular references.