Passed
Push — main ( 65d634...249587 )
by Thierry
19:37 queued 17:18
created

InputFieldTrait::getInputFieldExpression()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 15
c 1
b 0
f 0
nc 8
nop 3
dl 0
loc 23
rs 8.4444
1
<?php
2
3
namespace Lagdo\DbAdmin\Admin\Traits;
4
5
use Lagdo\DbAdmin\Driver\Entity\TableFieldEntity;
6
7
use function preg_match;
8
9
trait InputFieldTrait
10
{
11
    /**
12
     * @param TableFieldEntity $field
13
     * @param string $value
14
     * @param string $function
15
     *
16
     * @return string
17
     */
18
    private function getInputFieldExpression(TableFieldEntity $field, string $value, string $function): string
19
    {
20
        $expression = $this->driver->quote($value);
21
        if (preg_match('~^(now|getdate|uuid)$~', $function)) {
22
            return "$function()";
23
        }
24
        if (preg_match('~^current_(date|timestamp)$~', $function)) {
25
            return $function;
26
        }
27
        if (preg_match('~^([+-]|\|\|)$~', $function)) {
28
            return $this->driver->escapeId($field->name) . " $function $expression";
29
        }
30
        if (preg_match('~^[+-] interval$~', $function)) {
31
            return $this->driver->escapeId($field->name) . " $function " .
32
                (preg_match("~^(\\d+|'[0-9.: -]') [A-Z_]+\$~i", $value) ? $value : $expression);
33
        }
34
        if (preg_match('~^(addtime|subtime|concat)$~', $function)) {
35
            return "$function(" . $this->driver->escapeId($field->name) . ", $expression)";
36
        }
37
        if (preg_match('~^(md5|sha1|password|encrypt)$~', $function)) {
38
            return "$function($expression)";
39
        }
40
        return $expression;
41
    }
42
43
    /**
44
     * @param TableFieldEntity $field Single field from fields()
45
     * @param string $value
46
     * @param string $function
47
     *
48
     * @return string
49
     */
50
    protected function getUnconvertedFieldValue(TableFieldEntity $field, string $value, string $function = ''): string
51
    {
52
        if ($function === 'SQL') {
53
            return $value; // SQL injection
54
        }
55
56
        $expression = $this->getInputFieldExpression($field, $value, $function);
57
        return $this->driver->unconvertField($field, $expression);
58
    }
59
}
60