Completed
Push — master ( 792d52...bce0ff )
by Oscar
01:33
created

Insert::__toString()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 14
nc 4
nop 0
1
<?php
2
3
namespace SimpleCrud\Queries\Mysql;
4
5
use SimpleCrud\Queries\Query;
6
use SimpleCrud\Table;
7
8
/**
9
 * Manages a database insert query in Mysql databases.
10
 */
11
class Insert extends Query
12
{
13
    protected $data = [];
14
    protected $duplications;
15
16
    /**
17
     * Set the data to insert.
18
     *
19
     * @param array      $data
20
     * @param array|null $prepared
21
     *
22
     * @return self
23
     */
24 View Code Duplication
    public function data(array $data, array &$prepared = null)
25
    {
26
        $this->data = $this->table->prepareDataToDatabase($data, true);
27
28
        if (is_array($prepared)) {
29
            foreach ($this->data as $field => $value) {
30
                $prepared[$field] = $this->table->$field->dataFromDatabase($value);
31
            }
32
        }
33
34
        return $this;
35
    }
36
37
    /**
38
     * Set true to handle duplications.
39
     *
40
     * @param bool $handle
41
     *
42
     * @return self
43
     */
44
    public function duplications($handle = true)
45
    {
46
        $this->duplications = $handle;
47
48
        return $this;
49
    }
50
51
    /**
52
     * Run the query and return the id.
53
     *
54
     * @return int
55
     */
56
    public function run()
57
    {
58
        $this->__invoke();
59
60
        $id = $this->table->getDatabase()->lastInsertId();
61
62
        return $this->table->id->dataFromDatabase($id);
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 View Code Duplication
    public function __invoke()
69
    {
70
        $marks = [];
71
72
        foreach ($this->data as $field => $value) {
73
            $marks[":{$field}"] = $value;
74
        }
75
76
        return $this->table->getDatabase()->execute((string) $this, $marks);
77
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82
    public function __toString()
83
    {
84
        if (empty($this->data)) {
85
            return "INSERT INTO `{$this->table->getName()}` (`id`) VALUES (NULL)";
86
        }
87
88
        $fields = array_intersect_key($this->table->getFields(), $this->data);
89
90
        $query = "INSERT INTO `{$this->table->getName()}`";
91
        $query .= ' (`'.implode('`, `', array_keys($fields)).'`)';
92
        $query .= ' VALUES ('.self::buildFields($fields).')';
93
94
        if ($this->duplications) {
95
            if (!isset($this->data['id'])) {
96
                unset($fields['id']);
97
            }
98
99
            $query .= ' ON DUPLICATE KEY UPDATE';
100
            $query .= ' id = LAST_INSERT_ID(id), '.Update::buildFields($fields);
101
102
            var_dump($query);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($query); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
103
        }
104
105
        return $query;
106
    }
107
108
    /**
109
     * Generates the data part of a UPDATE query.
110
     *
111
     * @param array $fields
112
     *
113
     * @return string
114
     */
115 View Code Duplication
    protected static function buildFields(array $fields)
116
    {
117
        $query = [];
118
119
        foreach ($fields as $fieldName => $field) {
120
            $query[] = $field->getValueExpression(":{$fieldName}");
121
        }
122
123
        return implode(', ', $query);
124
    }
125
}
126