Completed
Push — feature/fixing_cost ( ef981e )
by Laurent
01:53
created

AbstractDomainRepository::write()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 2
nop 1
dl 0
loc 28
rs 9.1608
c 0
b 0
f 0
1
<?php
2
3
4
namespace FlightLog\Infrastructure\Common\Repository;
5
6
7
abstract class AbstractDomainRepository
8
{
9
    /**
10
     * @var \DoliDB
11
     */
12
    private $db;
13
14
    /**
15
     * @var string
16
     */
17
    private $tableName;
18
19
    /**
20
     * @param \DoliDB $db
21
     * @param string $tableName
22
     */
23
    public function __construct(\DoliDB $db, $tableName)
24
    {
25
        $this->db = $db;
26
        $this->tableName = strpos($tableName, MAIN_DB_PREFIX) === 0 ? $tableName : MAIN_DB_PREFIX.$tableName;
27
    }
28
29
    /**
30
     * @param array $elements
31
     *
32
     * @return float|int
33
     *
34
     * @throws \Exception
35
     */
36
    protected function write(array $elements){
37
        $columns = join(',', array_keys($elements));
38
        $values = join(',', array_map(function($value){
39
                if(is_null($value)){
40
                    return null;
41
                }
42
43
                if(is_bool($value)){
44
                    return (int)$value;
45
                }
46
47
                return is_string($value) ? $this->db->escape($value) : $value ;
48
            }, array_values($elements)));
49
50
        $this->db->begin();
51
        $resql = $this->db->query(sprintf('INSERT INTO ' . $this->tableName . '(%s) VALUES (%s)', $columns, $values));
52
53
        if (!$resql) {
54
            $lasterror = $this->db->lasterror();
55
            dol_syslog(__METHOD__ . ' ' . $lasterror, LOG_ERR);
56
            $this->db->rollback();
57
            throw new \Exception("Repository error - ".$lasterror);
58
        }
59
60
        $id = $this->db->last_insert_id($this->tableName);
61
        $this->db->commit();
62
        return $id;
63
    }
64
65
66
}