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

MovesToFileRenderer::render()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 8
rs 10
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
 * Moves-to-file Renderer
15
 *
16
 * Renders each of the moves that led to the final solution state to a file.
17
 *
18
 * @author Stratadox
19
 */
20
final class MovesToFileRenderer implements SolutionRenderer
21
{
22
    /** @var resource */
23
    private $output;
24
    /** @var string */
25
    private $separator;
26
    /** @var int */
27
    private $timeout;
28
29
    private function __construct($outputStream, string $separator, int $timeout)
30
    {
31
        $this->output = $outputStream;
32
        $this->separator = $separator;
33
        $this->timeout = $timeout;
34
        assert(is_resource($outputStream));
35
    }
36
37
    public static function fromFilenameAndSeparator(
38
        string $fileName,
39
        string $separator,
40
        int $timeout = 0
41
    ): SolutionRenderer {
42
        return new self(fopen($fileName, 'wb'), $separator, $timeout);
43
    }
44
45
    public function render(Solution $solution): void
46
    {
47
        foreach ($solution->moves() as $i => $move) {
48
            if ($i) {
49
                $this->log($this->separator);
50
            }
51
            $this->log((string) $move);
52
            usleep($this->timeout);
53
        }
54
    }
55
56
    private function log(string $entry): void
57
    {
58
        fwrite($this->output, $entry);
59
    }
60
}
61