iTunesService   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 71.43%

Importance

Changes 3
Bugs 3 Features 0
Metric Value
wmc 10
eloc 26
c 3
b 3
f 0
dl 0
loc 66
ccs 20
cts 28
cp 0.7143
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A used() 0 3 1
A getEndpoint() 0 3 1
B getTrackUrl() 0 33 6
A getKey() 0 3 1
A getSecret() 0 3 1
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