summaryrefslogtreecommitdiff
path: root/src/HistoryStorage.php
blob: 30d9aced7279dded7d65d369e7eade71dea77a16 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php

declare(strict_types=1);

namespace TCB;

final class HistoryStorage
{
    public function __construct(
        public array $playlists,
        public array $history,
        private readonly string $filename,
    ) {}

    static public function load(string $filename): self
    {
        $storage = is_readable($filename)
            ? json_decode(file_get_contents($filename), true)
            : [];

        return new self(
            playlists: $storage['playlists'] ?? [],
            history: $storage['history'] ?? [],
            filename: $filename,
        );
    }

    public function save(): void
    {
        file_put_contents($this->filename, json_encode($this, JSON_PRETTY_PRINT));
    }

    public function saveSong(array $song): void
    {
        $this->history[$song['id']] = [
            'timestamp' => time(),
            'details' => $song,
        ];
        $this->save();
    }
}