Stack   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 102
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
eloc 16
dl 0
loc 102
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A count() 0 3 1
A peek() 0 3 1
A pop() 0 3 1
A push() 0 12 1
A __construct() 0 4 1
A isEmpty() 0 3 1
A clear() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PHPCollections\Collections;
6
7
use Countable;
8
use PHPCollections\Checker;
9
10
/**
11
 * A generic LIFO Stack.
12
 */
13
class Stack implements Countable
14
{
15
    /**
16
     * The data container.
17
     *
18
     * @var array
19
     */
20
    private $data;
21
22
    /**
23
     * The type of the values
24
     * for this Stack.
25
     *
26
     * @var mixed
27
     */
28
    private $type;
29
30
    /**
31
     * Creates a new Stack.
32
     *
33
     * @param string $type
34
     */
35 7
    public function __construct(string $type)
36
    {
37 7
        $this->data = [];
38 7
        $this->type = $type;
39 7
    }
40
41
    /**
42
     * Clears the data values.
43
     *
44
     * @return void
45
     */
46 1
    public function clear(): void
47
    {
48 1
        $this->data = [];
49 1
    }
50
51
    /**
52
     * Returns the length of the Stack.
53
     *
54
     * @return int
55
     */
56 6
    public function count(): int
57
    {
58 6
        return count($this->data);
59
    }
60
61
    /**
62
     * Checks if the stack is empty.
63
     *
64
     * @return bool
65
     */
66 2
    public function isEmpty(): bool
67
    {
68 2
        return $this->count() === 0;
69
    }
70
71
    /**
72
     * Gets the element at
73
     * the end of the Stack.
74
     *
75
     * @return mixed
76
     */
77 3
    public function peek()
78
    {
79 3
        return $this->data[$this->count() - 1];
80
    }
81
82
    /**
83
     * Pops the element at
84
     * the end of the stack.
85
     *
86
     * @return mixed
87
     */
88 1
    public function pop()
89
    {
90 1
        return array_pop($this->data);
91
    }
92
93
    /**
94
     * Adds a new element at
95
     * the end of the Stack.
96
     *
97
     * @param mixed $value
98
     *
99
     * @throws \InvalidArgumentException
100
     *
101
     * @return mixed
102
     */
103 7
    public function push($value)
104
    {
105 7
        $message = sprintf(
106 7
            'The type specified for this collection is %s, you cannot pass a value of type %s',
107 7
            $this->type, gettype($value)
108
        );
109
110 7
        Checker::valueIsOfType($value, $this->type, $message);
111
112 7
        $this->data[] = $value;
113
114 7
        return $value;
115
    }
116
}
117