Passed
Push — master ( 57eb13...500eb5 )
by Aleksandr
34:06
created

EntityGnome::toArrayByGroup()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 17
c 0
b 0
f 0
nc 3
nop 0
dl 0
loc 23
ccs 6
cts 6
cp 1
crap 3
rs 9.7
1
<?php
2
/**
3
 * This file is part of the eav package.
4
 *
5
 * @author    Alex Kuperwood <[email protected]>
6
 * @copyright 2025 Alex Kuperwood
7
 * @license   https://opensource.org/license/mit  The MIT License
8
 */
9
declare(strict_types=1);
10
11
namespace Kuperwood\Eav;
12
13
use Kuperwood\Eav\Enum\_ENTITY;
14
use Kuperwood\Eav\Enum\_GROUP;
15
use Kuperwood\Eav\Exception\EntityException;
16
use Kuperwood\Eav\Model\AttributeGroupModel;
17
use Kuperwood\Eav\Result\Result;
18
use Kuperwood\Eav\Traits\SingletonsTrait;
19
20
class EntityGnome
21
{
22
    use SingletonsTrait;
23
24
    private Entity $entity;
25 1
26
    public function __construct(Entity $entity)
27 1
    {
28
        $this->entity = $entity;
29
    }
30 1
31
    public function getEntity(): Entity
32 1
    {
33
        return $this->entity;
34
    }
35
36
    /**
37
     * @throws EntityException
38
     * @throws Exception
39 10
     */
40
    public function beforeSave(): int
41 10
    {
42 10
        $entity = $this->getEntity();
43 10
        $set = $entity->getAttributeSet();
44 6
        if (!$entity->hasKey()) {
45 1
            if (!$entity->hasDomainKey()) {
46
                EntityException::undefinedDomainKey();
47 5
            }
48 1
            if (!$set->hasKey()) {
49
                EntityException::undefinedAttributeSetKey();
50 4
            }
51 4
            $domainKey = $entity->getDomainKey();
52 3
            $this->checkDomainExists($domainKey);
53 3
            $setKey = $set->getKey();
54 2
            $this->checkAttrSetExist($setKey);
55 2
            $model = $this->makeEntityModel();
56 2
            $key = $model->create([
57 2
                _ENTITY::DOMAIN_ID => $domainKey,
58 2
                _ENTITY::ATTR_SET_ID => $setKey
59 2
            ]);
60
            $entity->setKey($key);
61 2
62
            return 1;
63 4
        }
64 4
        $key = $entity->getKey();
65 3
        $record = $this->checkEntityExists($key);
66 3
        $domainKey = (int) $record[_ENTITY::DOMAIN_ID];
67
        $setKey = (int) $record[_ENTITY::ATTR_SET_ID];
68 3
69 2
        $this->checkDomainExists($domainKey);
70 1
        $this->checkAttrSetExist($setKey);
71 1
        $set->setKey($setKey);
72
        $entity->setDomainKey($domainKey);
73 1
74
        return 2;
75
    }
76 3
77
    public function find(): Result
78 3
    {
79
        $result = new Result();
80 3
81
        $entity = $this->getEntity();
82 3
83 1
        if (!$entity->hasKey()) {
84
            return $result->empty();
85 2
        }
86
        $key = $entity->getKey();
87 2
88 2
        $model = $this->makeEntityModel();
89
        $record = $model->findByKey($key);
90 2
91 1
        if ($record === false) {
92
            return $result->notFound();
93
        }
94 1
95 1
        $entity->setDomainKey($record[_ENTITY::DOMAIN_ID]);
96 1
        $set = $entity->getAttributeSet();
97 1
        $set->setKey($record[_ENTITY::ATTR_SET_ID]);
98
        $set->fetchContainers();
99 1
100
        $bag = $entity->getBag();
101 1
        foreach ($set->getContainers() as $container) {
102
            $attribute = $container->getAttribute();
103
            $valueManger = $container->getValueManager();
104
            $value = $valueManger->getValue();
105
            $bag->setField($attribute->getName(), $value);
106
        }
107
108 14
        $result->found();
109
110 14
        return $result;
111 14
    }
112 14
113 7
    /**
114 7
     * @throws EntityException
115 7
     * @throws Exception
116 7
     */
117 2
    public function save(): Result
118 2
    {
119
        $entity = $this->getEntity();
120 7
        $result = new Result();
121 3
        $operationType = $this->beforeSave();
122 4
        $set = $entity->getAttributeSet();
123 7
        $set->fetchContainers();
124 7
        $valueResults = [];
125 7
        foreach ($set->getContainers() as $container) {
126
            $attribute = $container->getAttribute();
127 7
            $valueResults[$attribute->getName()] = $container->getStrategy()->save();
128
        }
129
        1 == $operationType
130
            ? $result->created()
131
            : $result->updated();
132
        $result->setData($valueResults);
133 4
134
        // fill bag with new values
135 4
        $bag = $entity->getBag();
136 4
        $bag->clear();
137
        foreach ($set->getContainers() as $container) {
138 4
            $attribute = $container->getAttribute();
139 1
            $name = $attribute->getName();
140
            $value = $container->getValueManager()->getValue();
141 3
            $bag->setField($name, $value);
142 1
        }
143
144
        return $result;
145 2
    }
146 2
147 2
    /**
148 2
     * @throws EntityException
149 1
     */
150 1
    public function delete()
151
    {
152 2
        $entity = $this->getEntity();
153 2
        $set = $entity->getAttributeSet();
154 2
155 1
        if (!$entity->hasKey()) {
156
            EntityException::undefinedEntityKey();
157
        }
158 1
        if (!$set->hasKey()) {
159 1
            EntityException::undefinedAttributeSetKey();
160 1
        }
161 1
162
        $result = new Result();
163 1
        $set->fetchContainers();
164 1
        $deleteResults = [];
165
        foreach ($set->getContainers() as $container) {
166 1
            $attribute = $container->getAttribute();
167
            $deleteResults[$attribute->getName()] = $container->getStrategy()->delete();
168
        }
169 2
        $entityModel = $this->makeEntityModel();
170
        $recordResult = $entityModel->deleteByKey($entity->getKey());
171 2
        if (!$recordResult) {
172 2
            return $result->notDeleted();
173 2
        }
174 2
175 2
        $entity->setKey(0);
176 2
        $entity->setDomainKey(0);
177 2
        $set->setKey(0);
178 2
        $set->resetContainers();
179 2
180 1
        $bag = $entity->getBag();
181
        $bag->clear();
182
183 2
        $result->deleted();
184 1
        $result->setData($deleteResults);
185 1
186
        return $result;
187
    }
188 2
189
    public function validate(): Result
190
    {
191 1
        $result = new Result();
192
        $result->validationPassed();
193 1
        $entity = $this->getEntity();
194 1
        $set = $entity->getAttributeSet();
195 1
        $set->fetchContainers();
196 1
        $errors = [];
197
        foreach ($set->getContainers() as $container) {
198
            $validationResult = $container->getValueValidator()->validateField();
199 1
            if (!is_null($validationResult)) {
200
                $errors[$container->getAttribute()->getName()] = $validationResult;
201
            }
202
        }
203
        if (count($errors) > 0) {
204
            $result->validationFails();
205
            $result->setData($errors);
206
        }
207
208
        return $result;
209
    }
210
211
    public function toArray(): array
212
    {
213
        $result = [];
214
        $entity = $this->getEntity();
215
        foreach ($entity->getAttributeSet()->getContainers() as $container) {
216
            $result[$container->getAttribute()->getName()] = $container->getValueManager()->getValue();
217
        }
218
219 1
        return $result;
220
    }
221 1
222
    public function toArrayByGroup(): array
223 1
    {
224 1
        $entity = $this->getEntity();
225
        $attrSet = $entity->getAttributeSet();
226
        $setKey = $attrSet->getKey();
227
        $groupModel = new AttributeGroupModel();
228
        $groups = array_column($groupModel->findBySetKey($setKey), null, _GROUP::ID);
229
        $out = [];
230 1
        foreach ($attrSet->getContainers() as $container) {
231
            $attribute = $container->getAttribute();
232 1
            $groupKey = $attribute->getGroupKey();
233
            if (!key_exists($groupKey, $out)) {
234 1
                $out[$groupKey] = [
235 1
                    'group' => $groups[$groupKey],
236
                    'attributes' => []
237
                ];
238
            }
239
            $out[$groupKey]['attributes'][] = [
240
                'attribute' => $container->getAttribute()->getBag()->getFields(),
241
                'value' => $container->getValueManager()->getValue()
242
            ];
243
        }
244
        return $out;
245
    }
246
247
    /**
248
     * @throws EntityException
249
     */
250
    private function checkEntityExists(int $key): array
251
    {
252
        $entity = $this->makeEntityModel();
253
254
        $result = $entity->findByKey($key);
255
        if ($result === false)
256
            EntityException::entityNotFound();
257
258
        return $result;
259
    }
260
261
    /**
262
     * @throws EntityException
263
     */
264
    private function checkDomainExists(int $key): void
265
    {
266
        $domain = $this->makeDomainModel();
267
268
        if ($domain->findByKey($key) === false)
269
            EntityException::domainNotFound();
270
    }
271
272
    /**
273
     * @throws EntityException
274
     */
275
    private function checkAttrSetExist(int $key): void
276
    {
277
        $model = $this->makeAttributeSetModel();
278
279
        if($model->findByKey($key) === false) {
280
            EntityException::attrSetNotFound();
281
        }
282
    }
283
}
284