IterationLimiter::consider()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
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 9
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\PuzzleSolver\SearchStrategy;
4
5
use Stratadox\PuzzleSolver\Puzzle;
6
7
/**
8
 * Iteration Limiter
9
 *
10
 * Iteration Limiter aborts the search when the amount of considered candidates
11
 * exceeds a set limit.
12
 *
13
 * @author Stratadox
14
 */
15
final class IterationLimiter implements SearchStrategy
16
{
17
    /** @var SearchStrategy */
18
    private $strategy;
19
    /** @var int */
20
    private $limit;
21
    /** @var int */
22
    private $current = 0;
23
24
    private function __construct(SearchStrategy $strategy, int $limit)
25
    {
26
        $this->strategy = $strategy;
27
        $this->limit = $limit;
28
    }
29
30
    public static function limitingTo(int $limit, SearchStrategy $strategy): self
31
    {
32
        return new self($strategy, $limit);
33
    }
34
35
    public function isOngoing(): bool
36
    {
37
        return $this->strategy->isOngoing();
38
    }
39
40
    public function consider(Puzzle $puzzle): bool
41
    {
42
        if (!$this->strategy->consider($puzzle)) {
43
            return false;
44
        }
45
        if (++$this->current > $this->limit) {
46
            throw OutOfIterations::exceeded($this->limit);
47
        }
48
        return true;
49
    }
50
51
    public function nextCandidate(): Puzzle
52
    {
53
        return $this->strategy->nextCandidate();
54
    }
55
}
56