Completed
Push — master ( e47c19...3aaaf2 )
by Anton
15s queued 13s
created

Table   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 159
Duplicated Lines 0 %

Test Coverage

Coverage 91.53%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 13
eloc 55
c 1
b 0
f 0
dl 0
loc 159
ccs 54
cts 59
cp 0.9153
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A readSet() 0 50 4
A deleteOne() 0 8 2
A createOne() 0 8 1
A updateOne() 0 11 2
A readOne() 0 13 3
A getPrimaryKey() 0 3 1
1
<?php
2
3
/**
4
 * Bluz Framework Component
5
 *
6
 * @copyright Bluz PHP Team
7
 * @link      https://github.com/bluzphp/framework
8
 */
9
10
declare(strict_types=1);
11
12
namespace Bluz\Crud;
13
14
use Bluz\Application\Exception\ApplicationException;
15
use Bluz\Db\Exception\InvalidPrimaryKeyException;
16
use Bluz\Db\Exception\TableNotFoundException;
17
use Bluz\Http\Exception\NotFoundException;
18
use Bluz\Db;
19
use Bluz\Proxy;
20
21
/**
22
 * Crud Table
23
 *
24
 * @package  Bluz\Crud
25
 * @author   AntonShevchuk
26
 * @link     https://github.com/bluzphp/framework/wiki/Crud-Table
27
 */
28
class Table extends AbstractCrud
29
{
30
    use Db\Traits\TableProperty;
31
32
    /**
33
     * {@inheritdoc}
34
     *
35
     * @throws InvalidPrimaryKeyException
36
     * @throws TableNotFoundException
37
     */
38 26
    public function getPrimaryKey(): array
39
    {
40 26
        return $this->getTable()->getPrimaryKey();
41
    }
42
43
    /**
44
     * Get record from Db or create new object
45
     *
46
     * @param  mixed $primary
47
     *
48
     * @return Db\RowInterface
49
     * @throws TableNotFoundException
50
     * @throws NotFoundException
51
     */
52 4
    public function readOne($primary)
53
    {
54 4
        if (!$primary) {
55 1
            return $this->getTable()::create();
56
        }
57
58 3
        $row = $this->getTable()::findRow($primary);
59
60 3
        if (!$row) {
61 1
            throw new NotFoundException('Record not found');
62
        }
63
64 2
        return $this->filterRow($row);
65
    }
66
67
    /**
68
     * Get set of records
69
     *
70
     * @param int $offset
71
     * @param int $limit
72
     * @param array $params
73
     *
74
     * @return array[Row[], integer]
0 ignored issues
show
Documentation Bug introduced by
The doc comment array[Row[], integer] at position 1 could not be parsed: Expected ']' at position 1, but found '['.
Loading history...
75
     * @throws TableNotFoundException
76
     */
77 2
    public function readSet(int $offset = 0, int $limit = 10, array $params = [])
78
    {
79 2
        $select = $this->getTable()::select();
80
81
        // select only required fields
82 2
        if (count($this->getFields())) {
83 2
            $fields = $this->getFields();
84 2
            $name = $this->getTable()->getName();
85 2
            $fields = array_map(
86 2
                function ($field) use ($name) {
87 2
                    return $name . '.' . $field;
88 2
                },
89
                $fields
90
            );
91 2
            $select->select(implode(', ', $fields));
92
        }
93
94
        // switch statement for DB type
95 2
        $type = Proxy\Db::getOption('connect', 'type');
96 2
        switch ($type) {
97 2
            case 'mysql':
98 2
                $selectPart = $select->getSelect();
99 2
                $selectPart[0] = 'SQL_CALC_FOUND_ROWS ' . $selectPart[0];
0 ignored issues
show
Bug introduced by
Are you sure $selectPart[0] of type array can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

99
                $selectPart[0] = 'SQL_CALC_FOUND_ROWS ' . /** @scrutinizer ignore-type */ $selectPart[0];
Loading history...
100 2
                $select->select(...$selectPart);
0 ignored issues
show
Bug introduced by
$selectPart of type array is incompatible with the type string expected by parameter $select of Bluz\Db\Query\Select::select(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

100
                $select->select(/** @scrutinizer ignore-type */ ...$selectPart);
Loading history...
101 2
                $totalSQL = 'SELECT FOUND_ROWS()';
102 2
                break;
103
            case 'pgsql':
104
            default:
105
                $selectTotal = clone $select;
106
                $selectTotal->select('COUNT(*)');
107
                $totalSQL = $selectTotal->getSql();
108
                break;
109
        }
110
111 2
        $select->setLimit($limit);
112 2
        $select->setOffset($offset);
113
114 2
        $result = [];
115 2
        $total = 0;
116
117
        // run queries
118
        // use transaction to avoid errors
119 2
        Proxy\Db::transaction(
120 2
            function () use (&$result, &$total, $select, $totalSQL) {
121 2
                $result = $select->execute();
122 2
                $total = Proxy\Db::fetchOne($totalSQL);
123 2
            }
124
        );
125
126 2
        return [$result, $total];
127
    }
128
129
    /**
130
     * Create item
131
     *
132
     * @param array $data
133
     *
134
     * @return mixed
135
     * @throws TableNotFoundException
136
     */
137 1
    public function createOne(array $data)
138
    {
139 1
        $row = $this->getTable()::create();
140
141 1
        $data = $this->filterData($data);
142
143 1
        $row->setFromArray($data);
144 1
        return $row->save();
145
    }
146
147
    /**
148
     * Update item
149
     *
150
     * @param  mixed $primary
151
     * @param array $data
152
     *
153
     * @return integer
154
     * @throws NotFoundException
155
     * @throws TableNotFoundException
156
     */
157 2
    public function updateOne($primary, array $data)
158
    {
159 2
        $row = $this->getTable()::findRow($primary);
160
161 2
        if (!$row) {
162 1
            throw new NotFoundException('Record not found');
163
        }
164 1
        $data = $this->filterData($data);
165
166 1
        $row->setFromArray($data);
167 1
        return $row->save();
168
    }
169
170
    /**
171
     * Delete item
172
     *
173
     * @param  mixed $primary
174
     *
175
     * @return integer
176
     * @throws NotFoundException
177
     * @throws TableNotFoundException
178
     */
179 2
    public function deleteOne($primary)
180
    {
181 2
        $row = $this->getTable()::findRow($primary);
182
183 2
        if (!$row) {
184 1
            throw new NotFoundException('Record not found');
185
        }
186 1
        return $row->delete();
187
    }
188
}
189