json-api-php/json-api

Null one to one resource links

Opened this issue · 3 comments

Hiya,

Based on the spec:

Resource linkage MUST be represented as one of the following:

null for empty to-one relationships.
an empty array ([]) for empty to-many relationships.
a single resource identifier object for non-empty to-one relationships.
an array of resource identifier objects for non-empty to-many relationships.

How can I make a null resource link like so:

{
    "relationships": {
        "parent": {
            "data": null,
            "links" {...}
        }
    }
}

I can't see how it's done in a test, but I may have missed something.

f3ath commented

Hi @johnrobertporter thanks for your interest in this library. I think you want something like this:

<?php
declare(strict_types=1);
require_once __DIR__ . '/vendor/autoload.php';
$apple = new \JsonApiPhp\JsonApi\Document\Resource\ResourceObject('apples', '1');
$parent = \JsonApiPhp\JsonApi\Document\Resource\Relationship\Relationship::fromLinkage(
    \JsonApiPhp\JsonApi\Document\Resource\Relationship\Linkage::nullLinkage()
);
$parent->setLink('foo', 'http://example.com/foo');
$parent->setLink('bar', 'http://example.com/bar');
$apple->setRelationship('parent', $parent);
echo json_encode(\JsonApiPhp\JsonApi\Document::fromResource($apple), JSON_PRETTY_PRINT);

It will produce this:

{
    "data": {
        "type": "apples",
        "id": "1",
        "relationships": {
            "parent": {
                "data": null,
                "links": {
                    "foo": "http:\/\/example.com\/foo",
                    "bar": "http:\/\/example.com\/bar"
                }
            }
        }
    }
}

Haha, that's the second time I missed the obvious! nullLinkage got past me!

Thanks for your help.

f3ath commented

It may imdicate poor documentation. I'll try to improve it.