iTunesService::getKey()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace App\Services;
4
5
use Exception;
6
7
class iTunesService extends AbstractApiClient implements ApiConsumerInterface
8
{
9
    /**
10
     * Determines whether to use iTunes services.
11
     */
12 132
    public function used(): bool
13
    {
14 132
        return (bool) config('koel.itunes.enabled');
15
    }
16
17
    /**
18
     * Search for a track on iTunes Store with the given information and get its URL.
19
     *
20
     * @param string $term   The main query string (should be the track's name)
21
     * @param string $album  The album's name, if available
22
     * @param string $artist The artist's name, if available
23
     */
24 3
    public function getTrackUrl(string $term, string $album = '', string $artist = ''): ?string
25
    {
26
        try {
27 3
            return $this->cache->remember(
28 3
                md5("itunes_track_url_{$term}{$album}{$artist}"),
29 3
                24 * 60 * 7,
30
                function () use ($term, $album, $artist): ?string {
31
                    $params = [
32 3
                        'term' => $term.($album ? " $album" : '').($artist ? " $artist" : ''),
33 3
                        'media' => 'music',
34 3
                        'entity' => 'song',
35 3
                        'limit' => 1,
36
                    ];
37
38 3
                    $response = json_decode(
39 3
                        $this->getClient()->get($this->getEndpoint(), ['query' => $params])->getBody()
40
                    );
41
42 3
                    if (!$response->resultCount) {
43
                        return null;
44
                    }
45
46 3
                    $trackUrl = $response->results[0]->trackViewUrl;
47 3
                    $connector = parse_url($trackUrl, PHP_URL_QUERY) ? '&' : '?';
48 3
                    $trackUrl .= "{$connector}at=".config('koel.itunes.affiliate_id');
49
50 3
                    return $trackUrl;
51 3
                }
52
            );
53
        } catch (Exception $e) {
54
            $this->logger->error($e);
55
56
            return null;
57
        }
58
    }
59
60
    public function getKey(): ?string
61
    {
62
        return null;
63
    }
64
65
    public function getSecret(): ?string
66
    {
67
        return null;
68
    }
69
70 3
    public function getEndpoint(): ?string
71
    {
72 3
        return config('koel.itunes.endpoint');
73
    }
74
}
75