Completed
Push — feature/middleware ( e5c34d...47ade2 )
by Derek Stephen
04:05
created

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