Passed
Branch develop (6c349f)
by compolom
02:01
created

Select::setFields()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.2
c 0
b 0
f 0
cc 4
eloc 11
nc 5
nop 1
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
        $this->setFields($fields);
29
    }
30
31
    private function setFields(array $fields): void
32
    {
33
        foreach ($fields as $allias => $column) {
34
            preg_match("#(?<fieldName>.*)\|(?<function>.*)#", $column, $matches);
35
            if (count($matches)) {
36
                $field = $matches['fieldName'];
37
                $object = $this->fields[$field] = new Fields($field);
38
                $object->setFunction($matches['function']);
39
            } else {
40
                $object = $this->fields[$column] = new Fields($column);
41
            }
42
            if (!is_int($allias)) {
43
                $object->setAllias($allias);
44
            }
45
        }
46
    }
47
48
    public function setFunction(string $fieldName, string $function): Select
49
    {
50
        if (!in_array($fieldName, array_keys($this->fields))) {
51
            throw new \InvalidArgumentException('Не найдено поле ' . $fieldName . ' |SELECT setFunction|');
52
        }
53
        $this->fields[$fieldName]->setFunction($function);
54
        return $this;
55
    }
56
57
    public function setAllias(string $fieldName, string $allias): Select
58
    {
59
        $this->fields[$fieldName]->setAllias($allias);
60
        return $this;
61
    }
62
63
    public function getFields(): string
64
    {
65
        return $this->concat(array_map(function(Fields $field): string {
66
            return $field->result();
67
        }, $this->fields));
68
    }
69
70
    public function get(): string
71
    {
72
        return 'SELECT ' . $this->getFields() . ' FROM '
73
            . $this->table()
74
            . (!is_null($this->join) ? $this->join->result() : '')
75
            . $this->getParts();
76
    }
77
}
78