Completed
Pull Request — master (#363)
by Anton
06:05
created

Table::updateOne()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 2
dl 0
loc 11
ccs 0
cts 9
cp 0
crap 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link https://github.com/bluzphp/framework
7
 */
8
9
/**
10
 * @namespace
11
 */
12
namespace Bluz\Crud;
13
14
use Bluz\Application\Exception\ApplicationException;
15
use Bluz\Application\Exception\NotFoundException;
16
use Bluz\Db;
17
use Bluz\Db\Row;
18
use Bluz\Proxy;
19
20
/**
21
 * Crud Table
22
 *
23
 * @package  Bluz\Crud
24
 * @author   AntonShevchuk
25
 * @link     https://github.com/bluzphp/framework/wiki/Crud-Table
26
 */
27
class Table extends AbstractCrud
28
{
29
    /**
30
     * @var \Bluz\Db\Table instance of Db\Table
31
     */
32
    protected $table;
33
34
    /**
35
     * Setup Table instance
36
     *
37
     * @param  Db\Table $table
38
     * @return self
39
     */
40
    public function setTable(Db\Table $table)
41
    {
42
        $this->table = $table;
43
        return $this;
44
    }
45
46
    /**
47
     * Return table instance for manipulation
48
     *
49
     * @return Db\Table
50
     * @throws ApplicationException
51
     */
52
    public function getTable()
53
    {
54
        if (!$this->table) {
55
            $crudClass = static::class;
56
            $tableClass = substr($crudClass, 0, strrpos($crudClass, '\\', 1) + 1) . 'Table';
57
58
            // check class initialization
59
            if (!class_exists($tableClass) || !is_subclass_of($tableClass, '\\Bluz\\Db\\Table')) {
60
                throw new ApplicationException("`Table` class is not exists or not initialized");
61
            }
62
63
            /**
64
             * @var Db\Table $tableClass
65
             */
66
            $table = $tableClass::getInstance();
67
68
            $this->setTable($table);
69
        }
70
        return $this->table;
71
    }
72
73
    /**
74
     * Get primary key
75
     *
76
     * @return array
77
     */
78
    public function getPrimaryKey()
79
    {
80
        return $this->getTable()->getPrimaryKey();
81
    }
82
83
    /**
84
     * Get record from Db or create new object
85
     *
86
     * @param  mixed $primary
87
     * @return Row
88
     * @throws NotFoundException
89
     */
90
    public function readOne($primary)
91
    {
92
        if (!$primary) {
93
            return $this->getTable()->create();
94
        }
95
96
        $row = $this->getTable()->findRow($primary);
97
98
        if (!$row) {
99
            throw new NotFoundException("Record not found");
100
        }
101
102
        return $row;
103
    }
104
105
    /**
106
     * Get set of records
107
     *
108
     * @param int $offset
109
     * @param int $limit
110
     * @param array $params
111
     * @param int $total
112
     * @return array|int|mixed
113
     * @throws ApplicationException
114
     */
115
    public function readSet($offset = 0, $limit = 10, $params = array(), &$total = null)
116
    {
117
        $select = $this->getTable()->select();
118
119
        // switch statement for DB type
120
        $type = Proxy\Db::getOption('connect', 'type');
121
        switch ($type) {
122
            case 'mysql':
123
                $selectPart = $select->getQueryPart('select');
124
                $selectPart = 'SQL_CALC_FOUND_ROWS ' . current($selectPart);
125
                $select->select($selectPart);
126
                $totalSQL = 'SELECT FOUND_ROWS()';
127
                break;
128
            case 'pgsql':
129
            default:
130
                $selectTotal = clone $select;
131
                $selectTotal->select('COUNT(*)');
132
                $totalSQL = $selectTotal->getSql();
133
                break;
134
        }
135
136
        $select->setLimit($limit);
137
        $select->setOffset($offset);
138
139
        // run queries
140
        // use transaction to avoid errors
141
        Proxy\Db::transaction(function() use (&$result, &$total, $select, $totalSQL) {
142
            $result = $select->execute();
143
144
            if (!is_null($total)) {
145
                $total = Proxy\Db::fetchOne($totalSQL);
146
            }
147
        });
148
149
        return $result;
150
    }
151
152
    /**
153
     * Create item
154
     *
155
     * @param  array $data
156
     * @return integer
157
     */
158
    public function createOne($data)
159
    {
160
        $row = $this->getTable()->create();
161
        $row->setFromArray($data);
162
        return $row->save();
163
    }
164
165
    /**
166
     * Update item
167
     *
168
     * @param  mixed $primary
169
     * @param  array $data
170
     * @return integer
171
     * @throws NotFoundException
172
     */
173
    public function updateOne($primary, $data)
174
    {
175
        $row = $this->getTable()->findRow($primary);
176
177
        if (!$row) {
178
            throw new NotFoundException("Record not found");
179
        }
180
181
        $row->setFromArray($data);
182
        return $row->save();
183
    }
184
185
    /**
186
     * Delete item
187
     *
188
     * @param  mixed $primary
189
     * @return integer
190
     * @throws NotFoundException
191
     */
192
    public function deleteOne($primary)
193
    {
194
        $row = $this->getTable()->findRow($primary);
195
196
        if (!$row) {
197
            throw new NotFoundException("Record not found");
198
        }
199
        return $row->delete();
200
    }
201
}
202