Completed
Push — master ( 227237...06988d )
by Agel_Nash
02:25
created

SupportTrait::prepareWhere()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 5
nop 1
dl 0
loc 16
ccs 10
cts 10
cp 1
crap 5
rs 8.8571
c 0
b 0
f 0
1
<?php namespace AgelxNash\Modx\Evo\Database\Traits;
2
3
use AgelxNash\Modx\Evo\Database\Exceptions;
4
5
trait SupportTrait
6
{
7
    /**
8
     * @param null|string $key
9
     * @return mixed
10
     */
11
    abstract public function getConfig($key = null);
12
13
    /**
14
     * @param string $table
15
     * @param bool $escape
16
     * @return string
17
     * @throws Exceptions\TableNotDefinedException
18
     */
19 19
    public function getTableName(string $table, bool $escape = true): string
20
    {
21 19
        if (empty($table)) {
22 1
            throw new Exceptions\TableNotDefinedException($table);
23
        }
24
25 19
        $out = $this->getConfig('prefix') . $table;
26
27 19
        return $escape ? '`' . $out . '`' : $out;
28
    }
29
30
    /**
31
     * @param string $table
32
     * @return string
33
     * @throws Exceptions\TableNotDefinedException
34
     */
35 18
    public function getFullTableName(string $table): string
36
    {
37 18
        if (empty($table)) {
38 1
            throw new Exceptions\TableNotDefinedException($table);
39
        }
40
41 18
        return implode('.', [
42 18
            '`' . $this->getConfig('base') . '`',
43 18
            $this->getTableName($table)
44
        ]);
45
    }
46
47
    /**
48
     * @param $value
49
     * @return mixed
50
     */
51 5
    protected function convertValue($value)
52
    {
53
        switch (true) {
54 5
            case (\is_numeric($value) && ! \is_float(1 * $value)):
55 4
                $value = (int)$value;
56 4
                break;
57 4
            case \is_numeric($value) && \is_float(1*$value):
58 1
                $value = (float)$value;
59 1
                break;
60
            default:
61 4
                break;
62
        }
63
64 5
        return $value;
65
    }
66
67
    /**
68
     * @param int $timestamp
69
     * @param string $fieldType
70
     * @return bool|false|string
71
     * @deprecated
72
     */
73
    public function convertDate(int $timestamp, string $fieldType = 'DATETIME')
74
    {
75
        $date = false;
76
        if (!empty($timestamp) && $timestamp > 0) {
77
            switch ($fieldType) {
78
                case 'DATE':
79
                    $date = date('Y-m-d', $timestamp);
80
                    break;
81
                case 'TIME':
82
                    $date = date('H:i:s', $timestamp);
83
                    break;
84
                case 'YEAR':
85
                    $date = date('Y', $timestamp);
86
                    break;
87
                case 'DATETIME':
88
                default:
89
                    $date = date('Y-m-d H:i:s', $timestamp);
90
                    break;
91
            }
92
        }
93
94
        return $date;
95
    }
96
97
    /**
98
     * @param string|array $data
99
     * @param bool $ignoreAlias
100
     * @return string
101
     */
102 4
    protected function prepareFields($data, $ignoreAlias = false): string
103
    {
104 4
        if (\is_array($data)) {
105 2
            $tmp = [];
106 2
            foreach ($data as $alias => $field) {
107 2
                $tmp[] = ($alias !== $field && !\is_int($alias) && $ignoreAlias === false) ?
108 2
                    ($field . ' as `' . $alias . '`') : $field;
109
            }
110
111 2
            $data = implode(',', $tmp);
112
        }
113 4
        if (empty($data)) {
114
            $data = '*';
115
        }
116
117 4
        return $data;
118
    }
119
120
    /**
121
     * @param string|null $value
122
     * @return string
123
     * @throws Exceptions\InvalidFieldException
124
     */
125 6
    protected function prepareNull($value): string
126
    {
127
        switch (true) {
128 6
            case ($value === null || (\is_scalar($value) && strtolower($value) === 'null')):
129 3
                $value = 'NULL';
130 3
                break;
131 6
            case \is_scalar($value):
132 6
                $value = "'" . $value . "'";
133 6
                break;
134
            default:
135 1
                throw (new Exceptions\InvalidFieldException('NULL'))
136 1
                    ->setData($value);
137
        }
138
139 6
        return $value;
140
    }
141
142
    /**
143
     * @param string|array $data
144
     * @param int $level
145
     * @param bool $skipFieldNames
146
     * @return array|string
147
     * @throws Exceptions\TooManyLoopsException
148
     * @throws Exceptions\InvalidFieldException
149
     */
150 4
    protected function prepareValues($data, $level = 1, $skipFieldNames = false)
151
    {
152 4
        $fields = [];
153 4
        $values = [];
154 4
        $maxLevel = $level;
155 4
        $wrap = false;
156
157 4
        if (\is_array($data)) {
158 4
            foreach ($data as $key => $value) {
159 4
                if (\is_array($value)) {
160 1
                    if ($level > 2) {
161
                        throw new Exceptions\TooManyLoopsException('Values');
162
                    }
163 1
                    $maxLevel++;
164 1
                    $out = $this->prepareValues($value, $level + 1);
165 1
                    if (empty($fields)) {
166 1
                        $fields = $out['fields'];
167 1
                    } elseif ($fields !== $out['fields'] && $skipFieldNames === false) {
168
                        throw (new Exceptions\InvalidFieldException("Don't match field names"))
169
                            ->setData($data);
170
                    }
171 1
                    $wrap = true;
172 1
                    $values[] = $out['values'];
173
                } else {
174 4
                    $fields[] = $key;
175 4
                    $values[] = $this->prepareNull($value);
176
                }
177
            }
178 4
            if (\is_array($values)) {
179 4
                $values = implode(', ', $values);
180
            }
181 4
            if ($wrap === false) {
182 4
                $values = '(' . $values . ')';
183
            }
184
        }
185
186 4
        if (!\is_scalar($values)) {
187
            throw (new Exceptions\InvalidFieldException('values'))
188
                ->setData($values);
189
        }
190
191 4
        if (($fields = $this->checkFields($fields, $maxLevel, $skipFieldNames)) === false) {
192
            throw (new Exceptions\InvalidFieldException('fields name'))
193
                ->setData($data);
194
        }
195
196 4
        if ($level === 2) {
197 1
            return compact('fields', 'values');
198
        }
199
200 4
        return (empty($fields) ? '' : $fields . ' VALUES ') . $values;
201
    }
202
203
    /**
204
     * @param mixed $fields
205
     * @param int $level
206
     * @param bool $skipFieldNames
207
     * @return bool|string
208
     */
209 4
    protected function checkFields($fields, $level = 1, bool $skipFieldNames = false)
210
    {
211 4
        if (\is_array($fields) && $skipFieldNames === false) {
212 4
            if ($this->arrayOnlyNumeric($fields) === true) {
213 1
                $fields = ($level === 2) ? false : '';
214
            } else {
215 4
                $fields = '(`' . implode('`, `', $fields) . '`)';
216
            }
217
        }
218
219 4
        return $fields;
220
    }
221
222
    /**
223
     * @param array $data
224
     * @return bool
225
     */
226 6
    protected function arrayOnlyNumeric(array $data) : bool
227
    {
228 6
        $onlyNumbers = true;
229 6
        foreach ($data as $value) {
230 6
            if (!\is_numeric($value)) {
231 5
                $onlyNumbers = false;
232 6
                break;
233
            }
234
        }
235
236 6
        return $onlyNumbers;
237
    }
238
239
    /**
240
     * @param string|array $data
241
     * @return string
242
     * @throws Exceptions\InvalidFieldException
243
     */
244 2
    protected function prepareValuesSet($data): string
245
    {
246 2
        if (\is_array($data)) {
247 2
            foreach ($data as $key => $value) {
248 2
                $data[$key] = $this->prepareNull($value);
249
            }
250
251 2
            foreach ($data as $key => $value) {
252 2
                $data[$key] = "`{$key}` = " . $value;
253
            }
254 2
            $data = implode(', ', $data);
255
        }
256
257 2
        return trim($data);
258
    }
259
260
    /**
261
     * @param string|array $data
262
     * @param bool $hasArray
263
     * @return string
264
     * @throws Exceptions\TableNotDefinedException
265
     */
266 7
    protected function prepareFrom($data, bool $hasArray = false): string
267
    {
268 7
        if (\is_array($data) && $hasArray === true) {
269 2
            $tmp = [];
270 2
            foreach ($data as $table) {
271 2
                $tmp[] = $table;
272
            }
273 2
            $data = implode(' ', $tmp);
274
        }
275 7
        if (!is_scalar($data) || empty($data)) {
276
            throw new Exceptions\TableNotDefinedException($data);
277
        }
278
279 7
        return $data;
280
    }
281
282
    /**
283
     * @param array|string $data
284
     * @return string
285
     * @throws Exceptions\InvalidFieldException
286
     */
287 6
    protected function prepareWhere($data): string
288
    {
289 6
        if (\is_array($data)) {
290 2
            if ($this->arrayOnlyNumeric(array_keys($data)) === true) {
291 2
                $data = implode(' ', $data);
292
            } else {
293 1
                throw (new Exceptions\InvalidFieldException('WHERE'))
294 1
                    ->setData($data);
295
            }
296
        }
297 6
        $data = trim($data);
298 6
        if (!empty($data) && stripos($data, 'WHERE') !== 0) {
299 5
            $data = "WHERE {$data}";
300
        }
301
302 6
        return $data;
303
    }
304
305
    /**
306
     * @param string $data
307
     * @return string
308
     */
309 5
    protected function prepareOrder($data): string
310
    {
311 5
        $data = trim($data);
312 5
        if (!empty($data) && stripos($data, 'ORDER') !== 0) {
313 3
            $data = "ORDER BY {$data}";
314
        }
315
316 5
        return $data;
317
    }
318
319
    /**
320
     * @param string $data
321
     * @return string
322
     */
323 5
    protected function prepareLimit($data): string
324
    {
325 5
        $data = trim($data);
326 5
        if (!empty($data) && stripos($data, 'LIMIT') !== 0) {
327 3
            $data = "LIMIT {$data}";
328
        }
329
330 5
        return $data;
331
    }
332
}
333