diff --git a/src/Stringy.php b/src/Stringy.php index ccb6f5a..ba482e2 100644 --- a/src/Stringy.php +++ b/src/Stringy.php @@ -7,10 +7,11 @@ use Countable; use Exception; use InvalidArgumentException; +use JsonSerializable; use IteratorAggregate; use OutOfBoundsException; -class Stringy implements Countable, IteratorAggregate, ArrayAccess +class Stringy implements Countable, IteratorAggregate, ArrayAccess, JsonSerializable { /** * An instance's string. @@ -83,6 +84,15 @@ public function __toString() return $this->str; } + /** + * Returns value which can be serialized by json_encode(). + * + * @return string The current value of the $str property + */ + public function jsonSerialize() { + return (string) $this; + } + /** * Returns a new string with $string appended. * diff --git a/tests/StringyTest.php b/tests/StringyTest.php index 97d5502..b083538 100644 --- a/tests/StringyTest.php +++ b/tests/StringyTest.php @@ -56,6 +56,11 @@ public function testToString($expected, $str) $this->assertEquals($expected, (string) new S($str)); } + public function testToJson($expected, $str) + { + $this->assertEquals('" foo bar "', json_encode(new S(' foo bar '))); + } + public function toStringProvider() { return [