SetLikeTrait::offsetSet()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
3
namespace Collections\Traits;
4
5
use Collections\Exception\ElementAlreadyExists;
6
use Collections\Exception\InvalidOperationException;
7
8
trait SetLikeTrait
9
{
10
    use ConstSetLikeTrait,
11
        CommonMutableContainerTrait;
12
13
    public function offsetSet($offset, $value)
14
    {
15
        if (is_null($offset)) {
16
            $this->add($value);
17
        } else {
18
            throw new InvalidOperationException('[] operator cannot be used to modify elements of a Set');
19
        }
20
    }
21
22
    public function offsetUnset($offset)
23
    {
24
        $this->remove($offset);
25
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function add($item)
31
    {
32
        if ($this->contains($item)) {
33
            throw ElementAlreadyExists::duplicatedElement($item);
34
        }
35
36
        $this->container[] = $item;
37
38
        return $this;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function removeKey($key)
45
    {
46
        $this->validateKeyDoesNotExists($key);
47
48
        unset($this->container[$key]);
49
50
        return $this;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 View Code Duplication
    public function remove($element)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
57
    {
58
        $key = array_search($element, $this->container);
59
60
        if (false === $key) {
61
            throw new \OutOfBoundsException('No element found in the collection');
62
        }
63
64
        $this->removeKey($key);
65
66
        return $this;
67
    }
68
69
    /**
70
     * @inheritDoc
71
     */
72
    public function removeAll($traversable)
73
    {
74
        foreach ($traversable as $item) {
75
            if ($this->contains($item)) {
76
                $this->remove($item);
77
            }
78
        }
79
80
        return $this;
81
    }
82
83
    /**
84
     * {@inheritDoc}
85
     * @return $this
86
     */
87
    public function each(callable $callable)
88
    {
89
        foreach ($this as $v) {
0 ignored issues
show
Bug introduced by
The expression $this of type this<Collections\Traits\SetLikeTrait> is not traversable.
Loading history...
90
            $callable($v);
91
        }
92
93
        return $this;
94
    }
95
}
96