Lines 0.00% 0 / 256
Methods 0.00% 0 / 37
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 deleteEntity 0.00% 0 / 5 0.00% 0 / 1 6
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] __construct 0.00% 0 / 10 0.00% 0 / 1 12
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] entityNeedsUpdate 0.00% 0 / 8 0.00% 0 / 1 6
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] setStatus 0.00% 0 / 1 0.00% 0 / 1 2
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] getStatus 0.00% 0 / 1 0.00% 0 / 1 2
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] getReferenceMapping 0.00% 0 / 5 0.00% 0 / 1 12
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] setupMapping 0.00% 0 / 1 0.00% 0 / 1 2
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] preSetup 0.00% 0 / 1 0.00% 0 / 1 2
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] postSetup 0.00% 0 / 1 0.00% 0 / 1 2
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] preSetupFields 0.00% 0 / 1 0.00% 0 / 1 2
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] postSetupFields 0.00% 0 / 1 0.00% 0 / 1 2
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] setupFields 0.00% 0 / 12 0.00% 0 / 1 30
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] getReferenceFields 0.00% 0 / 4 0.00% 0 / 1 6
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] setupReferences 0.00% 0 / 39 0.00% 0 / 1 182
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] __set 0.00% 0 / 9 0.00% 0 / 1 42
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] addReference 0.00% 0 / 4 0.00% 0 / 1 12
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] __get 0.00% 0 / 5 0.00% 0 / 1 12
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] __isset 0.00% 0 / 1 0.00% 0 / 1 6
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] __unset 0.00% 0 / 4 0.00% 0 / 1 12
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] offsetExists 0.00% 0 / 1 0.00% 0 / 1 6
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] offsetGet 0.00% 0 / 3 0.00% 0 / 1 6
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] offsetSet 0.00% 0 / 3 0.00% 0 / 1 6
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] offsetUnset 0.00% 0 / 3 0.00% 0 / 1 6
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] count 0.00% 0 / 1 0.00% 0 / 1 2
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] jsonSerialize 0.00% 0 / 1 0.00% 0 / 1 2
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] getFields 0.00% 0 / 1 0.00% 0 / 1 2
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] get 0.00% 0 / 21 0.00% 0 / 1 90
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] arrayAccessByDotPerpareKeys 0.00% 0 / 10 0.00% 0 / 1 20
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] save 0.00% 0 / 6 0.00% 0 / 1 12
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] saveEntitiy 0.00% 0 / 15 0.00% 0 / 1 42
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] saveReferences 0.00% 0 / 6 0.00% 0 / 1 20
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] delete 0.00% 0 / 4 0.00% 0 / 1 6
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] deleteReferences 0.00% 0 / 27 0.00% 0 / 1 156
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] deleteWith 0.00% 0 / 10 0.00% 0 / 1 12
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] clearEntity 0.00% 0 / 3 0.00% 0 / 1 6
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] clearEntityReferences 0.00% 0 / 22 0.00% 0 / 1 72
 [BO\Zmsdldb\Importer\MySQL\Entity\Base] getTableName 0.00% 0 / 6 0.00% 0 / 1 6
5class TopicCluster extends Base
6{
7    protected array $fieldMapping = [
8        'id' => 'topic_id',
9        'parent_id' => 'parent_id',
10        'rank' => 'rank'
11    ];
12
13    #[\Override]
14    public function deleteEntity(): void
15    {
16        try {
17            $this->deleteWith(
18                array_combine(['topic_id', 'parent_id'], array_values($this->get('id', 'parent_id')))
19            );
20        } catch (\Exception $e) {
21            throw $e;
22        }
23    }
24}

Inherited from BO\Zmsdldb\Importer\MySQL\Entity\Base

