Completed
Pull Request — master (#451)
by Anton
11:31
created

Table   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 160
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 78.95%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 160
ccs 45
cts 57
cp 0.7895
rs 10
c 1
b 0
f 0
wmc 13
lcom 1
cbo 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getPrimaryKey() 0 4 1
A readOne() 0 16 3
B readSet() 0 51 4
A createOne() 0 9 1
A updateOne() 0 13 2
A deleteOne() 0 9 2
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
    use Db\Traits\TableProperty;
29
30
    /**
31
     * {@inheritdoc}
32
     *
33
     * @throws \Bluz\Db\Exception\InvalidPrimaryKeyException
34
     */
35
    public function getPrimaryKey() : array
36
    {
37
        return $this->getTable()->getPrimaryKey();
38
    }
39
40
    /**
41 37
     * Get record from Db or create new object
42
     *
43 37
     * @param  mixed $primary
44 37
     *
45
     * @return Db\RowInterface
46
     * @throws \Bluz\Db\Exception\TableNotFoundException
47
     * @throws NotFoundException
48
     */
49
    public function readOne($primary)
50
    {
51
        if (!$primary) {
52 37
            return $this->getTable()::create();
53
        }
54 37
55
        $row = $this->getTable()::findRow($primary);
56
57 37
        if (!$row) {
58
            throw new NotFoundException('Record not found');
59
        }
60
61
        $row = $this->filterRow($row);
0 ignored issues
show
Compatibility introduced by
$row of type object<Bluz\Db\RowInterface> is not a sub-type of object<Bluz\Db\Row>. It seems like you assume a concrete implementation of the interface Bluz\Db\RowInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
62
63
        return $row;
64
    }
65
66
    /**
67
     * Get set of records
68
     *
69
     * @param int   $offset
70
     * @param int   $limit
71
     * @param array $params
72
     *
73
     * @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...
74
     * @throws ApplicationException
75
     */
76
    public function readSet($offset = 0, $limit = 10, $params = [])
77
    {
78
        $select = $this->getTable()::select();
79
80
        // select only required fields
81
        if (count($this->getFields())) {
82
            $fields = $this->getFields();
83
            $name = $this->getTable()->getName();
84
            $fields = array_map(
85
                function ($field) use ($name) {
86 26
                    return $name .'.'. $field;
87
                },
88 26
                $fields
89
            );
90
            $select->select(implode(', ', $fields));
91
        }
92
93
        // switch statement for DB type
94
        $type = Proxy\Db::getOption('connect', 'type');
95
        switch ($type) {
96
            case 'mysql':
97
                $selectPart = $select->getQueryPart('select');
98
                $selectPart = 'SQL_CALC_FOUND_ROWS ' . current($selectPart);
99 4
                $select->select($selectPart);
100
                $totalSQL = 'SELECT FOUND_ROWS()';
101 4
                break;
102 1
            case 'pgsql':
103
            default:
104
                $selectTotal = clone $select;
105 3
                $selectTotal->select('COUNT(*)');
106
                $totalSQL = $selectTotal->getSql();
107 3
                break;
108 1
        }
109
110
        $select->setLimit($limit);
111 2
        $select->setOffset($offset);
112
113 2
        $result = [];
114
        $total = 0;
115
116
        // run queries
117
        // use transaction to avoid errors
118
        Proxy\Db::transaction(
119
            function () use (&$result, &$total, $select, $totalSQL) {
120
                $result = $select->execute();
121
                $total = Proxy\Db::fetchOne($totalSQL);
122
            }
123
        );
124
125
        return [$result, $total];
126 2
    }
127
128 2
    /**
129
     * Create item
130
     *
131 2
     * @param  array $data
132 2
     *
133 2
     * @return mixed
134 2
     */
135 2
    public function createOne($data)
136 2
    {
137 2
        $row = $this->getTable()::create();
138 2
139
        $data = $this->filterData($data);
140 2
141
        $row->setFromArray($data);
142
        return $row->save();
143
    }
144 2
145
    /**
146 2
     * Update item
147 2
     *
148 2
     * @param  mixed $primary
149 2
     * @param  array $data
150 2
     *
151 2
     * @return integer
152
     * @throws NotFoundException
153
     */
154
    public function updateOne($primary, $data)
155
    {
156
        $row = $this->getTable()::findRow($primary);
157
158
        if (!$row) {
159
            throw new NotFoundException('Record not found');
160 2
        }
161 2
162
        $data = $this->filterData($data);
163 2
164 2
        $row->setFromArray($data);
165
        return $row->save();
166
    }
167
168 2
    /**
169 2
     * Delete item
170 2
     *
171 2
     * @param  mixed $primary
172 2
     *
173
     * @return integer
174
     * @throws NotFoundException
175 2
     */
176
    public function deleteOne($primary)
177
    {
178
        $row = $this->getTable()::findRow($primary);
179
180
        if (!$row) {
181
            throw new NotFoundException('Record not found');
182
        }
183
        return $row->delete();
184
    }
185
}
186