Completed
Push — master ( d292ba...467d47 )
by Anton
15s
created

Table::setTable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
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\Common\Singleton;
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
     *
39
     * @return void
40
     */
41 37
    public function setTable(Db\Table $table)
42
    {
43 37
        $this->table = $table;
44 37
    }
45
46
    /**
47
     * Return table instance for manipulation
48
     *
49
     * @return Db\Table
50
     * @throws ApplicationException
51
     */
52 37
    public function getTable()
53
    {
54 37
        if (!$this->table) {
55
            $this->initTable();
56
        }
57 37
        return $this->table;
58
    }
59
60
    /**
61
     * Init table instance for manipulation
62
     *
63
     * @return void
64
     * @throws ApplicationException
65
     */
66
    protected function initTable()
67
    {
68
        $tableClass = class_namespace(static::class) . '\\Table';
69
70
        // check class initialization
71
        if (!class_exists($tableClass) || !is_subclass_of($tableClass, Db\Table::class)) {
72
            throw new ApplicationException('`Table` class is not exists or not initialized');
73
        }
74
75
        /**
76
         * @var Db\Table $tableClass
77
         */
78
        $this->setTable($tableClass::getInstance());
79
    }
80
81
    /**
82
     * Get primary key
83
     *
84
     * @return array
85
     */
86 26
    public function getPrimaryKey()
87
    {
88 26
        return $this->getTable()->getPrimaryKey();
89
    }
90
91
    /**
92
     * Get record from Db or create new object
93
     *
94
     * @param  mixed $primary
95
     *
96
     * @return Row
97
     * @throws NotFoundException
98
     */
99 4
    public function readOne($primary)
100
    {
101 4
        if (!$primary) {
102 1
            return $this->getTable()::create();
103
        }
104
105 3
        $row = $this->getTable()::findRow($primary);
106
107 3
        if (!$row) {
108 1
            throw new NotFoundException('Record not found');
109
        }
110
111 2
        $row = $this->filterRow($row);
112
113 2
        return $row;
114
    }
115
116
    /**
117
     * Get set of records
118
     *
119
     * @param int   $offset
120
     * @param int   $limit
121
     * @param array $params
122
     *
123
     * @return array[Row[], integer]
0 ignored issues
show
Documentation introduced by
The doc-type array[Row[], could not be parsed: Expected "]" at position 2, but found "Row". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
124
     * @throws ApplicationException
125
     */
126 2
    public function readSet($offset = 0, $limit = 10, $params = [])
127
    {
128 2
        $select = $this->getTable()::select();
129
130
        // select only required fields
131 2
        if (count($this->getFields())) {
132 2
            $fields = $this->getFields();
133 2
            $name = $this->getTable()->getName();
134 2
            $fields = array_map(
135 2
                function ($field) use ($name) {
136 2
                    return $name .'.'. $field;
137 2
                },
138 2
                $fields
139
            );
140 2
            $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 2
        $result = [];
164 2
        $total = 0;
165
166
        // run queries
167
        // use transaction to avoid errors
168 2
        Proxy\Db::transaction(
169 2
            function () use (&$result, &$total, $select, $totalSQL) {
170 2
                $result = $select->execute();
171 2
                $total = Proxy\Db::fetchOne($totalSQL);
172 2
            }
173
        );
174
175 2
        return [$result, $total];
176
    }
177
178
    /**
179
     * Create item
180
     *
181
     * @param  array $data
182
     *
183
     * @return mixed
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