RandomFavoriteSongsApplication::run()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 24
ccs 12
cts 12
cp 1
rs 9.9332
cc 2
nc 2
nop 3
crap 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