IterationLimiter   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 39
rs 10
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A nextCandidate() 0 3 1
A limitingTo() 0 3 1
A __construct() 0 4 1
A isOngoing() 0 3 1
A consider() 0 9 3
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