Completed
Push — master ( 857a85...1fa5c8 )
by Gabriel
02:48
created

Codes::findByCode()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 0
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 1
crap 12
1
<?php
2
3
namespace Waredesk\Collections\Products\Variants;
4
5
use Waredesk\Collection;
6
use Waredesk\Models\Product\Variant\Code;
7
use JsonSerializable;
8
9
/**
10
 * @method Code first()
11
 * @method Code current()
12
 * @method Code next()
13
 * @method Code offsetGet($offset)
14
 */
15
class Codes extends Collection
16
{
17
    /**
18
     * @param Code|\Waredesk\Models\Code $item
19
     */
20 1
    public function add($item): void
21
    {
22 1
        parent::add($item);
23 1
    }
24
25
    public function findByCode(string $code): ? Code
26
    {
27
        /** @var Code $item */
28
        foreach ($this->items as $item) {
29
            if ($item->getCode() === $code) {
30
                return $item;
31
            }
32
        }
33
        return null;
34
    }
35
36
    public function findByName($name): ? Code
37
    {
38
        /** @var Code $item */
39
        foreach ($this->items as $item) {
40
            if ($item->getName() === $name) {
41
                return $item;
42
            }
43
        }
44
        return null;
45
    }
46
47
    public function jsonSerialize(): array
48
    {
49 4
        return array_map(function (JsonSerializable $item) {
50 1
            $finalItem = $item->jsonSerialize();
51 1
            if (isset($finalItem['id'])) {
52 1
                $finalItem = array_merge(['code' => $finalItem['id']], $finalItem);
53 1
                unset($finalItem['id']);
54 1
                $finalItem = $this->serializeElements($finalItem);
55
            }
56 1
            return $finalItem;
57 4
        }, $this->items);
58
    }
59
60 1
    private function serializeElements(array $item): array
61
    {
62 1
        if (isset($item['elements']) && is_array($item['elements'])) {
63 1
            $finalElements = [];
64 1
            foreach ($item['elements'] as $element) {
65 1
                if (isset($element['id'])) {
66 1
                    $element = array_merge(['element' => $element['id']], $element);
67 1
                    unset($element['id']);
68
                }
69 1
                $finalElements[] = $element;
70
            }
71 1
            $item['elements'] = $finalElements;
72
        }
73 1
        return $item;
74
    }
75
}
76