Passed
Push — main ( 190e00...182afb )
by Daniel
03:41
created

RandomFavoriteSongsApplication::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 0
c 1
b 0
f 0
dl 0
loc 4
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
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\ResultItemFactoryInterface;
11
use Uxmp\Core\Component\Session\SessionValidatorMiddleware;
12
use Uxmp\Core\Orm\Model\UserInterface;
13
use Uxmp\Core\Orm\Repository\SongRepositoryInterface;
14
15
/**
16
 * Builds a result with random favorite songs of a user
17
 */
18
final class RandomFavoriteSongsApplication extends AbstractApiApplication
19
{
20
    private const DEFAULT_LIMIT = 100;
21
22 1
    public function __construct(
23
        private SongRepositoryInterface $songRepository,
24
        private ResultItemFactoryInterface $resultItemFactory,
25
    ) {
26 1
    }
27
28 1
    protected function run(
29
        ServerRequestInterface $request,
30
        ResponseInterface $response,
31
        array $args
32
    ): ResponseInterface {
33 1
        $list = [];
34
35 1
        $limit = (int) ($args['limit'] ?? self::DEFAULT_LIMIT);
36
37
        /** @var UserInterface $user */
38 1
        $user = $request->getAttribute(SessionValidatorMiddleware::USER);
39
40 1
        foreach ($this->songRepository->findFavorites($user) as $song) {
41 1
            $list[] = $this->resultItemFactory->createSongListItem(
42 1
                $song,
43 1
                $song->getDisc()->getAlbum()
44
            );
45
        }
46
47
        // @todo inefficient, but doctrine doesn't support RAND order natively
48 1
        shuffle($list);
49
50 1
        return $this->asJson(
51 1
            $response,
52 1
            ['items' => array_slice($list, 0, $limit)]
53
        );
54
    }
55
}
56