Skip to content

Commit

Permalink
Merge pull request #44 from swisnl/issue/43
Browse files Browse the repository at this point in the history
Fix hydrating of HasOne relations by id using ItemHydrator
  • Loading branch information
JaZo authored Jan 11, 2019
2 parents 9ff1982 + 2447be8 commit f80ee31
Show file tree
Hide file tree
Showing 2 changed files with 202 additions and 177 deletions.
21 changes: 8 additions & 13 deletions src/ItemHydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ protected function fillRelations(ItemInterface $item, array $attributes)

// It is a valid relation
if ($relation instanceof HasOneRelation) {
$this->hydrateHasOneRelation($item, $attributes, $relation, $availableRelation);
$this->hydrateHasOneRelation($attributes, $relation, $availableRelation);
} elseif ($relation instanceof HasManyRelation) {
$this->hydrateHasManyRelation($attributes, $availableRelation, $relation);
$this->hydrateHasManyRelation($attributes, $relation, $availableRelation);
} elseif ($relation instanceof MorphToRelation) {
$this->hydrateMorphToRelation($attributes, $relation, $availableRelation);
} elseif ($relation instanceof MorphToManyRelation) {
Expand Down Expand Up @@ -101,26 +101,21 @@ protected function getRelationFromItem(ItemInterface $item, string $availableRel
}

/**
* @param \Swis\JsonApi\Client\Interfaces\ItemInterface $item
* @param array $attributes
* @param \Swis\JsonApi\Client\Relations\HasOneRelation $relation
* @param string $availableRelation
*
* @throws \InvalidArgumentException
*/
protected function hydrateHasOneRelation(
ItemInterface $item,
array $attributes,
HasOneRelation $relation,
string $availableRelation
) {
protected function hydrateHasOneRelation(array $attributes, HasOneRelation $relation, string $availableRelation)
{
if (is_array($attributes[$availableRelation])) {
$relationItem = $this->buildRelationItem($relation, $attributes[$availableRelation]);
$relation->associate($relationItem);
} else {
$relation->setId($attributes[$availableRelation]);
$item->setAttribute($availableRelation.'_id', $attributes[$availableRelation]);
$relationItem = $this->buildRelationItem($relation, ['id' => $attributes[$availableRelation]]);
}

$relation->associate($relationItem);
}

/**
Expand All @@ -130,7 +125,7 @@ protected function hydrateHasOneRelation(
*
* @throws \InvalidArgumentException
*/
protected function hydrateHasManyRelation(array $attributes, string $availableRelation, HasManyRelation $relation)
protected function hydrateHasManyRelation(array $attributes, HasManyRelation $relation, string $availableRelation)
{
foreach ($attributes[$availableRelation] as $relationData) {
if (is_array($relationData)) {
Expand Down
Loading

0 comments on commit f80ee31

Please sign in to comment.