From 91484a8e7c69ee7f29adc60385f6c5e148960ad4 Mon Sep 17 00:00:00 2001 From: Jorrit Schippers Date: Fri, 29 May 2020 14:30:43 +0200 Subject: [PATCH] Implement JsonSerializable to enable automatic conversion to array in json_encode --- Tests/Unit/EnumerableTest.php | 18 ++++++++++++++++++ YaLinqo/Enumerable.php | 16 ++++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/Tests/Unit/EnumerableTest.php b/Tests/Unit/EnumerableTest.php index 0334bc8..9a84fc1 100644 --- a/Tests/Unit/EnumerableTest.php +++ b/Tests/Unit/EnumerableTest.php @@ -2649,6 +2649,24 @@ function testToString() E::from([ [ 0, 1 ], [ 0, 2 ], [ 1, 3 ] ])->select('$v[1]', '$v[0]')->toString(', ', '"$k=$v"')); } + /** @covers \YaLinqo\Enumerable::jsonSerialize + */ + function testJsonSerialize() + { + $this->assertEquals( + [], + E::from([])->jsonSerialize()); + $this->assertEquals( + [ 1, 2, 3 ], + E::from([ 1, 2, 3 ])->jsonSerialize()); + $this->assertEquals( + [ 1, 'a' => 2, 3 ], + E::from([ 1, 'a' => 2, 3 ])->jsonSerialize()); + $this->assertEquals( + [ 1, 2, 6 => [ 7 => [ 'a' => 'a' ], [ 8 => 4, 5 ] ] ], + E::from([ 1, 2, 6 => E::from([ 7 => [ 'a' => 'a' ], E::from([ 8 => 4, 5 ]) ]) ])->jsonSerialize()); + } + #endregion #region Actions diff --git a/YaLinqo/Enumerable.php b/YaLinqo/Enumerable.php index 6ee9899..51c13c3 100644 --- a/YaLinqo/Enumerable.php +++ b/YaLinqo/Enumerable.php @@ -18,7 +18,7 @@ * @see from * @package YaLinqo */ -class Enumerable implements \IteratorAggregate +class Enumerable implements \IteratorAggregate, \JsonSerializable { use EnumerableGeneration; use EnumerablePagination; @@ -1082,6 +1082,18 @@ public function toString(string $separator = '', $valueSelector = null): string return implode($separator, $array); } + /** + * Alias of toArrayDeep() that enables automatic json serialization when Enumerable is encoded using json_encode(). + * + * @see Enumerable::toArrayDeep + * @return array + * @package YaLinqo\Conversion + */ + public function jsonSerialize(): array + { + return $this->toArrayDeep(); + } + #endregion #region Actions @@ -1154,4 +1166,4 @@ public function writeLine($selector = null) } #endregion -} \ No newline at end of file +}