Select::execute()   A
last analyzed

Complexity

Conditions 4
Paths 13

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 14
cts 14
cp 1
rs 9.6333
c 0
b 0
f 0
cc 4
nc 13
nop 1
crap 4
1
<?php
2
/*
3
 * The MIT License
4
 *
5
 * Copyright 2017 David Schoenbauer <[email protected]>.
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the "Software"), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in
15
 * all copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
 * THE SOFTWARE.
24
 */
25
namespace DSchoenbauer\Sql\Command;
26
27
use DSchoenbauer\Sql\Exception\ExecutionErrorException;
28
use DSchoenbauer\Sql\Exception\NoRecordsAffectedException;
29
use DSchoenbauer\Sql\Exception\NoRecordsAffectedSelectException;
30
use DSchoenbauer\Sql\Where\WhereStatementInterface;
31
use PDO;
32
use PDOStatement;
33
34
/**
35
 * retrieves data from a PDO connected resource
36
 * @author David Schoenbauer <[email protected]>
37
 */
38
class Select extends AbstractCommand
39
{
40
41
    private $table;
42
    private $fields = ['*'];
43
    private $data = null;
44
    private $fetchStyle = \PDO::FETCH_ASSOC;
45
    private $fetchFlat = false;
46
    private $defaultValue = [];
47
48
    use WhereTrait;
49
50
    /**
51
     * retrieves data from a PDO connected resource
52
     * @param string $table name of the table that houses the data
53
     * @param array $fields optional default value: empty array - defines which
54
     * fields are returned if no fields defined a star will be used
55
     * @param null|WhereStatementInterface $where optional default value: null -
56
     * object used to limit the returned results
57
     * @param integer $fetchStyle optional default value: PDO::FETCH_ASSOC -
58
     * sets how the PDO statement will return records
59
     * @param boolean $fetchFlat optional default value: false - true will
60
     * return one record, false will return all records
61
     * @param mixed $defaultValue optional default value: empty array -
62
     * value to be returned on query failure
63
     * @since v1.0.0
64
     */
65 23
    public function __construct(
66
        $table,
67
        $fields = [],
68
        WhereStatementInterface $where = null,
69
        $fetchStyle = \PDO::FETCH_ASSOC,
70
        $fetchFlat = false,
71
        $defaultValue = []
72
    ) {
73
    
74
75
76 23
        $this->setTable($table)
77 23
            ->setFields($fields)
78 23
            ->setFetchStyle($fetchStyle)
79 23
            ->setFetchFlat($fetchFlat)
80 23
            ->setDefaultValue($defaultValue)
81 23
            ->setWhere($where);
82 23
    }
83
84
    /**
85
     * Runs a query and returns the result of the SQL
86
     * @param PDO $pdo a PDO  connection object
87
     * @return mixed with return the result set as defined by fetchStyle
88
     * @throws ExecutionErrorException on SQL error with the message of the exception
89
     * @since v1.0.0
90
     */
91 10
    public function execute(PDO $pdo)
92
    {
93
        try {
94 10
            $stmt = $pdo->prepare($this->getSql());
95 9
            $this->statementExecute($stmt, $this->getWhereData());
96 9
            $this->checkAffected($stmt, new NoRecordsAffectedSelectException());
97 8
            $data = $this->fetchData(
98 8
                $stmt,
99 8
                $this->getFetchFlat(),
100 8
                $this->getFetchStyle()
101
            );
102 8
            $this->setData($data ?: $this->getDefaultValue());
103 8
            return $this->getData();
104 2
        } catch (NoRecordsAffectedException $exc) {
105 1
            throw $exc;
106 1
        } catch (\Exception $exc) {
107 1
            throw new ExecutionErrorException($exc->getMessage());
108
        }
109
    }
110
111
    /**
112
     * Runs the sql statement inserting the query's data
113
     * @param PDOStatement $stmt PDO statement of a prepared SQL statement
114
     * @param array $whereData data to be used to fill out a where statement
115
     * @return bool true query succeeds, false there was an error executing the query
116
     * @since v1.0.0
117
     */
118 9
    protected function statementExecute(PDOStatement $stmt, array $whereData)
119
    {
120 9
        if (count($whereData) > 0) {
121 4
            return $stmt->execute($whereData);
122
        }
123 5
        return $stmt->execute();
124
    }
125
126
    /**
127
     * Fetches the data from PDO resource
128
     * @param PDOStatement $stmt PDO statement of a prepared SQL statement
129
     * @param bool $fetchFlat true returns one record, false returns all records
130
     * @param integer $fetchStyle a \PDO::FETCH_* variable defining the format of
131
     * the returned object
132
     * @return array returns the results of the query
133
     * @since v1.0.0
134
     */
135 8
    protected function fetchData(PDOStatement $stmt, $fetchFlat, $fetchStyle)
136
    {
137 8
        if ($fetchFlat) {
138 4
            return $stmt->fetch($fetchStyle);
139
        }
140 4
        return $stmt->fetchAll($fetchStyle);
141
    }
142
143
    /**
144
     * returns a PDO SQL string that has parameter syntax
145
     * @return string
146
     * @since v1.0.0
147
     */
148 11
    public function getSql()
149
    {
150 11
        $sqlTemplate = "SELECT %s FROM %s %s";
151 11
        $fieldsCompiled = implode(',', $this->getFields());
152 11
        return trim(sprintf(
153 11
            $sqlTemplate,
154 11
            $fieldsCompiled,
155 11
            $this->getTable(),
156 11
            $this->getWhereStatement()
157
        ));
158
    }
159
160
    /**
161
     * acts as a cache to house ran queries
162
     * @param mixed $data data to be stored
163
     * @return Select for method chaining
164
     * @since v1.0.0
165
     */
166 9
    public function setData($data)
167
    {
168 9
        $this->data = $data;
169 9
        return $this;
170
    }
171
172
    /**
173
     * Acts as a cache array that holds the data returned from a query
174
     * @return mixed
175
     * @since v1.0.0
176
     */
177 9
    public function getData()
178
    {
179 9
        return $this->data;
180
    }
181
182
    /**
183
     * retrieves the table with which you wish to select from
184
     * @return string  table with which you wish to select from
185
     * @since v1.0.0
186
     */
187 13
    public function getTable()
188
    {
189 13
        return $this->table;
190
    }
191
192
    /**
193
     * defines a table with which you wish to append to
194
     * @param string $table a table with which you wish to append to
195
     * @return Select for method chaining
196
     * @since v1.0.0
197
     */
198 23
    public function setTable($table)
199
    {
200 23
        $this->table = $table;
201 23
        return $this;
202
    }
203
204
    /**
205
     * Returns the fields to be returned, if no fields defined all fields are returned
206
     * @return array
207
     * @since v1.0.0
208
     */
209 15
    public function getFields()
210
    {
211 15
        return $this->fields;
212
    }
213
214
    /**
215
     * Defines the fields to be returned, if no fields defined all fields are returned
216
     * @param null|array $fields
217
     * @return Select for method chaining
218
     * @since v1.0.0
219
     */
220 23
    public function setFields(array $fields = null)
221
    {
222 23
        $this->fields = $fields ?: ["*"];
223 23
        return $this;
224
    }
225
226
    /**
227
     * defines how data is returned
228
     * @return  int $fetchStyle one of the PDO::FETCH_*
229
     * @since v1.0.0
230
     */
231 10
    public function getFetchStyle()
232
    {
233 10
        return $this->fetchStyle;
234
    }
235
236
    /**
237
     * used to define how data is returned
238
     * @param int $fetchStyle one of the PDO::FETCH_*
239
     * @return Select for method chaining
240
     * @since v1.0.0
241
     */
242 23
    public function setFetchStyle($fetchStyle)
243
    {
244 23
        $this->fetchStyle = $fetchStyle;
245 23
        return $this;
246
    }
247
248
    /**
249
     * sets if one or many records will be returned.
250
     * @return bool true for one record, false for all records
251
     * @since v1.0.0
252
     */
253 9
    public function getFetchFlat()
254
    {
255 9
        return $this->fetchFlat;
256
    }
257
258
    /**
259
     * sets if one or many records will be returned.
260
     * @param boolean $fetchFlat optional default value: false - true will
261
     * return one record, false will return all records
262
     * @return Select for method chaining
263
     * @since v1.0.0
264
     */
265 23
    public function setFetchFlat($fetchFlat = true)
266
    {
267 23
        $this->fetchFlat = $fetchFlat;
268 23
        return $this;
269
    }
270
271
    /**
272
     * Value to be returned if no data is found or query fails
273
     * @return mixed return the value used when the query returns false
274
     * @since v1.0.0
275
     */
276 5
    public function getDefaultValue()
277
    {
278 5
        return $this->defaultValue;
279
    }
280
281
    /**
282
     * Value to be returned if no data is found or query fails
283
     * @param array $defaultValue optional default value: empty array - value to
284
     * be returned on query failure
285
     * @return Select for method chaining
286
     * @since v1.0.0
287
     */
288 23
    public function setDefaultValue($defaultValue = [])
289
    {
290 23
        $this->defaultValue = $defaultValue;
291 23
        return $this;
292
    }
293
}
294