Passed
Push — master ( ecaff5...98df6c )
by Joao
13:38 queued 15s
created

BaseRepository::model()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace RestTemplate\Repository;
4
5
use ByJG\AnyDataset\Db\DbDriverInterface;
6
use ByJG\MicroOrm\Exception\OrmBeforeInvalidException;
7
use ByJG\MicroOrm\Exception\OrmInvalidFieldsException;
8
use ByJG\MicroOrm\FieldMapping;
9
use ByJG\MicroOrm\Literal;
10
use ByJG\MicroOrm\Mapper;
11
use ByJG\MicroOrm\Query;
12
use ByJG\MicroOrm\Repository;
13
use ByJG\Serializer\Exception\InvalidArgumentException;
14
use RestTemplate\Psr11;
15
use RestTemplate\Util\HexUuidLiteral;
16
17
abstract class BaseRepository
18
{
19
    /**
20
     * @var Repository
21
     */
22
    protected $repository;
23
24
    /**
25
     * @param $itemId
26
     * @return mixed
27
     * @throws \ByJG\MicroOrm\Exception\InvalidArgumentException
28
     * @throws InvalidArgumentException
29
     */
30
    public function get($itemId)
31
    {
32
        return $this->repository->get($this->prepareUuidQuery($itemId));
33
    }
34
35
    protected function prepareUuidQuery($itemId)
36
    {
37
        $result = [];
38
        foreach ((array)$itemId as $item) {
39
            if (!($item instanceof Literal) && preg_match("/^\w{8}-?\w{4}-?\w{4}-?\w{4}-?\w{12}$/", $item)) {
40
                $result[] = new HexUuidLiteral($item);
41
            } else {
42
                $result[] = $item;
43
            }
44
        }
45
46
        if (count($result) == 1) {
47
            return $result[0];
48
        }
49
        return $result;
50
    }
51
52
    /**
53
     * @param int|null $page
54
     * @param int $size
55
     * @param null $orderBy
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $orderBy is correct as it would always require null to be passed?
Loading history...
56
     * @param null $filter
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $filter is correct as it would always require null to be passed?
Loading history...
57
     * @return array
58
     * @throws \ByJG\MicroOrm\Exception\InvalidArgumentException
59
     * @throws InvalidArgumentException
60
     */
61
    public function list($page = 0, $size = 20, $orderBy = null, $filter = null)
62
    {
63
        if (empty($page)) {
64
            $page = 0;
65
        }
66
67
        if (empty($size)) {
68
            $size = 20;
69
        }
70
71
        $query = Query::getInstance()
72
            ->table($this->repository->getMapper()->getTable())
73
            ->limit($page*$size, $size);
74
75
        if (!empty($orderBy)) {
76
            if (!is_array($orderBy)) {
77
                $orderBy = [$orderBy];
78
            }
79
            $query->orderBy($orderBy);
80
        }
81
82
        foreach ((array)$filter as $item) {
83
            $query->where($item[0], $item[1]);
84
        }
85
86
        return $this->repository
87
            ->getByQuery($query);
88
    }
89
90
    public function listGeneric($tableName, $page = 0, $size = 20, $orderBy = null, $filter = null)
91
    {
92
        if (empty($page)) {
93
            $page = 0;
94
        }
95
96
        if (empty($size)) {
97
            $size = 20;
98
        }
99
100
        $query = Query::getInstance()
101
            ->table($tableName)
102
            ->limit($page*$size, $size);
103
104
        if (!empty($orderBy)) {
105
            if (!is_array($orderBy)) {
106
                $orderBy = [$orderBy];
107
            }
108
            $query->orderBy($orderBy);
109
        }
110
111
        foreach ((array)$filter as $item) {
112
            $query->where($item[0], $item[1]);
113
        }
114
115
        $object = $query->build($this->repository->getDbDriver());
116
117
        $iterator = $this->repository->getDbDriver()->getIterator($object["sql"], $object["params"]);
118
        return $iterator->toArray();
119
    }
120
121
    public function model()
122
    {
123
        $class = $this->repository->getMapper()->getEntity();
124
125
        return new $class();
126
    }
127
128
    protected function getClosureNewUUID()
129
    {
130
        return new Literal("X'" . $this->repository->getDbDriver()->getScalar("SELECT hex(uuid_to_bin(uuid()))") . "'");
131
    }
132
133
    public static function getUuid()
134
    {
135
        return Psr11::container()->get(DbDriverInterface::class)->getScalar("SELECT insert(insert(insert(insert(hex(uuid_to_bin(uuid())),9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-')");
136
    }
137
138
    /**
139
     * @param Mapper $mapper
140
     * @param string $pkFieldName
141
     * @param string $modelField
142
     * @return void
143
     */
144
    protected function setClosureFixBinaryUUID($mapper, $pkFieldName = 'id', $modelField = 'uuid')
145
    {
146
        $mapper->addFieldMapping(FieldMapping::create($pkFieldName)
147
            ->withUpdateFunction(function ($value, $instance) {
148
                if (empty($value)) {
149
                    return null;
150
                }
151
                if (!($value instanceof Literal)) {
152
                    $value = new HexUuidLiteral($value);
153
                }
154
                return $value;
155
            })
156
            ->withSelectFunction(function ($value, $instance) use ($modelField) {
157
                return str_replace('-', '', $instance->{'get' . $modelField}());
158
            })
159
        );
160
    }
161
162
    /**
163
     * @param $model
164
     * @throws \ByJG\MicroOrm\Exception\InvalidArgumentException
165
     * @throws OrmBeforeInvalidException
166
     * @throws OrmInvalidFieldsException
167
     * @throws InvalidArgumentException
168
     */
169
    public function save($model)
170
    {
171
        $model = $this->repository->save($model);
172
173
        $primaryKey = $this->repository->getMapper()->getPrimaryKey()[0];
174
175
        if ($model->{"get$primaryKey"}() instanceof Literal) {
176
            $model->{"set$primaryKey"}(HexUuidLiteral::getUuidFromLiteral($model->{"get$primaryKey"}()));
177
        }
178
179
        return $model;
180
    }
181
}
182