Passed
Branch main (339f6d)
by Cornelia
17:44 queued 07:47
created

HighscoreService   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 11
c 1
b 0
f 0
dl 0
loc 44
ccs 12
cts 12
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A addScore() 0 8 1
A __construct() 0 3 1
A getHighscores() 0 7 2
1
<?php
2
3
namespace App\Service;
4
5
/**
6
 * Tjänst för att hantera highscore-listor.
7
 * Läser från och skriver till en JSON-fil som lagrar topp 10 resultat.
8
 */
9
class HighscoreService
10
{
11
    /** @var string Sökvägen till JSON-filen som lagrar highscores */
12
    private string $file;
13
14
    /**
15
     * Konstruktor.
16
     *
17
     * @param string $projectDir Projektets rotkatalog (används för att hitta/highscores.json)
18
     */
19 3
    public function __construct(string $projectDir)
20
    {
21 3
        $this->file = $projectDir.'/var/highscores.json';
22
    }
23
24
    /**
25
     * Returnerar en lista med highscores.
26
     *
27
     * @return array En array med highscore-poster, varje post innehåller 'name' och 'score'
28
     */
29 3
    public function getHighscores(): array
30
    {
31 3
        if (!file_exists($this->file)) {
32 3
            return [];
33
        }
34
35 2
        return json_decode(file_get_contents($this->file), true) ?? [];
36
    }
37
38
    /**
39
     * Lägger till en ny score och uppdaterar filen.
40
     * Endast de 10 bästa resultaten sparas.
41
     *
42
     * @param string $name  Namn på spelaren
43
     * @param int    $score Poäng
44
     */
45 2
    public function addScore(string $name, int $score): void
46
    {
47 2
        $scores = $this->getHighscores();
48 2
        $scores[] = ['name' => $name, 'score' => $score];
49 2
        usort($scores, fn ($a, $b) => $b['score'] <=> $a['score']);
50 2
        $scores = array_slice($scores, 0, 10);
51
52 2
        file_put_contents($this->file, json_encode($scores, JSON_PRETTY_PRINT));
53
    }
54
}
55