Neomerx\JsonApi\Document\Presenters\ElementPresenter::addRelationshipTo PHP Method

addRelationshipTo() public method

public addRelationshipTo ( array &$target, Neomerx\JsonApi\Contracts\Schema\ResourceObjectInterface $parent, Neomerx\JsonApi\Contracts\Schema\RelationshipObjectInterface $relation, Neomerx\JsonApi\Contracts\Schema\ResourceObjectInterface $resource ) : void
$target array
$parent Neomerx\JsonApi\Contracts\Schema\ResourceObjectInterface
$relation Neomerx\JsonApi\Contracts\Schema\RelationshipObjectInterface
$resource Neomerx\JsonApi\Contracts\Schema\ResourceObjectInterface
return void
    public function addRelationshipTo(array &$target, ResourceObjectInterface $parent, RelationshipObjectInterface $relation, ResourceObjectInterface $resource)
    {
        $parentId = $parent->getId();
        $parentType = $parent->getType();
        $parentExists = isset($target[$parentType][$parentId]);
        // parent might be already added to included to it won't be in 'target' buffer
        if ($parentExists === true) {
            $parentAlias =& $target[$parentType][$parentId];
            $name = $relation->getName();
            $alreadyGotRelation = isset($parentAlias[Document::KEYWORD_RELATIONSHIPS][$name]);
            $linkage = null;
            if ($relation->isShowData() === true) {
                $linkage = $this->getLinkageRepresentation($resource);
            }
            if ($alreadyGotRelation === false) {
                // ... add the first linkage
                $representation = [];
                if ($linkage !== null) {
                    if ($resource->isInArray() === true) {
                        // original data in array
                        $representation[Document::KEYWORD_LINKAGE_DATA][] = $linkage;
                    } else {
                        // original data not in array (just object)
                        $representation[Document::KEYWORD_LINKAGE_DATA] = $linkage;
                    }
                }
                $representation += $this->getRelationRepresentation($parent, $relation);
                $parentAlias[Document::KEYWORD_RELATIONSHIPS][$name] = $representation;
            } elseif ($alreadyGotRelation === true && $linkage !== null) {
                // Check data in '$name' relationship are marked as not arrayed otherwise
                // it's fail to add multiple data instances
                $resource->isInArray() === true ?: Exceptions::throwLogicException();
                // ... or add another linkage
                $parentAlias[Document::KEYWORD_RELATIONSHIPS][$name][Document::KEYWORD_LINKAGE_DATA][] = $linkage;
            }
        }
    }

Usage Example

Beispiel #1
0
 /**
  * @inheritdoc
  */
 public function addRelationshipToIncluded(ResourceObjectInterface $parent, RelationshipObjectInterface $relationship, ResourceObjectInterface $resource)
 {
     $this->presenter->addRelationshipTo($this->bufferForIncluded, $parent, $relationship, $resource);
 }