Skip to content

Commit

Permalink
improve array merging.
Browse files Browse the repository at this point in the history
  • Loading branch information
ncou committed Jan 3, 2019
1 parent dff24c5 commit e52cbf2
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions src/HttpException.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,14 @@ public function addAdditionalData(string $key, $value): self
return $this;
}

/**
* @return array
*/
public function jsonSerialize(): array
{
return $this->toArray();
}

/**
* Return the Exception as an array, suitable for serializing.
*
Expand All @@ -186,16 +194,24 @@ public function toArray(): array
];

// Required fields should always overwrite additional fields
// + remove empty fields in the default fields
// (don't filter additionalData array in case there is a false value)
return array_merge($this->additionalData, array_filter($problem));
// Use array_filter to remove empty fields in the default fields
// And don't array_filter $additionalData in case there is a bool = false value
return $this->mergeArrays(array_filter($problem), $this->additionalData);
}

/**
* Merge the primary + secondary array.
*
* Values in the primary array will not be overwrited by the secondary values.
* Use some reverse function to be sure the secondary array is positioned at the end of the array.
*
* @param array $primary
* @param array $secondary
*
* @return array
*/
public function jsonSerialize(): array
private function mergeArrays(array $primary, array $secondary): array
{
return $this->toArray();
return array_reverse(array_merge(array_reverse($secondary), array_reverse($primary)));
}
}

0 comments on commit e52cbf2

Please sign in to comment.