DebugLogger::log()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\PuzzleSolver\SearchStrategy;
4
5
use Stratadox\PuzzleSolver\Puzzle;
6
use function assert;
7
use function fwrite;
8
use function is_resource;
9
use function usleep;
10
11
/**
12
 * Debug logger
13
 *
14
 * Debug logger is a visualiser for the puzzle solver. Each time a new candidate
15
 * is taken under consideration, the debug logger logs it to the output stream.
16
 *
17
 * Decorator for other search strategies.
18
 *
19
 * @author Stratadox
20
 */
21
final class DebugLogger implements SearchStrategy
22
{
23
    /** @var SearchStrategy */
24
    private $search;
25
    /** @var int */
26
    private $timeout;
27
    /** @var string */
28
    private $separator;
29
    /** @var resource */
30
    private $output;
31
    /** @var bool */
32
    private $isFirst = true;
33
34
    public function __construct(
35
        SearchStrategy $search,
36
        int $timeout,
37
        string $separator,
38
        $outputStream
39
    ) {
40
        $this->search = $search;
41
        $this->timeout = $timeout;
42
        $this->separator = $separator;
43
        assert(is_resource($outputStream));
44
        $this->output = $outputStream;
45
    }
46
47
    public function isOngoing(): bool
48
    {
49
        return $this->search->isOngoing();
50
    }
51
52
    public function consider(Puzzle $puzzle): bool
53
    {
54
        return $this->search->consider($puzzle);
55
    }
56
57
    public function nextCandidate(): Puzzle
58
    {
59
        $puzzle = $this->search->nextCandidate();
60
        if (!$this->isFirst) {
61
            $this->log($this->separator);
62
        }
63
        $this->isFirst = false;
64
        $this->log($puzzle->representation());
65
        usleep($this->timeout);
66
        return $puzzle;
67
    }
68
69
    private function log(string $entry): void
70
    {
71
        fwrite($this->output, $entry);
72
    }
73
}
74