GridValidator::blocksAreValid()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 9
c 0
b 0
f 0
rs 10
cc 3
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace CoenMooij\Sudoku\Validator;
6
7
use CoenMooij\Sudoku\Puzzle\Grid;
8
9
class GridValidator
10
{
11
    public static function gridIsValid(Grid $grid): bool
12
    {
13
        return self::columnsAreValid($grid) && self::rowsAreValid($grid) && self::blocksAreValid($grid);
14
    }
15
16
    private static function rowsAreValid(Grid $grid): bool
17
    {
18
        for ($i = 0; $i < Grid::NUMBER_OF_ROWS; $i++) {
19
            $row = $grid->getRow($i);
20
            if (self::hasDuplicates($row)) {
21
                return false;
22
            }
23
        }
24
25
        return true;
26
    }
27
28
    private static function columnsAreValid(Grid $grid): bool
29
    {
30
        for ($i = 0; $i < Grid::NUMBER_OF_COLUMNS; $i++) {
31
            if (self::hasDuplicates($grid->getColumn($i))) {
32
                return false;
33
            }
34
        }
35
36
        return true;
37
    }
38
39
    private static function blocksAreValid(Grid $grid): bool
40
    {
41
        foreach ($grid->getBlocks() as $block) {
42
            if (self::hasDuplicates($block)) {
43
                return false;
44
            }
45
        }
46
47
        return true;
48
    }
49
50
    /**
51
     * @param int[] $values
52
     *
53
     * @return bool
54
     */
55
    private static function hasDuplicates(array $values): bool
56
    {
57
        $values = array_diff($values, [Grid::EMPTY_VALUE]);
58
59
        return count(array_count_values($values)) !== count($values);
60
    }
61
}
62