/**
  * Adds a relationship field to this entity.
  *
  * @param   RelationshipMetadata    $relationship
  * @return  self
  * @throws  MetadataException       If the relationship key already exists as an attribute.
  */
 public function addRelationship(RelationshipMetadata $relationship)
 {
     if (isset($this->attributes[$relationship->getKey()])) {
         throw MetadataException::fieldKeyInUse('relationship', 'attribute', $relationship->getKey(), $this->type);
     }
     $this->relationships[$relationship->getKey()] = $relationship;
     ksort($this->relationships);
     return $this;
 }
Example #2
0
 /**
  * Serializes a relationship value
  *
  * @param   Model                       $owner
  * @param   Model|Model[]|null          $relationship
  * @param   RelationshipMetadata        $relMeta
  * @param   AdapterInterface            $adapter
  * @return  array
  */
 protected function serializeRelationship(Model $owner, $relationship = null, RelationshipMetadata $relMeta, AdapterInterface $adapter)
 {
     if ($relMeta->isOne()) {
         if (is_array($relationship)) {
             throw SerializerException::badRequest('Invalid relationship value.');
         }
         $serialized = $this->serializeHasOne($owner, $relationship, $adapter);
     } elseif (is_array($relationship) || null === $relationship) {
         $serialized = $this->serializeHasMany($owner, $relationship, $adapter);
     } else {
         throw SerializerException::badRequest('Invalid relationship value.');
     }
     $ownerMeta = $owner->getMetadata();
     $serialized['links'] = ['self' => $adapter->buildUrl($ownerMeta, $owner->getId(), $relMeta->getKey()), 'related' => $adapter->buildUrl($ownerMeta, $owner->getId(), $relMeta->getKey(), true)];
     return $serialized;
 }