Passed
Push — main ( f4e9d2...4a4379 )
by Jesse
01:41
created

NetworkPuzzleFactory   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 24
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A fromString() 0 17 3
A make() 0 3 1
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\PuzzleSolver\Puzzle\NetworkNavigation;
4
5
use Stratadox\PuzzleSolver\InvalidFormat;
6
use Stratadox\PuzzleSolver\Puzzle;
7
use Stratadox\PuzzleSolver\PuzzleFactory;
8
use function json_decode;
9
use function json_last_error;
10
use function json_last_error_msg;
11
use const JSON_ERROR_NONE;
12
13
final class NetworkPuzzleFactory implements PuzzleFactory
14
{
15
    public static function make(): PuzzleFactory
16
    {
17
        return new self();
18
    }
19
20
    public function fromString(string $puzzle): Puzzle
21
    {
22
        $network = [];
23
        $data = json_decode($puzzle, true);
24
25
        if (json_last_error() !== JSON_ERROR_NONE) {
26
            throw InvalidFormat::couldNotLoad('network', $puzzle, json_last_error_msg());
27
        }
28
29
        foreach ($data['edges'] as $edge) {
30
            $network[$edge['from']][$edge['to']] = $edge['cost'];
31
        }
32
33
        return NetworkNavigationPuzzle::fromArrayAndStartAndGoal(
34
            $network,
35
            $data['start'],
36
            $data['goal']
37
        );
38
    }
39
}
40