Slide   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 34
c 1
b 0
f 0
dl 0
loc 72
rs 10
wmc 7

7 Methods

Rating   Name   Duplication   Size   Complexity  
A right() 0 3 1
A down() 0 3 1
A __construct() 0 10 1
A left() 0 3 1
A applyTo() 0 8 1
A __toString() 0 3 1
A up() 0 3 1
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\PuzzleSolver\Puzzle\SlidingPuzzle;
4
5
use Stratadox\PuzzleSolver\Move;
6
7
final class Slide implements Move
8
{
9
    private const UP = 'up';
10
    private const DOWN = 'down';
11
    private const LEFT = 'left';
12
    private const RIGHT = 'right';
13
    private const ADD_ROW = [
14
        Slide::UP => -1,
15
        Slide::DOWN => 1,
16
        Slide::LEFT => 0,
17
        Slide::RIGHT => 0,
18
    ];
19
    private const ADD_COL = [
20
        Slide::UP => 0,
21
        Slide::DOWN => 0,
22
        Slide::LEFT => -1,
23
        Slide::RIGHT => 1,
24
    ];
25
    /** @var int */
26
    private $piece;
27
    /** @var string */
28
    private $direction;
29
    /** @var int */
30
    private $row;
31
    /** @var int */
32
    private $col;
33
34
    private function __construct(
35
        int $piece,
36
        string $direction,
37
        int $row,
38
        int $col
39
    ) {
40
        $this->piece = $piece;
41
        $this->direction = $direction;
42
        $this->row = $row;
43
        $this->col = $col;
44
    }
45
46
    public static function up(array $pieces, int $row, int $col): self
47
    {
48
        return new self($pieces[$row][$col], Slide::UP, $row, $col);
49
    }
50
51
    public static function down(array $pieces, int $row, int $col): self
52
    {
53
        return new self($pieces[$row][$col], Slide::DOWN, $row, $col);
54
    }
55
56
    public static function left(array $pieces, int $row, int $col): self
57
    {
58
        return new self($pieces[$row][$col], Slide::LEFT, $row, $col);
59
    }
60
61
    public static function right(array $pieces, int $row, int $col): self
62
    {
63
        return new self($pieces[$row][$col], Slide::RIGHT, $row, $col);
64
    }
65
66
    public function applyTo(array $pieces): array
67
    {
68
        $otherR = $this->row + self::ADD_ROW[$this->direction];
69
        $otherC = $this->col + self::ADD_COL[$this->direction];
70
        $swap = $pieces[$otherR][$otherC];
71
        $pieces[$otherR][$otherC] = $pieces[$this->row][$this->col];
72
        $pieces[$this->row][$this->col] = $swap;
73
        return $pieces;
74
    }
75
76
    public function __toString(): string
77
    {
78
        return "Slide {$this->piece} {$this->direction}";
79
    }
80
}
81