Passed
Push — main ( f4e9d2...4a4379 )
by Jesse
01:41
created

MazeFactory::default()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\PuzzleSolver\Puzzle\Maze;
4
5
use Stratadox\PuzzleSolver\Puzzle;
6
use Stratadox\PuzzleSolver\PuzzleFactory;
7
use function assert;
8
use function preg_split;
9
use function str_split;
10
11
final class MazeFactory implements PuzzleFactory
12
{
13
    /** @var string */
14
    private $wall;
15
    /** @var string */
16
    private $goal;
17
    /** @var string */
18
    private $hero;
19
20
    public function __construct(string $wall, string $goal, string $hero)
21
    {
22
        $this->wall = $wall;
23
        $this->goal = $goal;
24
        $this->hero = $hero;
25
    }
26
27
    public static function make(): PuzzleFactory
28
    {
29
        return new self('#', 'X', 'H');
30
    }
31
32
    public function fromString(string $maze): Puzzle
33
    {
34
        $walls = [];
35
        $goal = null;
36
        $hero = null;
37
        foreach (preg_split("/(\n)|(\r)/", $maze) as $y => $line) {
38
            foreach (str_split($line) as $x => $char) {
39
                if ($char === $this->wall) {
40
                    $walls[] = new Wall($x, $y);
41
                }
42
                if ($char === $this->goal) {
43
                    $goal = new Goal($x, $y);
44
                }
45
                if ($char === $this->hero) {
46
                    $hero = new Hero($x, $y);
47
                }
48
            }
49
        }
50
        assert(null !== $goal);
51
        assert(null !== $hero);
52
        return MazePuzzle::withHeroAndMaze($hero, Maze::withGoalAndWalls($goal, ...$walls));
53
    }
54
}
55