/** * Serializes the "interior" of a model. * This is the serialization that takes place outside of a "data" container. * Can be used for root model and relationship model serialization. * * @param Model $model * @param AdapterInterface $adapter * @return array */ protected function serializeModel(Model $model, AdapterInterface $adapter) { $metadata = $model->getMetadata(); $serialized = ['type' => $model->getType(), 'id' => $model->getId()]; if ($this->depth > 0) { // $this->includeResource($resource); return $serialized; } foreach ($metadata->getAttributes() as $key => $attrMeta) { $value = $model->get($key); $serialized['attributes'][$key] = $this->serializeAttribute($value, $attrMeta); } $serialized['links'] = ['self' => $adapter->buildUrl($metadata, $model->getId())]; $model->enableCollectionAutoInit(false); $this->increaseDepth(); foreach ($metadata->getRelationships() as $key => $relMeta) { $relationship = $model->get($key); $serialized['relationships'][$key] = $this->serializeRelationship($model, $relationship, $relMeta, $adapter); } $this->decreaseDepth(); $model->enableCollectionAutoInit(true); return $serialized; }
/** * Pushes a model into the memory cache. * * @param Model $model * @return self */ public function push(Model $model) { $this->models[$model->getType()][$model->getId()] = $model; return $this; }
/** * Gets the Model array index from a collection property (original, added, removed, models). * Will return -1 if the model was not found. * * @param string $property The property key * @param Model $model The model to check. * @return int */ protected function indexOf($property, Model $model) { // @todo For performance, can we create a map using the model's composite key to avoid these loops? foreach ($this->{$property} as $index => $loaded) { if ($model->getType() === $loaded->getType() && $model->getId() === $loaded->getId()) { return $index; } } return -1; }
/** * Sets a has-one relationship. * * @param string $key The relationship key (field) name. * @param Model|null $model The model to relate. * @return self */ protected function setHasOne($key, Model $model = null) { if (true === $this->isInverse($key)) { throw ModelException::cannotModifyInverse($this, $key); } if (null !== $model) { $this->validateRelSet($key, $model->getType()); } $this->touch(); $this->hasOneRelationships->set($key, $model); $this->doDirtyCheck(); return $this; }
/** * Creates a reference for storage of a related model in the database * * @param RelationshipMetadata $relMeta * @param Model $model * @return mixed */ protected function createReference(RelationshipMetadata $relMeta, Model $model) { if (true === $relMeta->isPolymorphic()) { $reference[$this->getIdentifierKey()] = $this->convertId($model->getId()); $reference[$this->getPolymorphicKey()] = $model->getType(); return $reference; } return $this->convertId($model->getId()); }