Passed
Push — master ( c716e1...3ae7db )
by compolom
02:01
created

Select::setField()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 4
nop 2
1
<?php declare(strict_types=1);
2
3
namespace Compolomus\LSQLQueryBuilder\Parts;
4
5
use Compolomus\LSQLQueryBuilder\System\{
6
    Traits\Helper,
7
    Traits\GetParts,
8
    Traits\Join as TJoin,
9
    Traits\Limit as TLimit,
10
    Traits\Where as TWhere,
11
    Traits\Order as TOrder,
12
    Traits\Group as TGroup,
13
    Traits\Caller,
14
    Fields
15
};
16
17
/**
18
 * @method string table()
19
 */
20
class Select
21
{
22
    use TJoin, TLimit, TWhere, TOrder, TGroup, Caller, GetParts, Helper;
23
24
    private $fields = [];
25
26
    public function __construct(array $fields = ['*'])
27
    {
28
        array_map([$this, 'setField'], array_keys($fields), array_values($fields));
29
    }
30
31
    private function setField($allias, $value): void
32
    {
33
        preg_match("#(?<fieldName>\w{2,}|\*)(\|(?<function>\w{2,}))?#is", $value, $matches);
34
        $field = $matches['fieldName'];
35
        $object = $this->fields[$field] = new Fields($field);
36
        if (isset($matches['function'])) {
37
            $object->setFunction($matches['function']);
38
        }
39
        if (!is_int($allias)) {
40
            $object->setAllias($allias);
41
        }
42
    }
43
44
    public function setFunction(string $fieldName, string $function): Select
45
    {
46
        if (!in_array($fieldName, array_keys($this->fields))) {
47
            throw new \InvalidArgumentException('Не найдено поле ' . $fieldName . ' |SELECT setFunction|');
48
        }
49
        $this->fields[$fieldName]->setFunction($function);
50
        return $this;
51
    }
52
53
    public function setAllias(string $fieldName, string $allias): Select
54
    {
55
        $this->fields[$fieldName]->setAllias($allias);
56
        return $this;
57
    }
58
59
    public function getFields(): string
60
    {
61
        return $this->concat(array_map(function(Fields $field): string {
62
            return $field->result();
63
        }, $this->fields));
64
    }
65
66
    public function get(): string
67
    {
68
        return 'SELECT ' . $this->getFields() . ' FROM '
69
            . $this->table()
70
            . (!is_null($this->join) ? $this->join->result() : '')
71
            . $this->getParts();
72
    }
73
}
74