Completed
Push — master ( 7c5d05...0ade20 )
by Nate
02:05
created

ArraySet::remove()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
/*
3
 * Copyright (c) Nate Brunette.
4
 * Distributed under the MIT License (http://opensource.org/licenses/MIT)
5
 */
6
7
namespace Tebru\Collection;
8
9
use ArrayIterator;
10
11
/**
12
 * Class ArraySet
13
 *
14
 * @author Nate Brunette <[email protected]>
15
 */
16
class ArraySet extends AbstractSet
17
{
18
    /**
19
     * The set elements
20
     *
21
     * @var array
22
     */
23
    private $elements = [];
24
25
    /**
26
     * Constructor
27
     *
28
     * @param array $elements
29
     */
30
    public function __construct(array $elements = [])
31
    {
32
        $this->addAllArray($elements);
33
    }
34
35
    /**
36
     * Ensure the element exists in the collection
37
     *
38
     * Returns true if the collection can contain duplicates,
39
     * and false if it cannot.
40
     *
41
     * @param mixed $element
42
     * @return bool
43
     */
44
    public function add($element): bool
45
    {
46
        if ($this->contains($element)) {
47
            return false;
48
        }
49
50
        $this->elements[] = $element;
51
52
        return true;
53
    }
54
55
    /**
56
     * Removes all elements from a collection
57
     *
58
     * @return void
59
     */
60
    public function clear(): void
61
    {
62
        $this->elements = [];
63
    }
64
65
    /**
66
     * Removes object if it exists
67
     *
68
     * Returns true if the element was removed
69
     *
70
     * @param mixed $element
71
     * @return bool
72
     */
73
    public function remove($element): bool
74
    {
75
        if (!$this->contains($element)) {
76
            return false;
77
        }
78
79
        unset($this->elements[array_search($element, $this->elements, true)]);
80
81
        return true;
82
    }
83
84
    /**
85
     * Returns an array of all elements in the collection
86
     *
87
     * @return array
88
     */
89
    public function toArray(): array
90
    {
91
        return array_values($this->elements);
92
    }
93
94
    /**
95
     * Retrieve an external iterator
96
     *
97
     * @return ArrayIterator
98
     */
99
    public function getIterator(): ArrayIterator
100
    {
101
        return new ArrayIterator($this->toArray());
102
    }
103
}
104