summaryrefslogtreecommitdiff
path: root/app/frontend/db/ActiveRecord.php
blob: 45469dc6dcdb25de2ee00c17c194bfe730b392a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php

class ActiveRecord extends TActiveRecord {

    private function _getMappedPropertyName(string $name) {
        if (isset(static::$COLUMN_MAPPING[$name])) {
            return static::$COLUMN_MAPPING[$name];
        }
        return $name;
    }

    const DYNAMIC_METHODS = [
        'findby',
        'findallby',
        'deleteby',
        'deleteallby'
    ];

    private function _getMappedMethodName(string $method) {
        if (static::$COLUMN_MAPPING) {
            $methodParts = [];
            if (preg_match('/^(' . implode('|', self::DYNAMIC_METHODS) . ')(.*)$/i', $method, $methodParts)) {
                $methodParameters = [];
                $columnString = implode(
                    '|',
                    array_merge(
                        array_keys(static::$COLUMN_MAPPING),
                        array_values(static::$COLUMN_MAPPING)
                    )
                );
                $parameterRegex = '/(' . $columnString . ')(and|_and_|or|_or_)?/i';
                $method = $methodParts[1];
                if (preg_match_all($parameterRegex, $methodParts[2], $methodParameters, PREG_SET_ORDER)) {
                    foreach ($methodParameters as $parameter) {
                        $mappedColumn = array_search($parameter[1], static::$COLUMN_MAPPING);
                        $method .= ($mappedColumn !== FALSE) ? $mappedColumn : $parameter[1];
                        if (count($parameter) > 2) {
                            $method .= $parameter[2];
                        }
                    }
                }
            }
        }
        return $method;
    }

    public function __get($name) {
        $name = $this->_getMappedPropertyName($name);
        if (property_exists($this, $name)) {
            return $this->$name;
        }
        return parent::__get($name);
    }

    public function __set($name, $value) {
        $name = $this->_getMappedPropertyName($name);
        if (property_exists($this, $name)) {
            return $this->$name = $value;
        }
        return parent::__set($name, $value);
    }

    public function __call($method, $args) {
        return parent::__call($this->_getMappedMethodName($method), $args);
    }

    public static function finder($className=NULL) {
        if (NULL === $className) {
            $className = get_called_class();
        }
        return parent::finder($className);
    }

}

?>