PlayerState   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 10
c 1
b 0
f 0
dl 0
loc 35
ccs 15
cts 15
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A resolvePlayerSaveFile() 0 5 1
A __construct() 0 5 1
A save() 0 5 1
A load() 0 10 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AardsGerds\Game\Infrastructure\Persistence;
6
7
use AardsGerds\Game\Player\Player;
8
9
final class PlayerState
10
{
11 11
    public function __construct(
12
        private NormalizePlayer $normalizePlayer,
13
        private DenormalizePlayer $denormalizePlayer,
14
        private string $savesLocation,
15 11
    ) {}
16
17 1
    public function save(Player $player): void
18
    {
19 1
        $playerNormalized = ($this->normalizePlayer)($player);
20
21 1
        file_put_contents($this->resolvePlayerSaveFile($player->getName()), json_encode($playerNormalized));
22 1
    }
23
24
    /**
25
     * @throws PlayerStateException
26
     */
27 2
    public function load(string $playerName): Player
28
    {
29 2
        if (!file_exists($fileName = $this->resolvePlayerSaveFile($playerName))) {
30 1
            throw PlayerStateException::notFound($fileName);
31
        }
32
33 1
        assert(is_readable($fileName));
34 1
        $playerNormalized = json_decode(file_get_contents($fileName) ?: '', true);
35
36 1
        return ($this->denormalizePlayer)($playerNormalized);
37
    }
38
39 2
    private function resolvePlayerSaveFile(string $playerName): string
40
    {
41 2
        $playerSaveFile = str_replace(' ', '_', strtolower($playerName));
42
43 2
        return "{$this->savesLocation}/{$playerSaveFile}.json";
44
    }
45
}
46