Skip to content

Commit 2b2b0f4

Browse files
committed
Implement JsonSerializable
1 parent df24ab6 commit 2b2b0f4

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

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: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,11 @@ public function testToString($expected, $str)
5656
$this->assertEquals($expected, (string) new S($str));
5757
}
5858

59+
public function testToJson($expected, $str)
60+
{
61+
$this->assertEquals('" foo bar "', json_encode(new S(' foo bar ')));
62+
}
63+
5964
public function toStringProvider()
6065
{
6166
return [

0 commit comments

Comments
 (0)