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 #186

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
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
5 changes: 5 additions & 0 deletions tests/StringyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 [
Expand Down