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

Insert   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 6
dl 0
loc 45
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 2
A orIgnore() 0 15 3
A run() 0 8 1
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