Passed
Push — master ( 4c916a...c716e1 )
by compolom
01:44
created

Insert::preSet()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 2
1
<?php declare(strict_types=1);
2
3
namespace Compolomus\LSQLQueryBuilder\Parts;
4
5
use Compolomus\LSQLQueryBuilder\System\Traits\{
6
    Helper,
7
    Caller,
8
    Placeholders
9
};
10
11
/**
12
 * @method string table()
13
 * @method void addPlaceholders($placeholders)
14
 */
15
class Insert
16
{
17
    use Caller, Placeholders, Helper;
18
19
    protected $fields = [];
20
21
    protected $values = [];
22
23
    public function __construct(array $args = [])
24
    {
25
        if (count($args) > 0) {
26
            if (is_string(key($args))) {
27
                $this->fields(array_keys($args));
28
            }
29
            $this->values(array_values($args));
30
        }
31
    }
32
33
    public function fields(array $fields): Insert
34
    {
35
        $this->fields = $fields;
36
        return $this;
37
    }
38
39
    public function values(array $values): Insert
40
    {
41
        $this->values[] = $this->set($values);
42
        return $this;
43
    }
44
45
    protected function preSet(array $values, string $flag): array
46
    {
47
        $result = [];
48
        foreach ($values as $value) {
49
            $key = $this->uid($flag);
50
            $result[] = ':' . $key;
51
            $this->placeholders()->set($key, $value);
52
        }
53
        return $result;
54
    }
55
56
    protected function set(array $values): string
57
    {
58
        return '(' . implode(',', $this->preSet($values, 'i')) . ')';
59
    }
60
61
    public function get(): string
62
    {
63
        $this->addPlaceholders($this->placeholders()->get());
64
        return 'INSERT INTO ' . $this->table() . ' '
65
            . (count($this->fields) ? '(' . implode(',', $this->escapeField($this->fields)) . ')' : '')
66
            . ' VALUES '
67
            . (count($this->values)
68
                ? implode(',', $this->values)
69
                : (count($this->fields) && !count($this->values)
70
                    ? '(' . implode(',', array_fill(0, count($this->fields), '?')) . ')'
71
                    : '')
72
            );
73
    }
74
}
75