From fbbe2dba248c6b972b68ae9898b92992e6dfa783 Mon Sep 17 00:00:00 2001 From: Gregory Oschwald Date: Mon, 2 Dec 2013 10:02:37 -0800 Subject: [PATCH] Fix isset for models/records --- src/GeoIp2/Model/Country.php | 8 ++++++++ src/GeoIp2/Record/AbstractRecord.php | 23 +++++++++++++++++++---- tests/GeoIp2/Test/Model/CountryTest.php | 16 ++++++++++++++++ 3 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/GeoIp2/Model/Country.php b/src/GeoIp2/Model/Country.php index 06c80f7..c3ba143 100644 --- a/src/GeoIp2/Model/Country.php +++ b/src/GeoIp2/Model/Country.php @@ -93,6 +93,14 @@ class Country implements \JsonSerializable throw new \RuntimeException("Unknown attribute: $attr"); } + /** + * @ignore + */ + public function __isset($attr) + { + return $attr != "instance" && isset($this->$attr); + } + public function jsonSerialize() { return $this->raw; diff --git a/src/GeoIp2/Record/AbstractRecord.php b/src/GeoIp2/Record/AbstractRecord.php index 301d0b0..77e43dd 100644 --- a/src/GeoIp2/Record/AbstractRecord.php +++ b/src/GeoIp2/Record/AbstractRecord.php @@ -19,19 +19,34 @@ abstract class AbstractRecord implements \JsonSerializable */ public function __get($attr) { - $valid = in_array($attr, $this->validAttributes); // XXX - kind of ugly but greatly reduces boilerplate code - $key = strtolower(preg_replace('/([A-Z])/', '_\1', $attr)); + $key = $this->attributeToKey($attr); - if ($valid && isset($this->record[$key])) { + if ($this->__isset($attr)) { return $this->record[$key]; - } elseif ($valid) { + } elseif ($this->validAttribute($attr)) { return null; } else { throw new \RuntimeException("Unknown attribute: $attr"); } } + public function __isset($attr) + { + return $this->validAttribute($attr) && + isset($this->record[$this->attributeToKey($attr)]); + } + + private function attributeToKey($attr) + { + return strtolower(preg_replace('/([A-Z])/', '_\1', $attr)); + } + + public function validAttribute($attr) + { + return in_array($attr, $this->validAttributes); + } + public function jsonSerialize() { return $this->record; diff --git a/tests/GeoIp2/Test/Model/CountryTest.php b/tests/GeoIp2/Test/Model/CountryTest.php index f4c2a3b..91c4556 100644 --- a/tests/GeoIp2/Test/Model/CountryTest.php +++ b/tests/GeoIp2/Test/Model/CountryTest.php @@ -190,4 +190,20 @@ class CountryTest extends \PHPUnit_Framework_TestCase 'json_encode can be called on the record object directly' ); } + + public function testIsSet() + { + $this->assertTrue(isset($this->model->traits), 'traits is set'); + $this->assertFalse(isset($this->model->unknown), 'unknown is not set'); + + $this->assertTrue( + isset($this->model->traits->ipAddress), + 'ip_address is set' + ); + $this->assertFalse( + isset($this->model->traits->unknown), + 'unknown trait is not set' + ); + + } }