Completed
Push — master ( ba922a...9c7654 )
by Milos
03:24
created

LinearFunction::evaluate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Cgi\Calc\Func;
4
5
use Cgi\Calc\FunctionInterface;
6
use Cgi\Calc\Point;
7
8
class LinearFunction implements FunctionInterface
9
{
10
    /** @var float */
11
    private $k;
12
13
    /** @var float */
14
    private $n;
15
16
    /**
17
     * @param float $k
18
     * @param float $n
19
     */
20
    public function __construct($k, $n)
21
    {
22
        $this->k = $k;
23
        $this->n = $n;
24
    }
25
26
    /**
27
     * @param Point $a
28
     * @param Point $b
29
     *
30
     * @return LinearFunction
31
     *
32
     * @throws \RuntimeException When $a and $b points have same x
33
     */
34
    public static function fromTwoPoints(Point $a, Point $b)
35
    {
36
        if ($a->getX() === $b->getX()) {
37
            throw new \RuntimeException('Line can be defined only by two points with different X');
38
        }
39
40
        $k = ($a->getY() - $b->getY()) / ($a->getX() - $b->getX());
41
        $n = $a->getY() - $k * $a->getX();
42
43
        return new LinearFunction($k, $n);
44
    }
45
46
    /**
47
     * @param float $x
48
     *
49
     * @return float
50
     */
51
    public function evaluate($x)
52
    {
53
        return $this->k * $x + $this->n;
54
    }
55
}
56