Skip to content

Commit 86eea41

Browse files
committed
Implement JsonSerializable
1 parent df24ab6 commit 86eea41

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

src/Stringy.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@
77
use Countable;
88
use Exception;
99
use InvalidArgumentException;
10+
use JsonSerializable;
1011
use IteratorAggregate;
1112
use OutOfBoundsException;
1213

13-
class Stringy implements Countable, IteratorAggregate, ArrayAccess
14+
class Stringy implements Countable, IteratorAggregate, ArrayAccess, JsonSerializable
1415
{
1516
/**
1617
* An instance's string.
@@ -83,6 +84,15 @@ public function __toString()
8384
return $this->str;
8485
}
8586

87+
/**
88+
* Returns value which can be serialized by json_encode().
89+
*
90+
* @return string The current value of the $str property
91+
*/
92+
public function jsonSerialize() {
93+
return (string) $this;
94+
}
95+
8696
/**
8797
* Returns a new string with $string appended.
8898
*

tests/StringyTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,14 @@ public function testToString($expected, $str)
5656
$this->assertEquals($expected, (string) new S($str));
5757
}
5858

59+
/**
60+
* @dataProvider toStringProvider()
61+
*/
62+
public function testToJson($expected, $str)
63+
{
64+
$this->assertEquals('" foo bar "', json_encode(new S(' foo bar ')));
65+
}
66+
5967
public function toStringProvider()
6068
{
6169
return [

0 commit comments

Comments
 (0)