IntervalFunction::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 3
eloc 5
nc 3
nop 2
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