MovingAverage::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Phperf\Pipeline\Vector;
4
5
6
class MovingAverage implements VectorProcessor
7
{
8
    private $size;
9
10
    private $values = [];
11
12
    public function __construct($size)
13
    {
14
        $this->size = $size;
15
    }
16
17
    /**
18
     * @param $value
19
     * @return int
20
     * @todo optimize for fixed size array
21
     */
22
    public function value($value)
23
    {
24
        $result = $value;
25
        $cnt = 1;
26
        foreach ($this->values as $prev) {
27
            $result += $prev;
28
            ++$cnt;
29
        }
30
        if ($cnt > 1) {
31
            $result /= $cnt;
32
        }
33
        if (count($this->values) >= $this->size) {
34
            array_shift($this->values);
35
        }
36
        $this->values[] = $value;
37
        return $result;
38
    }
39
}