spatie/schema-org

Support for custom @context

paulofreitas opened this issue · 1 comments

It would be really useful to have support for custom @context objects as outlined in the JSON-LD spec starting from chapter 3.1 The Context.

I used to use Schema.org vocabulary with a custom base IRI to simplify the linking identifiers:

{
    "@context": {
        "@vocab": "https://schema.org/",
        "@base": "https://domain.com/"
    }
}

There's a lot of other use-cases when using custom @context objects.

Unfortunately, Schema::context() only accepts a string, ideally it would also take an array and serialize it as needed:

$graph = new Graph([
    '@vocab' => 'https://schema.org/',
    '@base' => 'https://domain.com/',
]);

If this is not intended, is there anything we can do to achieve this?

Edit:

For now I'm overloading Graph implementation as it fits my needs:

class Graph extends \Spatie\SchemaOrg\Graph
{
    public function __construct(array|string $context = null)
    {
        if (is_array($context)) {
            $context = json_encode($context);
        }

        parent::__construct($context);
    }

    public function toArray(): array
    {
        $graph = parent::toArray();
        $graph['@context'] = json_decode($graph['@context']);

        return $graph;
    }
}

Please let me know if there's an easier way to do this!