Skip to content

Commit

Permalink
Implemented JsonSerializable interface for models/records
Browse files Browse the repository at this point in the history
  • Loading branch information
oschwald committed Oct 26, 2013
1 parent 7fa971a commit 569043c
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 3 deletions.
5 changes: 4 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
"satooshi/php-coveralls": "dev-master"
},
"autoload": {
"psr-0": { "GeoIp2": "src/" }
"psr-0": {
"GeoIp2": "src/",
"" : "compat/"
}
}
}
7 changes: 6 additions & 1 deletion src/GeoIp2/Model/Country.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
* @property \GeoIp2\Record\Traits $traits Data for the traits of the
* requested IP address.
*/
class Country
class Country implements \JsonSerializable
{
private $continent;
private $country;
Expand Down Expand Up @@ -92,4 +92,9 @@ public function __get($attr)

throw new \RuntimeException("Unknown attribute: $attr");
}

public function jsonSerialize()
{
return $this->raw;
}
}
7 changes: 6 additions & 1 deletion src/GeoIp2/Record/AbstractRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace GeoIp2\Record;

abstract class AbstractRecord
abstract class AbstractRecord implements \JsonSerializable
{
private $record;

Expand Down Expand Up @@ -31,4 +31,9 @@ public function __get($attr)
throw new \RuntimeException("Unknown attribute: $attr");
}
}

public function jsonSerialize()
{
return $this->record;
}
}
31 changes: 31 additions & 0 deletions tests/GeoIp2/Test/Model/CountryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,4 +159,35 @@ public function testValues()
'raw method returns raw input'
);
}

public function testJsonSerialize()
{
$this->assertEquals(
$this->raw,
$this->model->jsonSerialize(),
'jsonSerialize returns initial array'
);

$this->assertEquals(
$this->raw['country'],
$this->model->country->jsonSerialize(),
'jsonSerialize returns initial array for the record'
);

if (version_compare(PHP_VERSION, '5.4.0', '<')) {
$this->markTestSkipped('Requires PHP 5.4+.');
}

$this->assertEquals(
json_encode($this->raw),
json_encode($this->model),
'json_encode can be called on the model object directly'
);

$this->assertEquals(
json_encode($this->raw['country']),
json_encode($this->model->country),
'json_encode can be called on the record object directly'
);
}
}

0 comments on commit 569043c

Please sign in to comment.