Completed
Pull Request — master (#437)
by Anton
04:37
created

Table::readSet()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 51
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 5.0952

Importance

Changes 0
Metric Value
cc 5
eloc 32
nc 6
nop 4
dl 0
loc 51
ccs 27
cts 32
cp 0.8438
crap 5.0952
rs 8.6588
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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