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

DiscCache::retrieve()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 35
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 35
ccs 19
cts 19
cp 1
rs 9.6666
c 0
b 0
f 0
cc 3
nc 3
nop 3
crap 3
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\Disc\DiscLengthUpdaterInterface;
9
use Uxmp\Core\Component\Event\EventHandlerInterface;
10
use Uxmp\Core\Component\Tag\Container\AudioFileInterface;
11
use Uxmp\Core\Orm\Model\CatalogInterface;
12
use Uxmp\Core\Orm\Model\DiscInterface;
13
use Uxmp\Core\Orm\Repository\DiscRepositoryInterface;
14
15
final class DiscCache implements DiscCacheInterface
16
{
17
    /** @var array<string, DiscInterface> */
18
    private array $cache = [];
19
20 2
    public function __construct(
21
        private readonly DiscRepositoryInterface $discRepository,
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 AlbumCacheInterface $albumCache,
23
        private readonly EventHandlerInterface $eventHandler
24
    ) {
25
    }
26
27 2
    public function retrieve(
28
        CatalogInterface $catalog,
29
        AudioFileInterface $audioFile,
30
        array $analysisResult
31
    ): DiscInterface {
32 2
        $discMbId = $audioFile->getDiscMbid();
33 2
        $discNumber = $audioFile->getDiscNumber();
34 2
        $album = $this->albumCache->retrieve($catalog, $audioFile, $analysisResult);
35
36 2
        $cacheKey = sprintf('%s_%d', $discMbId, $discNumber);
37
38 2
        $disc = $this->cache[$cacheKey] ?? null;
39 2
        if ($disc === null) {
40 2
            $disc = $this->discRepository->findUniqueDisc($discMbId, $discNumber);
41 2
            if ($disc === null) {
42 1
                $disc = $this->discRepository->prototype();
43
            }
44
45 2
            $disc->setMbid($discMbId)
46 2
                ->setAlbum($album)
47 2
                ->setNumber($discNumber)
48
            ;
49
50 2
            $this->discRepository->save($disc);
51
52 2
            $this->cache[$cacheKey] = $disc;
53
        }
54
55 2
        $this->eventHandler->fire(
56 2
            static function (ContainerInterface $c) use ($disc): void {
57 2
                $c->get(DiscLengthUpdaterInterface::class)->update($disc);
58
            }
59
        );
60
61 2
        return $disc;
62
    }
63
}
64