Completed
Branch master (6f5620)
by Anton
02:08
created

Table::readSet()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 38
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 4.1643

Importance

Changes 0
Metric Value
cc 4
eloc 24
nc 3
nop 4
dl 0
loc 38
ccs 18
cts 23
cp 0.7826
crap 4.1643
rs 8.5806
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
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 self
39
     */
40 12
    public function setTable(Db\Table $table)
41
    {
42 12
        $this->table = $table;
43 12
        return $this;
44
    }
45
46
    /**
47
     * Return table instance for manipulation
48
     *
49
     * @return Db\Table
50
     * @throws ApplicationException
51
     */
52 18
    public function getTable()
53
    {
54 18
        if (!$this->table) {
55 1
            $crudClass = static::class;
56 1
            $tableClass = substr($crudClass, 0, strrpos($crudClass, '\\', 1) + 1) . 'Table';
57
58
            // check class initialization
59 1
            if (!class_exists($tableClass) || !is_subclass_of($tableClass, '\\Bluz\\Db\\Table')) {
60 1
                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 17
        return $this->table;
71
    }
72
73
    /**
74
     * Get primary key
75
     *
76
     * @return array
77
     */
78 9
    public function getPrimaryKey()
79
    {
80 9
        return $this->getTable()->getPrimaryKey();
81
    }
82
83
    /**
84
     * Get record from Db or create new object
85
     *
86
     * @param  mixed $primary
87
     *
88
     * @return Row
89
     * @throws NotFoundException
90
     */
91 3
    public function readOne($primary)
92
    {
93 3
        if (!$primary) {
94 1
            return $this->getTable()->create();
95
        }
96
97 2
        $row = $this->getTable()->findRow($primary);
98
99 2
        if (!$row) {
100 1
            throw new NotFoundException('Record not found');
101
        }
102
103 1
        return $row;
104
    }
105
106
    /**
107
     * Get set of records
108
     *
109
     * @param int   $offset
110
     * @param int   $limit
111
     * @param array $params
112
     * @param int   $total
113
     *
114
     * @return array|int|mixed
115
     * @throws ApplicationException
116
     */
117 1
    public function readSet($offset = 0, $limit = 10, $params = [], &$total = null)
118
    {
119 1
        $select = $this->getTable()->select();
120
121
        // switch statement for DB type
122 1
        $type = Proxy\Db::getOption('connect', 'type');
123
        switch ($type) {
124 1
            case 'mysql':
125 1
                $selectPart = $select->getQueryPart('select');
126 1
                $selectPart = 'SQL_CALC_FOUND_ROWS ' . current($selectPart);
127 1
                $select->select($selectPart);
128 1
                $totalSQL = 'SELECT FOUND_ROWS()';
129 1
                break;
130
            case 'pgsql':
131
            default:
132
                $selectTotal = clone $select;
133
                $selectTotal->select('COUNT(*)');
134
                $totalSQL = $selectTotal->getSql();
135
                break;
136
        }
137
138 1
        $select->setLimit($limit);
139 1
        $select->setOffset($offset);
140
141
        // run queries
142
        // use transaction to avoid errors
143 1
        Proxy\Db::transaction(
144 1
            function () use (&$result, &$total, $select, $totalSQL) {
145 1
                $result = $select->execute();
146
147 1
                if (!is_null($total)) {
148 1
                    $total = Proxy\Db::fetchOne($totalSQL);
149
                }
150 1
            }
151
        );
152
153 1
        return $result;
154
    }
155
156
    /**
157
     * Create item
158
     *
159
     * @param  array $data
160
     *
161
     * @return integer
162
     */
163 1
    public function createOne($data)
164
    {
165 1
        $row = $this->getTable()->create();
166 1
        $row->setFromArray($data);
167 1
        return $row->save();
168
    }
169
170
    /**
171
     * Update item
172
     *
173
     * @param  mixed $primary
174
     * @param  array $data
175
     *
176
     * @return integer
177
     * @throws NotFoundException
178
     */
179 2
    public function updateOne($primary, $data)
180
    {
181 2
        $row = $this->getTable()->findRow($primary);
182
183 2
        if (!$row) {
184 1
            throw new NotFoundException('Record not found');
185
        }
186
187 1
        $row->setFromArray($data);
188 1
        return $row->save();
189
    }
190
191
    /**
192
     * Delete item
193
     *
194
     * @param  mixed $primary
195
     *
196
     * @return integer
197
     * @throws NotFoundException
198
     */
199 2
    public function deleteOne($primary)
200
    {
201 2
        $row = $this->getTable()->findRow($primary);
202
203 2
        if (!$row) {
204 1
            throw new NotFoundException('Record not found');
205
        }
206 1
        return $row->delete();
207
    }
208
}
209