PlayerState::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 5
ccs 2
cts 2
cp 1
crap 1
rs 10
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