Lines 100.00% 25 / 25
Functions and Methods 100.00% 5 / 5
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
Insert 100.00% 25 / 25 100.00% 5 / 5 9 100.00% 1 / 1
 sql 100.00% 8 / 8 100.00% 1 / 1 2
 valuesSQL 100.00% 10 / 10 100.00% 1 / 1 3
 params 100.00% 1 / 1 100.00% 1 / 1 1
 reset 100.00% 3 / 3 100.00% 1 / 1 1
 allTablesReferenced 100.00% 3 / 3 100.00% 1 / 1 2
1<?php
2
3namespace BO\Zmsbackend\Query\Builder;
4
5/**
6 * Insert
7 *
8 * Generates an SQL query for an INSERT operation.
9 *
10 * @package     BO\Zmsbackend\Query\Builder
11 * @author      Alex Gisby<alex@solution10.com>
12 * @license     MIT
13 */
14class Insert extends Query
15{
16    use TableName;
17    use Values;
18
19    /**
20     * @var     string      The base part of the query
21     */
22    protected $queryBase = 'INSERT INTO';
23
24    /**
25     * Generates the full SQL statement for this query with all the composite parts.
26     *
27     * @return  string
28     */
29    #[\Override]
30    public function sql()
31    {
32        if ($this->table === null) {
33            return '';
34        }
35
36        $candidateParts = [
37            $this->queryBase,
38            $this->dialect->quoteTable($this->table),
39            $this->valuesSQL(),
40        ];
41
42        return implode(' ', $candidateParts);
43    }
44
45    /**
46     * Returns the values part of a query for an INSERT statement (so using VALUES())
47     *
48     * @return  string
49     */
50    protected function valuesSQL()
51    {
52        $sql = '';
53        if (!empty($this->values)) {
54            $keyParts = [];
55            $valueParts = [];
56            foreach (array_keys($this->values) as $field) {
57                $keyParts[]     = $this->dialect->quoteField($field);
58                $valueParts[]   = '?';
59            }
60
61            $sql .= '(' . implode(', ', $keyParts) . ') ';
62            $sql .= 'VALUES (' . implode(', ', $valueParts) . ')';
63        }
64        return $sql;
65    }
66
67    /**
68     * Returns all the parameters, in the correct order, to pass into PDO.
69     *
70     * @return  array
71     */
72    #[\Override]
73    public function params()
74    {
75        return array_values($this->values);
76    }
77
78    /**
79     * Resets the entire query.
80     *
81     * @return  $this
82     */
83    #[\Override]
84    public function reset()
85    {
86        $this->table = null;
87        $this->resetValues();
88        return $this;
89    }
90
91    /*
92     * ------------------- All Tables ------------------------
93     */
94
95    /**
96     * Returns all the tables that this query makes mention of, in FROMs and JOINs
97     *
98     * @return  array
99     */
100    #[\Override]
101    public function allTablesReferenced()
102    {
103        if ($this->table()) {
104            return [$this->table()];
105        }
106        return [];
107    }
108}