Passed
Push — main ( d28073...f4e9d2 )
by Jesse
01:39
created

PuzzleStatesToFileRenderer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 41
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A log() 0 3 1
A __construct() 0 6 1
A render() 0 10 2
A fromFilenameAndSeparator() 0 6 1
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\PuzzleSolver\Renderer;
4
5
use Stratadox\PuzzleSolver\Solution;
6
use Stratadox\PuzzleSolver\SolutionRenderer;
7
use function assert;
8
use function fopen;
9
use function fwrite;
10
use function is_resource;
11
use function usleep;
12
13
/**
14
 * PuzzleStates-to-file Renderer
15
 *
16
 * Renders each of the in-between states on the path that led to the final
17
 * solution to a file.
18
 *
19
 * @author Stratadox
20
 */
21
final class PuzzleStatesToFileRenderer implements SolutionRenderer
22
{
23
    /** @var resource */
24
    private $output;
25
    /** @var string */
26
    private $separator;
27
    /** @var int */
28
    private $timeout;
29
30
    private function __construct($outputStream, string $separator, int $timeout)
31
    {
32
        $this->output = $outputStream;
33
        $this->separator = $separator;
34
        $this->timeout = $timeout;
35
        assert(is_resource($outputStream));
36
    }
37
38
    public static function fromFilenameAndSeparator(
39
        string $fileName,
40
        string $separator,
41
        int $timeout = 0
42
    ): SolutionRenderer {
43
        return new self(fopen($fileName, 'wb'), $separator, $timeout);
44
    }
45
46
    public function render(Solution $solution): void
47
    {
48
        $puzzle = $solution->original();
49
        $this->log($puzzle->representation());
50
        usleep($this->timeout);
51
        foreach ($solution->moves() as $move) {
52
            $puzzle = $puzzle->afterMaking($move);
53
            $this->log($this->separator);
54
            $this->log($puzzle->representation());
55
            usleep($this->timeout);
56
        }
57
    }
58
59
    private function log(string $entry): void
60
    {
61
        fwrite($this->output, $entry);
62
    }
63
}
64