Completed
Push — master ( 467d47...6f2bb4 )
by Anton
14s
created

Table   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 163
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 91.67%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 163
ccs 55
cts 60
cp 0.9167
c 1
b 0
f 0
rs 10
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 12 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\Db\Exception\InvalidPrimaryKeyException;
15
use Bluz\Db\Exception\TableNotFoundException;
16
use Bluz\Http\Exception\NotFoundException;
17
use Bluz\Db;
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
    use Db\Traits\TableProperty;
30
31
    /**
32
     * {@inheritdoc}
33
     *
34
     * @throws InvalidPrimaryKeyException
35
     * @throws TableNotFoundException
36
     */
37 26
    public function getPrimaryKey() : array
38
    {
39 26
        return $this->getTable()->getPrimaryKey();
40
    }
41
42
    /**
43
     * Get record from Db or create new object
44
     *
45
     * @param  mixed $primary
46
     *
47
     * @return Db\RowInterface
48
     * @throws TableNotFoundException
49
     * @throws NotFoundException
50
     */
51 4
    public function readOne($primary)
52
    {
53 4
        if (!$primary) {
54 1
            return $this->getTable()::create();
55
        }
56
57 3
        $row = $this->getTable()::findRow($primary);
58
59 3
        if (!$row) {
60 1
            throw new NotFoundException('Record not found');
61
        }
62
63 2
        $row = $this->filterRow($row);
64
65 2
        return $row;
66
    }
67
68
    /**
69
     * Get set of records
70
     *
71
     * @param int   $offset
72
     * @param int   $limit
73
     * @param array $params
74
     *
75
     * @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...
76
     * @throws ApplicationException
77
     */
78 2
    public function readSet($offset = 0, $limit = 10, $params = [])
79
    {
80 2
        $select = $this->getTable()::select();
81
82
        // select only required fields
83 2
        if (count($this->getFields())) {
84 2
            $fields = $this->getFields();
85 2
            $name = $this->getTable()->getName();
86 2
            $fields = array_map(
87 2
                function ($field) use ($name) {
88 2
                    return $name .'.'. $field;
89 2
                },
90 2
                $fields
91
            );
92 2
            $select->select(implode(', ', $fields));
93
        }
94
95
        // switch statement for DB type
96 2
        $type = Proxy\Db::getOption('connect', 'type');
97
        switch ($type) {
98 2
            case 'mysql':
99 2
                $selectPart = $select->getSelect();
100 2
                $selectPart[0] = 'SQL_CALC_FOUND_ROWS ' . $selectPart[0];
101 2
                $select->select(...$selectPart);
102 2
                $totalSQL = 'SELECT FOUND_ROWS()';
103 2
                break;
104
            case 'pgsql':
105
            default:
106
                $selectTotal = clone $select;
107
                $selectTotal->select('COUNT(*)');
108
                $totalSQL = $selectTotal->getSql();
109
                break;
110
        }
111
112 2
        $select->setLimit($limit);
113 2
        $select->setOffset($offset);
114
115 2
        $result = [];
116 2
        $total = 0;
117
118
        // run queries
119
        // use transaction to avoid errors
120 2
        Proxy\Db::transaction(
121 2
            function () use (&$result, &$total, $select, $totalSQL) {
122 2
                $result = $select->execute();
123 2
                $total = Proxy\Db::fetchOne($totalSQL);
124 2
            }
125
        );
126
127 2
        return [$result, $total];
128
    }
129
130
    /**
131
     * Create item
132
     *
133
     * @param  array $data
134
     *
135
     * @return mixed
136
     * @throws TableNotFoundException
137
     */
138 1
    public function createOne($data)
139
    {
140 1
        $row = $this->getTable()::create();
141
142 1
        $data = $this->filterData($data);
143
144 1
        $row->setFromArray($data);
145 1
        return $row->save();
146
    }
147
148
    /**
149
     * Update item
150
     *
151
     * @param  mixed $primary
152
     * @param  array $data
153
     *
154
     * @return integer
155
     * @throws NotFoundException
156
     * @throws TableNotFoundException
157
     */
158 2
    public function updateOne($primary, $data)
159
    {
160 2
        $row = $this->getTable()::findRow($primary);
161
162 2
        if (!$row) {
163 1
            throw new NotFoundException('Record not found');
164
        }
165 1
        $data = $this->filterData($data);
166
167 1
        $row->setFromArray($data);
168 1
        return $row->save();
169
    }
170
171
    /**
172
     * Delete item
173
     *
174
     * @param  mixed $primary
175
     *
176
     * @return integer
177
     * @throws NotFoundException
178
     * @throws TableNotFoundException
179
     */
180 2
    public function deleteOne($primary)
181
    {
182 2
        $row = $this->getTable()::findRow($primary);
183
184 2
        if (!$row) {
185 1
            throw new NotFoundException('Record not found');
186
        }
187 1
        return $row->delete();
188
    }
189
}
190