Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement JsonSerializable to enable automatic conversion to array in json_encode #50

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Tests/Unit/EnumerableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 14 additions & 2 deletions YaLinqo/Enumerable.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
* @see from
* @package YaLinqo
*/
class Enumerable implements \IteratorAggregate
class Enumerable implements \IteratorAggregate, \JsonSerializable
{
use EnumerableGeneration;
use EnumerablePagination;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1154,4 +1166,4 @@ public function writeLine($selector = null)
}

#endregion
}
}