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

InputFieldTrait   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 49
rs 10
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B getInputFieldExpression() 0 23 8
A getUnconvertedFieldValue() 0 8 2
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