Completed
Push — master ( cda99f...f447a0 )
by Oscar
01:28
created

Insert::orIgnore()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 3
nc 3
nop 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace SimpleCrud\Queries;
5
6
use SimpleCrud\Table;
7
8
final class Insert extends Query
9
{
10
    protected const ALLOWED_METHODS = [
11
        'setFlag',
12
        'set',
13
    ];
14
15
    public function __construct(Table $table, array $data = [])
16
    {
17
        $this->table = $table;
18
19
        $this->query = $table->getDatabase()
20
            ->insert()
21
            ->into((string) $table);
22
23
        foreach ($data as $fieldName => $value) {
24
            $this->table->{$fieldName}->insert($this->query, $value);
25
        }
26
    }
27
28
    public function orIgnore(): self
29
    {
30
        $engine = $this->table->getDatabase()->getConnection()->getDriverName();
31
32
        switch ($engine) {
33
            case 'mysql':
34
                $this->query->setFlag('IGNORE');
35
                break;
36
            case 'sqlite':
37
                $this->query->setFlag('OR IGNORE');
38
                break;
39
        }
40
41
        return $this;
42
    }
43
44
    public function run()
45
    {
46
        $this->__invoke();
47
48
        $id = $this->table->getDatabase()->lastInsertId();
49
50
        return $this->table->id->format($id);
51
    }
52
}
53