IntegerList::isEmpty()   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 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cunningsoft\GenericList;
6
7
use ArrayIterator;
8
use InvalidArgumentException;
9
use function array_sum;
10
use function count;
11
use function get_class;
12
use function gettype;
13
use function is_int;
14
use function is_object;
15
use function sprintf;
16
17
final class IntegerList implements ListType
18
{
19
    /** @var int[] */
20
    private $elements = [];
21
22
    /** @param mixed[] $elements */
23 8
    public function __construct(iterable $elements = [])
24
    {
25 8
        foreach ($elements as $element) {
26 6
            if (!is_int($element)) {
27 4
                throw new InvalidArgumentException(sprintf(
28 4
                    'Expected an integer, but got: %s.',
29 4
                    is_object($element) ? get_class($element) : gettype($element),
30
                ));
31
            }
32 6
            $this->elements[] = $element;
33
        }
34 4
    }
35
36 12
    public function count(): int
37
    {
38 12
        return count($this->elements);
39
    }
40
41 9
    public function isEmpty(): bool
42
    {
43 9
        return $this->count() === 0;
44
    }
45
46 3
    public function isNotEmpty(): bool
47
    {
48 3
        return !$this->isEmpty();
49
    }
50
51 4
    public function sum(): int
52
    {
53 4
        return (int) array_sum($this->elements);
54
    }
55
56 3
    public function average(): float
57
    {
58 3
        if ($this->isEmpty()) {
59 1
            return 0.0;
60
        }
61
62 2
        return $this->sum() / $this->count();
63
    }
64
65
    /** @return ArrayIterator|int[] */
66 3
    public function getIterator(): ArrayIterator
67
    {
68 3
        return new ArrayIterator($this->elements);
69
    }
70
}
71