BoundaryCondition::test()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 9
cts 9
cp 1
rs 9.6333
c 0
b 0
f 0
cc 3
nc 4
nop 1
crap 3
1
<?php
2
3
/**
4
 * (c) 2018 Douglas Reith.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
declare(strict_types=1);
10
11
namespace Reith\ToyRobot\Domain\Space;
12
13
use Assert\Assert;
14
use Reith\ToyRobot\Domain\Space\Exception\BoundaryTestException;
15
16
class BoundaryCondition
17
{
18
    private $bounds;
19
20
    /**
21
     * @param int $bounds
22
     */
23 33
    private function __construct(int $bounds)
24
    {
25 33
        $this->bounds = $bounds;
26 33
    }
27
28
    /**
29
     * @param int $bounds
30
     *
31
     * @throws \Assert\AssertionFailedException
32
     */
33 33
    public static function create(int $bounds): BoundaryCondition
34
    {
35
        // Boundary conditions must be greater than zero
36 33
        Assert::that($bounds)->greaterThan(0);
37
38 33
        return new self($bounds);
39
    }
40
41
    /**
42
     * @param int $value
43
     *
44
     * @return bool
45
     *
46
     * @throws BoundaryTestException
47
     */
48 25
    public function test(int $value): bool
49
    {
50 25
        $boundary = 1 / $this->bounds;
51
52 25
        $positionDenominator = $this->bounds - $value;
53
54
        // Div by zero
55 25
        if (0 === $positionDenominator) {
56 3
            $this->throwBoundaryTestException($value);
57
        }
58
59 23
        $position = 1 / $positionDenominator;
60
61 23
        if ($position < $boundary) {
62 5
            $this->throwBoundaryTestException($value);
63
        }
64
65 20
        return true;
66
    }
67
68
    /**
69
     * @param int $value
70
     *
71
     * @throws BoundaryTestException
72
     */
73 8
    private function throwBoundaryTestException(int $value): void
74
    {
75 8
        $msg = sprintf('[%d] is outside the bounds of [0..%d]', $value, $this->bounds - 1);
76
77 8
        throw new BoundaryTestException($msg);
78
    }
79
}
80