diff --git a/composer.json b/composer.json index cfc0cf7..f9a94aa 100644 --- a/composer.json +++ b/composer.json @@ -22,6 +22,9 @@ "satooshi/php-coveralls": "dev-master" }, "autoload": { - "psr-0": { "GeoIp2": "src/" } + "psr-0": { + "GeoIp2": "src/", + "" : "compat/" + } } } diff --git a/src/GeoIp2/Model/Country.php b/src/GeoIp2/Model/Country.php index 90f05be..2a9f341 100644 --- a/src/GeoIp2/Model/Country.php +++ b/src/GeoIp2/Model/Country.php @@ -33,7 +33,7 @@ namespace GeoIp2\Model; * @property \GeoIp2\Record\Traits $traits Data for the traits of the * requested IP address. */ -class Country +class Country implements \JsonSerializable { private $continent; private $country; @@ -92,4 +92,9 @@ class Country throw new \RuntimeException("Unknown attribute: $attr"); } + + public function jsonSerialize() + { + return $this->raw; + } } diff --git a/src/GeoIp2/Record/AbstractRecord.php b/src/GeoIp2/Record/AbstractRecord.php index e85a623..301d0b0 100644 --- a/src/GeoIp2/Record/AbstractRecord.php +++ b/src/GeoIp2/Record/AbstractRecord.php @@ -2,7 +2,7 @@ namespace GeoIp2\Record; -abstract class AbstractRecord +abstract class AbstractRecord implements \JsonSerializable { private $record; @@ -31,4 +31,9 @@ abstract class AbstractRecord throw new \RuntimeException("Unknown attribute: $attr"); } } + + public function jsonSerialize() + { + return $this->record; + } } diff --git a/tests/GeoIp2/Test/Model/CountryTest.php b/tests/GeoIp2/Test/Model/CountryTest.php index 73ed334..f4c2a3b 100644 --- a/tests/GeoIp2/Test/Model/CountryTest.php +++ b/tests/GeoIp2/Test/Model/CountryTest.php @@ -159,4 +159,35 @@ class CountryTest extends \PHPUnit_Framework_TestCase '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' + ); + } }