From e52cbf26bcc4ada8a5c70dca4767cb9c1a946f59 Mon Sep 17 00:00:00 2001 From: ncou Date: Fri, 4 Jan 2019 00:38:45 +0100 Subject: [PATCH] improve array merging. --- src/HttpException.php | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/src/HttpException.php b/src/HttpException.php index cccf600..42458e7 100644 --- a/src/HttpException.php +++ b/src/HttpException.php @@ -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. * @@ -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))); } }