Merge pull request #8 from maxmind/greg/isset

Fix isset for models/records
This commit is contained in:
Boris Zentner 2013-12-02 12:00:36 -08:00
commit a29e43bad4
3 changed files with 43 additions and 4 deletions

View File

@ -93,6 +93,14 @@ class Country implements \JsonSerializable
throw new \RuntimeException("Unknown attribute: $attr"); throw new \RuntimeException("Unknown attribute: $attr");
} }
/**
* @ignore
*/
public function __isset($attr)
{
return $attr != "instance" && isset($this->$attr);
}
public function jsonSerialize() public function jsonSerialize()
{ {
return $this->raw; return $this->raw;

View File

@ -19,19 +19,34 @@ abstract class AbstractRecord implements \JsonSerializable
*/ */
public function __get($attr) public function __get($attr)
{ {
$valid = in_array($attr, $this->validAttributes);
// XXX - kind of ugly but greatly reduces boilerplate code // 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]; return $this->record[$key];
} elseif ($valid) { } elseif ($this->validAttribute($attr)) {
return null; return null;
} else { } else {
throw new \RuntimeException("Unknown attribute: $attr"); 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));
}
private function validAttribute($attr)
{
return in_array($attr, $this->validAttributes);
}
public function jsonSerialize() public function jsonSerialize()
{ {
return $this->record; return $this->record;

View File

@ -190,4 +190,20 @@ class CountryTest extends \PHPUnit_Framework_TestCase
'json_encode can be called on the record object directly' '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'
);
}
} }