RemoveTraverseTrait::remove()   A
last analyzed

Complexity

Conditions 6
Paths 7

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 18
dl 0
loc 27
ccs 19
cts 19
cp 1
rs 9.0444
c 2
b 0
f 0
cc 6
nc 7
nop 1
crap 6
1
<?php
2
/**
3
 * @author Maxim Sokolovsky
4
 */
5
6
namespace WS\Utils\Collections;
7
8
use WS\Utils\Collections\Iterator\Iterator;
9
10
trait RemoveTraverseTrait
11
{
12 12
    public function remove($element): bool
13
    {
14 12
        if ($this->isEmpty()) {
15 2
            return false;
16
        }
17
        $fMatch = static function ($tested) use ($element): bool {
18 8
            return $tested === $element;
19 10
        };
20 10
        if ($element instanceof HashCodeAware) {
21
            $fMatch = static function ($tested) use ($element): bool {
22 4
                if ($tested instanceof HashCodeAware) {
23 4
                    return $tested->getHashCode() === $element->getHashCode();
24
                }
25 1
                return $tested === $element;
26 4
            };
27
        }
28 10
        $indexIterator = $this->getIndexIterator();
29 10
        $elements = $this->getElements();
30 10
        while ($indexIterator->hasNext()) {
31 10
            $index = $indexIterator->next();
32 10
            if ($fMatch($elements[$index])) {
33 8
                unset($elements[$index]);
34 8
                $this->setElements(array_values($elements));
35 8
                return true;
36
            }
37
        }
38 6
        return false;
39
    }
40
41
    abstract public function getIndexIterator(): Iterator;
42
43
    abstract public function isEmpty(): bool;
44
45
    abstract protected function setElements(array $elements): void;
46
47
    abstract protected function getElements(): array;
48
}
49