RandomFavoriteSongsApplication   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
eloc 12
c 1
b 0
f 0
dl 0
loc 37
ccs 14
cts 14
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A run() 0 24 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Uxmp\Core\Api\Random;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Uxmp\Core\Api\AbstractApiApplication;
10
use Uxmp\Core\Api\Lib\Message\JsonEnabledResponseInterface;
11
use Uxmp\Core\Api\Lib\Middleware\SessionValidatorMiddleware;
12
use Uxmp\Core\Api\Lib\ResultItemFactoryInterface;
13
use Uxmp\Core\Orm\Model\UserInterface;
14
use Uxmp\Core\Orm\Repository\SongRepositoryInterface;
15
16
/**
17
 * Builds a result with random favorite songs of a user
18
 */
19
final class RandomFavoriteSongsApplication extends AbstractApiApplication
20
{
21
    /**
22
     * @var int
23
     */
24
    private const DEFAULT_LIMIT = 100;
25
26 1
    public function __construct(
27
        private readonly SongRepositoryInterface $songRepository,
28
        private readonly ResultItemFactoryInterface $resultItemFactory,
29
    ) {
30 1
    }
31
32 1
    protected function run(
33
        ServerRequestInterface $request,
34
        JsonEnabledResponseInterface $response,
35
        array $args
36
    ): ResponseInterface {
37 1
        $list = [];
38
39 1
        $limit = (int) ($args['limit'] ?? self::DEFAULT_LIMIT);
40
41
        /** @var UserInterface $user */
42 1
        $user = $request->getAttribute(SessionValidatorMiddleware::USER);
43
44 1
        foreach ($this->songRepository->findFavorites($user) as $song) {
45 1
            $list[] = $this->resultItemFactory->createSongListItem(
46 1
                $song,
47 1
                $song->getDisc()->getAlbum()
48 1
            );
49
        }
50
51
        // @todo inefficient, but doctrine doesn't support RAND order natively
52 1
        shuffle($list);
53
54 1
        return $response->withJson(
55 1
            ['items' => array_slice($list, 0, $limit)]
56 1
        );
57
    }
58
}
59