Passed
Push — main ( 1d1c5b...83bc52 )
by Daniel
04:23
created

AlbumCache::retrieve()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 34
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 19
c 0
b 0
f 0
dl 0
loc 34
ccs 0
cts 20
cp 0
rs 9.6333
cc 3
nc 3
nop 3
crap 12
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Uxmp\Core\Component\Catalog\Scanner;
6
7
use Psr\Container\ContainerInterface;
8
use Uxmp\Core\Component\Album\AlbumCoverUpdaterInterface;
9
use Uxmp\Core\Component\Event\EventHandlerInterface;
10
use Uxmp\Core\Component\Tag\Container\AudioFileInterface;
11
use Uxmp\Core\Orm\Model\AlbumInterface;
12
use Uxmp\Core\Orm\Model\CatalogInterface;
13
use Uxmp\Core\Orm\Repository\AlbumRepositoryInterface;
14
15
final class AlbumCache implements AlbumCacheInterface
16
{
17
    /** @var array<string, AlbumInterface> */
18
    private array $cache = [];
19
20
    public function __construct(
21
        private readonly AlbumRepositoryInterface $albumRepository,
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting T_VARIABLE on line 21 at column 25
Loading history...
22
        private readonly ArtistCacheInterface $artistCache,
23
        private readonly EventHandlerInterface $eventHandler
24
    ) {
25
    }
26
27
    public function retrieve(
28
        CatalogInterface $catalog,
29
        AudioFileInterface $audioFile,
30
        array $analysisResult
31
    ): AlbumInterface {
32
        $albumMbid = $audioFile->getAlbumMbid();
33
34
        $album = $this->cache[$albumMbid] ?? null;
35
        if ($album === null) {
36
            $album = $this->albumRepository->findByMbId($albumMbid);
37
            if ($album === null) {
38
                $artist = $this->artistCache->retrieve($audioFile);
39
40
                $album = $this->albumRepository->prototype()
41
                    ->setTitle($audioFile->getAlbumTitle())
42
                    ->setArtist($artist)
43
                    ->setMbid($albumMbid)
44
                    ->setCatalog($catalog)
45
                    ->setLastModified(new \DateTime())
46
                ;
47
                $this->albumRepository->save($album);
48
49
                $artist->addAlbum($album);
50
            }
51
            $this->eventHandler->fire(
52
                static function (ContainerInterface $c) use ($album, $analysisResult): void {
53
                    $c->get(AlbumCoverUpdaterInterface::class)->update($album, $analysisResult);
54
                }
55
            );
56
57
            $this->cache[$albumMbid] = $album;
58
        }
59
60
        return $album;
61
    }
62
}
63