45    public function __construct(PDOAccess $mySqlAccess, array $dataRaw = [], bool $setup = true)
46    {
47        try {
48            $this->pdoAccess = $mySqlAccess;
49            $this->dataRaw = $dataRaw;
50
51            if (true === $setup) {
52                $this->setupMapping();
53
54                $this->preSetup();
55
56                $this->setupFields();
57
58                $this->setupReferences();
59
60                $this->postSetup();
61            }
62        } catch (\Exception $e) {
63            throw $e;
64        }
65    }
67    protected function entityNeedsUpdate(): bool
68    {
69        $fields = $this->get(['id', 'meta.locale', 'meta.hash']);
70        $hash = $fields['meta.hash'] ?? '';
71
72        return $this->itemNeedsUpdate(
73            (int) ($fields['id'] ?? 0),
74            (string) ($fields['meta.locale'] ?? ''),
75            is_scalar($hash) ? (string) $hash : '',
76            static::getTableName()
77        );
78    }
80    public function setStatus(int $status = Base::STATUS_NEW): void
81    {
82        $this->status = $status;
83    }
85    public function getStatus(): int
86    {
87        return $this->status;
88    }
90    public function getReferenceMapping(bool $setup = false): array
91    {
92        try {
93            if (true === $setup) {
94                $this->setupMapping();
95            }
96
97            return $this->referanceMapping;
98        } catch (\Exception $e) {
99            throw $e;
100        }
101    }
103    protected function setupMapping(): void
104    {
105    }
107    public function preSetup(): void
108    {
109    }
111    public function postSetup(): void
112    {
113    }
115    public function preSetupFields(): void
116    {
117    }
119    public function postSetupFields(): void
120    {
121    }
123    final public function setupFields(): void
124    {
125        try {
126            if (false === $this->setupFields) {
127                return;
128            }
129            $this->preSetupFields();
130
131            $values = $this->get(array_keys(array_filter($this->fieldMapping)));
132            foreach ($values as $key => $value) {
133                if (!is_string($key)) {
134                    continue;
135                }
136                $this->__set($key, $value);
137            }
138            $this->postSetupFields();
139            $this->setupFields = false;
140        } catch (\Exception $e) {
141            throw $e;
142        }
143    }
145    protected function getReferenceFields(): array
146    {
147        $referenceFields = array_flip(array_keys(array_filter($this->referanceMapping)));
148
149        foreach (array_keys($referenceFields) as $name) {
150            $referenceFields[$name] = $this->get($name);
151        }
152        return $referenceFields;
153    }
155    final public function setupReferences(): void
156    {
157        try {
158            if (false === $this->setupReferences) {
159                return;
160            }
161            $values = $this->getReferenceFields();
162
163            foreach ($values as $name => $references) {
164                $referenceEntityClass = $this->referanceMapping[$name]['class'];
165                if (!is_string($referenceEntityClass)) {
166                    throw new \InvalidArgumentException('Invalid reference entity class');
167                }
168                /** @var class-string<Base> $referenceEntityClass */
169                $addFields = [];
170
171                foreach (($this->referanceMapping[$name]['neededFields'] ?? []) as $sourceKey => $destinationKey) {
172                    $addFields[$destinationKey] = $this->get($sourceKey);
173                }
174                $isMultiple = $this->referanceMapping[$name]['multiple'] ?? true;
175
176                if (false === $isMultiple) {
177                    $references = [$references];
178                }
179
180                $position = 0;
181                foreach (($references ?? []) as $reference) {
182                    foreach ($this->referanceMapping[$name]['addFields'] as $key => $value) {
183                        if (is_callable($value)) {
184                            $addFields[$key] = call_user_func_array($value, [$position, $name, $reference]);
185                        } else {
186                            $addFields[$key] = $value;
187                        }
188                    }
189                    if (true === ($this->referanceMapping[$name]['selfAsArray'] ?? false)) {
190                        $reference = [
191                            $name => $reference
192                        ];
193                    }
194                    if (!is_array($reference)) {
195                        $reference = [];
196                    }
197                    /** @psalm-suppress UnsafeInstantiation */
198                    $referencesInstance = new $referenceEntityClass(
199                        $this->getPDOAccess(),
200                        array_merge(
201                            $reference,
202                            $addFields
203                        )
204                    );
205                    if (!$referencesInstance instanceof Base) {
206                        throw new \InvalidArgumentException($referenceEntityClass . ' must extend ' . Base::class);
207                    }
208
209                    $this->addReference($name, $referencesInstance);
210                    $position++;
211                }
212            }
213            $this->setupReferences = false;
214        } catch (\Exception $e) {
215            throw $e;
216        }
217    }
219    final public function __set(string $name, mixed $value): void
220    {
221        if (array_key_exists($name, $this->fieldMapping)) {
222            $name = $this->fieldMapping[$name];
223            if (is_bool($value)) {
224                $value = (int)$value;
225            } elseif (false !== stripos($name, '_json')) {
226                $value = json_encode($value);
227            }
228            $this->fields[$name] = $value;
229        } elseif (array_key_exists($name, $this->referanceMapping) && $value instanceof Base) {
230            $this->addReference($name, $value);
231        }
232    }
234    public function addReference(string $name, Base $reference): void
235    {
236        if (array_key_exists($name, $this->referanceMapping)) {
237            if (!isset($this->references[$name])) {
238                $this->references[$name] = new EntityCollection();
239            }
240            $this->references[$name][] = $reference;
241        }
242    }
244    final public function __get(string $name): mixed
245    {
246        if (array_key_exists($name, $this->fields)) {
247            return $this->fields[$name];
248        }
249        if (array_key_exists($name, $this->references)) {
250            return $this->references[$name];
251        }
252        throw new \InvalidArgumentException(__METHOD__ . " {$name} has not been set!");
253    }
255    final public function __isset(string $name): bool
256    {
257        return array_key_exists($name, $this->fields) || array_key_exists($name, $this->references);
258    }
260    final public function __unset(string $name): void
261    {
262        if (array_key_exists($name, $this->fields)) {
263            unset($this->fields[$name]);
264        }
265        if (array_key_exists($name, $this->references)) {
266            unset($this->references[$name]);
267        }
268    }
271    final public function offsetExists($offset): bool
272    {
273        return is_string($offset) && $this->__isset($offset);
274    }
277    final public function offsetGet($offset): mixed
278    {
279        if (!is_string($offset)) {
280            throw new \InvalidArgumentException(__METHOD__ . ' offset must be a string');
281        }
282        return $this->__get($offset);
283    }
286    final public function offsetSet($offset, $value): void
287    {
288        if (!is_string($offset)) {
289            throw new \InvalidArgumentException(__METHOD__ . ' offset must be a string');
290        }
291        $this->__set($offset, $value);
292    }
295    final public function offsetUnset($offset): void
296    {
297        if (!is_string($offset)) {
298            throw new \InvalidArgumentException(__METHOD__ . ' offset must be a string');
299        }
300        $this->__unset($offset);
301    }
304    final public function count(): int
305    {
306        return count($this->fields);
307    }
310    public function jsonSerialize(): mixed
311    {
312        return $this->fields;
313    }
315    public function getFields(): array
316    {
317        return $this->fields;
318    }
320    public function get(null|array|string $key = null, mixed $default = null): mixed
321    {
322        if (null === $key) {
323            return $this->dataRaw;
324        }
325        $keys = $key;
326        if (!is_array($keys)) {
327            $keys = [$keys];
328        }
329        $values = [];
330
331        foreach ($keys as $key) {
332            if ('__RAW__' == $key) {
333                $values[$key] = $this->dataRaw;
334                continue;
335            }
336            $levels = static::arrayAccessByDotPerpareKeys($key);
337
338            $value = $default;
339
340            $current = $this->dataRaw;
341            $levelsCount = count($levels);
342            for ($i = 0; $i < $levelsCount; ++$i) {
343                if (!is_array($current) || !array_key_exists($levels[$i], $current)) {
344                    continue;
345                }
346                $current = $current[$levels[$i]];
347                $value = $current;
348            }
349            $values[$key] = ($value);
350        }
351        return 1 == count($keys) ? $values[$keys[0]] : $values;
352    }
354    protected static function arrayAccessByDotPerpareKeys(?string $key = null): array
355    {
356        if (null === $key) {
357            return [];
358        }
359        $keys = explode('.', $key);
360        $keys = array_filter($keys, 'strlen');
361        $keys = array_map(static function (string $segment): int|string {
362            if (is_numeric($segment) && !str_contains($segment, '.')) {
363                return (int) $segment;
364            }
365            return $segment;
366        }, $keys);
367
368        return $keys;
369    }
371    public function save(): void
372    {
373        try {
374            if (static::STATUS_NEW !== $this->getStatus()) {
375                return;
376            }
377            $this->saveEntitiy();
378            $this->saveReferences();
379        } catch (\Exception $e) {
380            throw $e;
381        }
382    }
384    final public function saveEntitiy(): void
385    {
386        try {
387            if (static::STATUS_NEW !== $this->getStatus()) {
388                return;
389            }
390            if (!empty($this->fields)) {
391                $sql = 'REPLACE INTO ' . static::getTableName() . ' ';
392                $sql .= '(`' . implode('`, `', array_keys($this->fields)) . '`) ';
393
394                $questionMarks = array_fill(0, count($this->fields), '?');
395                $sql .= 'VALUES (' . implode(', ', $questionMarks) . ') ';
396
397                $stm = $this->getPDOAccess()->prepare($sql);
398
399                $stm->execute(array_values($this->fields));
400
401                if ($stm && 0 < $stm->rowCount()) {
402                    return;
403                }
404                throw new \Exception('Could not save entity');
405            }
406            throw new \Exception('Could not save entity, fields are empty');
407        } catch (\Exception $e) {
408            throw $e;
409        }
410    }
412    final public function saveReferences(): void
413    {
414        try {
415            if (static::STATUS_NEW !== $this->getStatus()) {
416                return;
417            }
418            foreach ($this->references as $referencesCollection) {
419                $referencesCollection->saveEntities();
420            }
421        } catch (\Exception $e) {
422            throw $e;
423        }
424    }
427    public function delete(): void
428    {
429        try {
430            $this->deleteEntity();
431            $this->deleteReferences();
432        } catch (\Exception $e) {
433            throw $e;
434        }
435    }
439    public function deleteReferences(): void
440    {
441        try {
442            foreach ($this->referanceMapping as $name => $mappingData) {
443                if (isset($mappingData['deleteFunction']) && is_callable($mappingData['deleteFunction'])) {
444                    call_user_func_array($mappingData['deleteFunction'], [$this, $name, $mappingData]);
445                    continue;
446                }
447                if (array_key_exists('delete', $mappingData) && false === $mappingData['delete']) {
448                    continue;
449                }
450                if (!array_key_exists('deleteFields', $mappingData) || empty($mappingData['deleteFields'])) {
451                    throw new \Exception(static::class . ' missing $deleteFields in reference mapping');
452                }
453                $addFields = [];
454                $referenceEntityClass = $mappingData['class'];
455                if (!is_string($referenceEntityClass)) {
456                    throw new \InvalidArgumentException('Invalid reference entity class');
457                }
458                /** @var class-string<Base> $referenceEntityClass */
459                foreach ($mappingData['deleteFields'] as $sourceKey => $val) {
460                    $addFields[$sourceKey] = $val;
461                }
462
463                /** @psalm-suppress UnsafeInstantiation */
464                $referencesInstance = new $referenceEntityClass(
465                    $this->getPDOAccess(),
466                    $addFields,
467                    false
468                );
469                if (!$referencesInstance instanceof Base) {
470                    throw new \InvalidArgumentException($referenceEntityClass . ' must extend ' . Base::class);
471                }
472                $referencesInstance->setupFields();
473
474                $referencesInstance->deleteWith(
475                    array_intersect_key($referencesInstance->getFields(), $addFields)
476                );
477            }
478        } catch (\Exception $e) {
479            throw $e;
480        }
481    }
483    final public function deleteWith(array $fields): void
484    {
485        try {
486            $sql = "DELETE FROM " . static::getTableName();
487            if (!empty($fields)) {
488                $where = array_map(function (int|string $field): string {
489                    return $field . ' = ?';
490                }, array_keys($fields));
491                $sql .= " WHERE " . implode(' AND ', $where);
492            }
493
494            $stm = $this->getPDOAccess()->prepare($sql);
495            $stm->execute(array_values($fields));
496        } catch (\Exception $e) {
497            throw $e;
498        }
499    }
501    public function clearEntity(array $addWhere = []): void
502    {
503        try {
504            $this->deleteWith($addWhere);
505        } catch (\Exception $e) {
506            throw $e;
507        }
508    }
510    public function clearEntityReferences(): void
511    {
512        try {
513            foreach ($this->getReferenceMapping(true) as $name => $mappingData) {
514                $referenceEntityClass = $mappingData['class'];
515                if (!is_string($referenceEntityClass)) {
516                    throw new \InvalidArgumentException('Invalid reference entity class');
517                }
518                /** @var class-string<Base> $referenceEntityClass */
519                $clearFields = [];
520                $position = 0;
521                foreach (($mappingData['clearFields'] ?? []) as $key => $value) {
522                    if (is_callable($value)) {
523                        $clearFields[$key] = call_user_func_array($value, [$position++, $name, null]);
524                    } else {
525                        $clearFields[$key] = $value;
526                    }
527                }
528
529                /** @psalm-suppress UnsafeInstantiation */
530                $referencesInstance = new $referenceEntityClass(
531                    $this->getPDOAccess(),
532                    [],
533                    false
534                );
535                if (!$referencesInstance instanceof Base) {
536                    throw new \InvalidArgumentException($referenceEntityClass . ' must extend ' . Base::class);
537                }
538                if (!empty($clearFields)) {
539                    $referencesInstance->deleteWith($clearFields);
540                } else {
541                    $referencesInstance->clearEntity();
542                }
543            }
544        } catch (\Exception $e) {
545            throw $e;
546        }
547    }
549    public static function getTableName(): string
550    {
551        $classNameWithNs = explode("\\", static::class);
552        $className = end($classNameWithNs);
553        $table = defined('static::TABLENAME')
554            ? constant('static::TABLENAME')
555            : preg_replace('/(?<!^)[A-Z]/', '_$0', $className);
556
557        return strtolower((string) $table);
558    }