Completed
Push — feature/middleware ( 16c6e3...4ff047 )
by Derek Stephen
07:45
created

DragonCollection::jsonSerialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace BoneMvc\Module\Dragon\Collection;
4
5
use BoneMvc\Module\Dragon\Entity\Dragon;
6
use Doctrine\Common\Collections\ArrayCollection;
7
use JsonSerializable;
8
use LogicException;
9
10
class DragonCollection extends ArrayCollection implements JsonSerializable
11
{
12
    /**
13
     * @param Dragon $dragon
14
     * @return $this
15
     * @throws LogicException
16
     */
17
    public function update(Dragon $dragon)
18
    {
19
        $key = $this->findKey($dragon);
20
        if($key) {
21
            $this->offsetSet($key,$dragon);
22
            return $this;
23
        }
24
        throw new LogicException('Dragon was not in the collection.');
25
    }
26
27
    /**
28
     * @param Dragon $dragon
29
     */
30
    public function append(Dragon $dragon)
31
    {
32
        $this->add($dragon);
33
    }
34
35
    /**
36
     * @return Dragon|null
37
     */
38
    public function current()
39
    {
40
        return parent::current();
41
    }
42
43
    /**
44
     * @param Dragon $dragon
45
     * @return bool|int
46
     */
47
    public function findKey(Dragon $dragon)
48
    {
49
        $it = $this->getIterator();
50
        $it->rewind();
51
        while($it->valid()) {
52
            if($it->current()->getId() == $dragon->getId()) {
53
                return $it->key();
54
            }
55
            $it->next();
56
        }
57
        return false;
58
    }
59
60
    /**
61
     * @param int $id
62
     * @return Dragon|bool
63
     */
64
    public function findById(int $id)
65
    {
66
        $it = $this->getIterator();
67
        $it->rewind();
68
        while($it->valid()) {
69
            if($it->current()->getId() == $id) {
70
                return $it->current();
71
            }
72
            $it->next();
73
        }
74
        return false;
75
    }
76
77
    /**
78
     * @return array
79
     */
80
    public function toArray(): array
81
    {
82
        $collection = [];
83
        $it = $this->getIterator();
84
        $it->rewind();
85
        while($it->valid()) {
86
            /** @var Dragon $row */
87
            $row = $it->current();
88
            $collection[] = $row->toArray();
89
            $it->next();
90
        }
91
92
        return $collection;
93
    }
94
95
    /**
96
     * @return string
97
     */
98
    public function jsonSerialize(): string
99
    {
100
        return \json_encode($this->toArray());
101
    }
102
103
    /**
104
     * @return string
105
     */
106
    public function __toString(): string
107
    {
108
        return $this->jsonSerialize();
109
    }
110
}
111