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

LinearFunction   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A fromTwoPoints() 0 11 2
A evaluate() 0 4 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