StringList::walk()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cunningsoft\GenericList;
6
7
use ArrayIterator;
8
use InvalidArgumentException;
9
use const SORT_REGULAR;
10
use function array_merge;
11
use function array_slice;
12
use function array_unique;
13
use function array_walk;
14
use function count;
15
use function get_class;
16
use function gettype;
17
use function implode;
18
use function is_object;
19
use function is_string;
20
use function sprintf;
21
22
final class StringList implements ListType
23
{
24
    /** @var string[] */
25
    private $elements = [];
26
27
    /** @param mixed[] $elements */
28 29
    public function __construct(iterable $elements = [])
29
    {
30 29
        foreach ($elements as $element) {
31 19
            if (!is_string($element)) {
32 4
                throw new InvalidArgumentException(sprintf(
33 4
                    'Expected a string, but got: %s.',
34 4
                    is_object($element) ? get_class($element) : gettype($element),
35
                ));
36
            }
37 19
            $this->elements[] = $element;
38
        }
39 25
    }
40
41 9
    public function count(): int
42
    {
43 9
        return count($this->elements);
44
    }
45
46 6
    public function isEmpty(): bool
47
    {
48 6
        return $this->count() === 0;
49
    }
50
51 3
    public function isNotEmpty(): bool
52
    {
53 3
        return !$this->isEmpty();
54
    }
55
56 4
    public function merge(self $other): self
57
    {
58 4
        return new self(array_merge($this->elements, $other->elements));
59
    }
60
61 12
    public function slice(int $offset, ?int $length = null): self
62
    {
63 12
        return new self(array_slice($this->elements, $offset, $length));
64
    }
65
66 4
    public function distinct(): self
67
    {
68 4
        return new self(array_unique($this->elements, SORT_REGULAR));
69
    }
70
71 1
    public function walk(callable $callback): bool
72
    {
73 1
        return array_walk($this->elements, $callback);
74
    }
75
76 6
    public function implode(string $glue = ''): string
77
    {
78 6
        return implode($glue, $this->elements);
79
    }
80
81
    /** @return ArrayIterator|string[] */
82 3
    public function getIterator(): ArrayIterator
83
    {
84 3
        return new ArrayIterator($this->elements);
85
    }
86
}
87