Skip to content

Commit

Permalink
Added the ability to pass options to the json serializer to make the …
Browse files Browse the repository at this point in the history
…definition of the trait Jsonable compatible with Laravel's Jsonable interface
  • Loading branch information
Max Brokman committed Sep 24, 2015
1 parent a2be26b commit cd4aff3
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 7 deletions.
5 changes: 3 additions & 2 deletions src/Serializers/JsonSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,12 @@ public function __construct()
/**
* @param $entity
*
* @param int $jsonEncodeOptions
* @return string
*/
public function serialize($entity)
public function serialize($entity, $jsonEncodeOptions = 0)
{
return $this->serializer->serialize($entity, 'json');
return $this->serializer->serialize($entity, 'json', ['json_encode_options' => $jsonEncodeOptions]);
}

/**
Expand Down
5 changes: 3 additions & 2 deletions src/Serializers/Jsonable.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
trait Jsonable
{
/**
* @param int $options
* @return string
*/
public function toJson()
public function toJson($options = 0)
{
return (new JsonSerializer)->serialize($this);
return (new JsonSerializer)->serialize($this, $options);
}

/**
Expand Down
22 changes: 19 additions & 3 deletions tests/Serializers/JsonSerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,20 @@ protected function setUp()
$this->serializer = new JsonSerializer;
}

public function test_can_serialize_to_array()
public function test_can_serialize_to_json()
{
$array = $this->serializer->serialize(new JsonableEntity);
$json = $this->serializer->serialize(new JsonableEntity);

$this->assertEquals('{"id":"IDVALUE","name":"NAMEVALUE"}', $array);
$this->assertJson($json);
$this->assertEquals('{"id":"IDVALUE","name":"NAMEVALUE","numeric":"1"}', $json);
}

public function test_can_serialize_to_json_with_numeric_check()
{
$json = $this->serializer->serialize(new JsonableEntity(), JSON_NUMERIC_CHECK);

$this->assertJson($json);
$this->assertEquals('{"id":"IDVALUE","name":"NAMEVALUE","numeric":1}', $json);
}
}

Expand All @@ -31,6 +40,8 @@ class JsonableEntity

protected $name = 'NAMEVALUE';

protected $numeric = "1";

public function getId()
{
return $this->id;
Expand All @@ -40,4 +51,9 @@ public function getName()
{
return $this->name;
}

public function getNumeric()
{
return $this->numeric;
}
}

0 comments on commit cd4aff3

Please sign in to comment.