IntervalFunction   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
c 1
b 0
f 0
lcom 1
cbo 4
dl 0
loc 54
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 3
B evaluate() 0 26 6
1
<?php
2
3
/*
4
 * This file is part of the CGI-Calc package.
5
 *
6
 * (c) Milos Tomic <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Cgi\Calc\Func;
13
14
use Cgi\Calc\FunctionInterface;
15
use Cgi\Calc\Point\Path;
16
use Cgi\Calc\Point;
17
18
class IntervalFunction implements FunctionInterface
19
{
20
    /** @var Path */
21
    private $path;
22
23
    /** @var bool */
24
    private $extrapolate;
25
26
    /**
27
     * @param Path $path
28
     * @param bool $extrapolate
29
     */
30
    public function __construct(Path $path, $extrapolate = true)
31
    {
32
        if (false === $path->isMonotonouslyIncreasingX()) {
33
            throw new \InvalidArgumentException('Path must be monotony increasing by X');
34
        }
35
36
        $this->path = $path;
37
        $this->extrapolate = $extrapolate ? true : false;
38
    }
39
40
    /**
41
     * @param float $x
42
     *
43
     * @return float|null
44
     */
45
    public function evaluate($x)
46
    {
47
        $nowPoint = new Point($x, 0);
48
49
        $containingLine = null;
50
        foreach ($this->path->getLineIterator() as $line) {
51
            if ($nowPoint->betweenX($line->getStartPoint(), $line->getEndPoint())) {
52
                $containingLine = $line;
53
                break;
54
            }
55
        }
56
57
        if (null === $containingLine) {
58
            if (false === $this->extrapolate) {
59
                return null;
60
            }
61
62
            if ($this->path->firstPoint()->getX() > $x) {
63
                $containingLine = $this->path->firstLine();
64
            } else {
65
                $containingLine = $this->path->lastLine();
66
            }
67
        }
68
69
        return $containingLine->getLinearFunction()->evaluate($x);
70
    }
71
}
72