Passed
Branch main (d0474b)
by Sammy
03:57 queued 02:09
created

TableModel.php (2 issues)

Severity
1
<?php
2
3
namespace HexMakina\TightORM;
4
5
use HexMakina\Crudites\Crudites;
6
use HexMakina\Crudites\CruditesException;
7
8
use HexMakina\Crudites\Interfaces\TableManipulationInterface;
9
use HexMakina\Crudites\Interfaces\SelectInterface;
10
11
abstract class TableModel extends Crudites
12
{
13
14
    //check all primary keys are set (FIXME that doesn't work unles AIPK.. nice try)
15
    public function is_new(): bool
16
    {
17
        $match = static::table()->primary_keys_match(get_object_vars($this));
18
        return empty($match);
19
    }
20
21
    public function get_id($mode = null)
22
    {
23
        $primary_key = static::table()->auto_incremented_primary_key();
24
        if (is_null($primary_key) && count($pks = static::table()->primary_keys()) == 1) {
25
            $primary_key = current($pks);
26
        }
27
28
        return $mode === 'name' ? $primary_key->name() : $this->get($primary_key->name());
29
    }
30
31
    public function get($prop_name)
32
    {
33
        if (property_exists($this, $prop_name) === true) {
34
            return $this->$prop_name;
35
        }
36
37
        return null;
38
    }
39
40
    public function set($prop_name, $value)
41
    {
42
        $this->$prop_name = $value;
43
    }
44
45
    public function import($assoc_data)
46
    {
47
        if (!is_array($assoc_data)) {
48
            throw new \Exception(__FUNCTION__ . '(assoc_data) parm is not an array');
49
        }
50
51
        // shove it all up in model, god will sort them out
52
        foreach ($assoc_data as $field => $value) {
53
            $this->set($field, $value);
54
        }
55
56
        return $this;
57
    }
58
59
    public static function table(): TableManipulationInterface
60
    {
61
        $table = static::table_name();
62
        $table = self::inspect($table);
63
64
        return $table;
65
    }
66
67
    public static function table_name(): string
68
    {
69
        $reflect = new \ReflectionClass(get_called_class());
70
71
        $table_name = $reflect->getConstant('TABLE_NAME');
72
73
        if ($table_name === false) {
74
            $calling_class = $reflect->getShortName();
75
            if (defined($const_name = 'TABLE_' . strtoupper($calling_class))) {
76
                $table_name = constant($const_name);
77
            } else {
78
                $table_name = strtolower($calling_class);
79
            }
80
        }
81
82
        return $table_name;
83
    }
84
85
86
    public function to_table_row($operator_id = null)
87
    {
88
        if (!is_null($operator_id) && $this->is_new() && is_null($this->get('created_by'))) {
89
            $this->set('created_by', $operator_id);
90
        }
91
92
        $model_data = get_object_vars($this);
93
94
        // 1. Produce OR restore a row
95
        if ($this->is_new()) {
96
            $table_row = static::table()->produce($model_data);
97
        } else {
98
            $table_row = static::table()->restore($model_data);
99
        }
100
101
        // 2. Apply alterations from form_model data
102
        $table_row->alter($model_data);
103
104
        return $table_row;
105
    }
106
107
108
    public static function query_retrieve($filters = [], $options = []): SelectInterface
0 ignored issues
show
The parameter $filters is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

108
    public static function query_retrieve(/** @scrutinizer ignore-unused */ $filters = [], $options = []): SelectInterface

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
The parameter $options is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

108
    public static function query_retrieve($filters = [], /** @scrutinizer ignore-unused */ $options = []): SelectInterface

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
109
    {
110
        return static::table()->select();
111
    }
112
113
114
    // success: return PK-indexed array of results (associative array or object)
115
    public static function retrieve(SelectInterface $Query): array
116
    {
117
        $ret = [];
118
        $pk_name = implode('_', array_keys($Query->table()->primary_keys()));
119
120
        if (count($pks = $Query->table()->primary_keys()) > 1) {
121
            $concat_pk = sprintf('CONCAT(%s) as %s', implode(',', $pks), $pk_name);
122
            $Query->select_also([$concat_pk]);
123
        }
124
125
        try {
126
            $Query->run();
127
        } catch (CruditesException $e) {
128
            return [];
129
        }
130
131
        if ($Query->is_success()) {
132
            foreach ($Query->ret_obj(get_called_class()) as $rec) {
133
                  $ret[$rec->get($pk_name)] = $rec;
134
            }
135
        }
136
137
        return $ret;
138
    }
139
140
    /* USAGE
141
    * one($primary_key_value)
142
    * one($unique_column, $value)
143
    */
144
    public static function one($arg1, $arg2 = null)
145
    {
146
        $mixed_info = is_null($arg2) ? $arg1 : [$arg1 => $arg2];
147
148
        $unique_identifiers = get_called_class()::table()->match_uniqueness($mixed_info);
149
150
        if (empty($unique_identifiers)) {
151
            throw new CruditesException('UNIQUE_IDENTIFIER_NOT_FOUND');
152
        }
153
154
        $Query = static::query_retrieve([], ['eager' => true])->aw_fields_eq($unique_identifiers);
155
        switch (count($res = static::retrieve($Query))) {
156
            case 0:
157
                throw new CruditesException('INSTANCE_NOT_FOUND');
158
            case 1:
159
                return current($res);
160
            default:
161
                throw new CruditesException('SINGULAR_INSTANCE_ERROR');
162
        }
163
    }
164
165
    public static function exists($arg1, $arg2 = null)
166
    {
167
        try {
168
            return self::one($arg1, $arg2);
169
        } catch (CruditesException $e) {
170
            return null;
171
        }
172
    }
173
174
175
    public static function any($field_exact_values, $options = [])
176
    {
177
        $Query = static::query_retrieve([], $options)->aw_fields_eq($field_exact_values);
178
        return static::retrieve($Query);
179
    }
180
181
    public static function filter($filters = [], $options = []): array
182
    {
183
        return static::retrieve(static::query_retrieve($filters, $options));
184
    }
185
186
    public static function listing($filters = [], $options = []): array
187
    {
188
        return static::retrieve(static::query_retrieve($filters, $options)); // listing as arrays for templates
189
    }
190
191
192
193
    public static function get_many_by_AIPK($aipk_values)
194
    {
195
        if (!empty($aipk_values) && !is_null($AIPK = static::table()->auto_incremented_primary_key())) {
196
            return static::retrieve(static::table()->select()->aw_numeric_in($AIPK, $aipk_values));
197
        }
198
199
        return null;
200
    }
201
202
203
}
204