Update::getSql()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 13
cts 13
cp 1
rs 9.6666
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
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\EmptyDatasetException;
28
use DSchoenbauer\Sql\Exception\ExecutionErrorException;
29
use DSchoenbauer\Sql\Exception\NoRecordsAffectedException;
30
use DSchoenbauer\Sql\Exception\NoRecordsAffectedUpdateException;
31
use DSchoenbauer\Sql\Where\WhereStatementInterface;
32
use PDO;
33
34
/**
35
 * updates values in a PDO connected resource
36
 * @author David Schoenbauer <[email protected]>
37
 * @since v1.0.0
38
 */
39
class Update extends AbstractCommand
40
{
41
42
    private $table;
43
    private $data = [];
44
45
    use WhereTrait;
46
47
    /**
48
     * @param string $table table with which you wish to append to
49
     * @param array $data  a single level associative array containing keys that
50
     * represent the fields and values that represent new values to be added into
51
     * the table
52
     * @param null|WhereStatementInterface $where an object that is designed to return
53
     * a where statement to limit the data that is affected by the update
54
     * @since v1.0.0
55
     */
56 13
    public function __construct(
57
        $table,
58
        array $data,
59
        WhereStatementInterface $where = null
60
    ) {
61
    
62 13
        $this->setTable($table)->setData($data)->setWhere($where);
63 13
    }
64
65
    /**
66
     * takes the SQL and the data provided and executes the query with the data
67
     * @param PDO $pdo a connection object that defines where the connection is
68
     * to be executed
69
     * @return bool TRUE on success or FALSE on failure.
70
     * @throws NoRecordsAffectedException  if strict is set to true an exception will be thrown if
71
     * @throws EmptyDatasetException  if no data has been set no fields can be discerned and no query can be made
72
     * @throws ExecutionErrorException thrown when any exception or SQL failure occurs
73
     * @since v1.0.0
74
     */
75 4
    public function execute(PDO $pdo)
76
    {
77
        try {
78 4
            $stmt = $pdo->prepare($this->getSql());
79 3
            $result = $stmt->execute($this->getCombinedData());
80 2
            $this->checkAffected($stmt, new NoRecordsAffectedUpdateException());
81 1
            return $result;
82 3
        } catch (NoRecordsAffectedException $exc) {
83 1
            throw $exc;
84 2
        } catch (EmptyDatasetException $exc) {
85 1
            throw $exc;
86 1
        } catch (\Exception $exc) {
87 1
            throw new ExecutionErrorException($exc->getMessage());
88
        }
89
    }
90
91
    /**
92
     * Generates a SQL statement ready to be prepared for execution with the
93
     * intent of updating data
94
     * @return string a string that represents an update statement ready to be
95
     * prepared by PDO
96
     * @throws EmptyDatasetException if no data has been set no fields can be
97
     * discerned and no query can be made
98
     * @since v1.0.0
99
     */
100 7
    public function getSql()
101
    {
102 7
        if (count($this->getData()) === 0) {
103 2
            throw new EmptyDatasetException();
104
        }
105
106 5
        $sets = array_map(function ($value) {
107 5
            return sprintf('%1$s = :%1$s', $value);
108 5
        }, array_keys($this->getData()));
109 5
        $where = $this->getWhereStatement();
110 5
        $sqlTemplate = "UPDATE %s SET %s %s";
111 5
        return trim(sprintf(
112 5
            $sqlTemplate,
113 5
            $this->getTable(),
114 5
            implode(',', $sets),
115 5
            $where
116
        ));
117
    }
118
119
    /**
120
     * retrieves the table with which you wish to update
121
     * @return string  table with which you wish to update
122
     * @since v1.0.0
123
     */
124 7
    public function getTable()
125
    {
126 7
        return $this->table;
127
    }
128
129
    /**
130
     * defines a table with which you wish to update
131
     * @param string $table a table with which you wish to update
132
     * @return Update for method chaining
133
     * @since v1.0.0
134
     */
135 13
    public function setTable($table)
136
    {
137 13
        $this->table = $table;
138 13
        return $this;
139
    }
140
141
    /**
142
     * Returns a combination of data from Where statement and from this object
143
     * @return array
144
     * @since v1.0.0
145
     */
146 4
    public function getCombinedData()
147
    {
148 4
        $whereData = $this->getWhereData();
149 4
        return array_merge($this->getData(), $whereData);
150
    }
151
152
    /**
153
     * retrieves the data that is used to generate the update statement. The
154
     * fields of the array are used to generate the field list.
155
     * @return array a single level associative array containing keys that
156
     * represent the fields and values that represent new values to be updated in the table
157
     * @since v1.0.0
158
     */
159 10
    public function getData()
160
    {
161 10
        return $this->data;
162
    }
163
164
    /**
165
     * sets the data that is used to generate the update statement. The fields
166
     * of the array are used to generate the field list.
167
     * @param array $data a single level associative array containing keys that
168
     * represent the fields and values that represent values to be updated into the table
169
     * @return Update for method chaining
170
     * @since v1.0.0
171
     */
172 13
    public function setData($data)
173
    {
174 13
        $this->data = $data;
175 13
        return $this;
176
    }
177
}
178