1<?php
2
3namespace GeoIp2\Record;
4
5abstract class AbstractRecord implements \JsonSerializable
6{
7    private $record;
8
9    /**
10     * @ignore
11     *
12     * @param mixed $record
13     */
14    public function __construct($record)
15    {
16        $this->record = isset($record) ? $record : [];
17    }
18
19    /**
20     * @ignore
21     *
22     * @param mixed $attr
23     */
24    public function __get($attr)
25    {
26        // XXX - kind of ugly but greatly reduces boilerplate code
27        $key = $this->attributeToKey($attr);
28
29        if ($this->__isset($attr)) {
30            return $this->record[$key];
31        } elseif ($this->validAttribute($attr)) {
32            if (preg_match('/^is_/', $key)) {
33                return false;
34            }
35
36            return null;
37        }
38        throw new \RuntimeException("Unknown attribute: $attr");
39    }
40
41    public function __isset($attr)
42    {
43        return $this->validAttribute($attr) &&
44             isset($this->record[$this->attributeToKey($attr)]);
45    }
46
47    private function attributeToKey($attr)
48    {
49        return strtolower(preg_replace('/([A-Z])/', '_\1', $attr));
50    }
51
52    private function validAttribute($attr)
53    {
54        return in_array($attr, $this->validAttributes, true);
55    }
56
57    public function jsonSerialize()
58    {
59        return $this->record;
60    }
61}
62