Completed
Push — master ( e0916e...38b230 )
by Rudi
05:33
created

Capacity   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 0
dl 0
loc 52
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A capacity() 0 4 1
A allocate() 0 4 1
increaseCapacity() 0 1 ?
A adjustCapacity() 0 13 3
1
<?php
2
namespace Ds\Traits;
3
4
/**
5
 * Capacity
6
 *
7
 * @package Ds\Traits
8
 */
9
trait Capacity
10
{
11
    /**
12
     * @var int
13
     */
14
    private $capacity = self::MIN_CAPACITY;
15
16
    /**
17
     * Returns the current capacity.
18
     *
19
     * @return int
20
     */
21
    public function capacity(): int
22
    {
23
        return $this->capacity;
24
    }
25
26
    /**
27
     * Ensures that enough memory is allocated for a specified capacity. This
28
     * potentially reduces the number of reallocations as the size increases.
29
     *
30
     * @param int $capacity The number of values for which capacity should be
31
     *                      allocated. Capacity will stay the same if this value
32
     *                      is less than or equal to the current capacity.
33
     */
34
    public function allocate(int $capacity)
35
    {
36
        $this->capacity = max($capacity, $this->capacity);
37
    }
38
39
    /**
40
     * Increase Capacity
41
     */
42
    abstract protected function increaseCapacity();
43
44
    /**
45
     * Adjust Capacity
46
     */
47
    private function adjustCapacity()
48
    {
49
        $size = count($this);
50
51
        if ($size >= $this->capacity) {
52
            $this->increaseCapacity();
53
54
        } else {
55
            if ($size < $this->capacity / 4) {
56
                $this->capacity = max(self::MIN_CAPACITY, $this->capacity / 2);
57
            }
58
        }
59
    }
60
}
61