GridSerializer::deserialize()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 15
c 0
b 0
f 0
rs 9.9666
cc 4
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace CoenMooij\Sudoku\Serializer;
6
7
use CoenMooij\Sudoku\Puzzle\Grid;
8
use CoenMooij\Sudoku\Puzzle\Location;
9
use LengthException;
10
11
class GridSerializer
12
{
13
    public static function serialize(Grid $grid): string
14
    {
15
        $string = '';
16
        for ($i = 0; $i < Grid::NUMBER_OF_LOCATIONS; $i++) {
17
            $string .= (string) $grid->get(self::getLocationByIndex($i));
18
        }
19
20
        return $string;
21
    }
22
23
    public static function deserialize(string $string): Grid
24
    {
25
        if (strlen($string) !== Grid::NUMBER_OF_LOCATIONS) {
26
            throw new LengthException();
27
        }
28
        $grid = new Grid();
29
        for ($i = 0; $i < Grid::NUMBER_OF_LOCATIONS; $i++) {
30
            $location = self::getLocationByIndex($i);
31
            $value = (int) $string[$i];
32
            if (Grid::valueIsValid($value)) {
33
                $grid->set($location, $value);
34
            }
35
        }
36
37
        return $grid;
38
    }
39
40
    public static function getLocationByIndex(int $index): Location
41
    {
42
        $row = (int) floor($index / Grid::NUMBER_OF_COLUMNS);
43
        $column = $index % Grid::NUMBER_OF_ROWS;
44
45
        return new Location($row, $column);
46
    }
47
}
48