protected function formatResource(Resource $resource) { $descriptor = $resource->getDescriptor(); // type and id fields are required. $data = ['type' => $descriptor->getName(), 'id' => $resource->getId()]; // If resource has any attributes, add them. $attributes = $resource->getData(); unset($attributes[$descriptor->getPrimaryKey()]); if (!empty($attributes)) { $data['attributes'] = $attributes; } // Include loaded relationships. if (!empty($loadedRelationships = $resource->getLoadedRelationships())) { $data['relationships'] = []; // For each different relationship... foreach ($loadedRelationships as $relationshipName => $relatedResources) { // We will include a whole mew JSON-API document, as per the specification. $document = new Document(); $document->singleResource = !is_array($relatedResources); $document->resources = $relatedResources; $data['relationships'][$relationshipName] = $this->formatDocument($document); } } return $data; }
public function delete(Resource $resource) { $table = $resource->getDescriptor()->getName(); $primaryKey = $resource->getDescriptor()->getPrimaryKey(); try { return (bool) $this->database->table($table)->where($primaryKey, $resource->getId())->delete(); } catch (QueryException $e) { return false; } }
/** * @param Resource $parent * @param Resource $child * @throws InvalidArgumentException If either of the resources do not have an unique identifier. */ public function relateResources($parent, $child) { if (is_null($parent->id())) { throw new InvalidArgumentException('Tried to relate child to a parent that has no ID.'); } if (is_null($parent->id())) { throw new InvalidArgumentException('Tried to relate parent to a child that has no ID.'); } $foreignKey = $this->foreignKeyName(); $child->{$foreignKey} = $parent->id(); }