Completed
Pull Request — master (#409)
by Anton
06:23
created

Table::getPrimaryKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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