IntegerList   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 15
c 1
b 0
f 0
dl 0
loc 52
ccs 22
cts 22
cp 1
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 4
A getIterator() 0 3 1
A isNotEmpty() 0 3 1
A average() 0 7 2
A sum() 0 3 1
A isEmpty() 0 3 1
A count() 0 3 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