Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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