Skip to content

Commit

Permalink
Implement JsonSerializable
Browse files Browse the repository at this point in the history
  • Loading branch information
danmichaelo committed Jul 3, 2018
1 parent df24ab6 commit 86eea41
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/Stringy.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
*
Expand Down
8 changes: 8 additions & 0 deletions tests/StringyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ public function testToString($expected, $str)
$this->assertEquals($expected, (string) new S($str));
}

/**
* @dataProvider toStringProvider()
*/
public function testToJson($expected, $str)
{
$this->assertEquals('" foo bar "', json_encode(new S(' foo bar ')));
}

public function toStringProvider()
{
return [
Expand Down

0 comments on commit 86eea41

Please sign in to comment.