Test Setup Failed
Push — master ( 077d1d...f344b4 )
by Phan
04:03
created

iTunes::getTrackUrl()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 36
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 36
rs 8.439
c 0
b 0
f 0
cc 6
eloc 22
nc 2
nop 3
1
<?php
2
3
namespace App\Services;
4
5
use Cache;
6
use Exception;
7
use GuzzleHttp\Client;
8
use Log;
9
10
class iTunes
11
{
12
    /**
13
     * @var Client
14
     */
15
    protected $client;
16
17
    /**
18
     * @var string
19
     */
20
    protected $endPoint = 'https://itunes.apple.com/search';
21
22
    /**
23
     * iTunes constructor.
24
     *
25
     * @param Client|null $client
26
     */
27
    public function __construct(Client $client = null)
28
    {
29
        $this->client = $client ?: new Client();
30
    }
31
32
    /**
33
     * Determines whether to use iTunes services.
34
     *
35
     * @return bool
36
     */
37
    public function used()
38
    {
39
        return (bool) config('koel.itunes.enabled');
40
    }
41
42
    /**
43
     * Search for a track on iTunes Store with the given information and get its URL.
44
     *
45
     * @param $term string The main query string (should be the track's name)
46
     * @param $album string The album's name, if available
47
     * @param $artist string The artist's name, if available
48
     *
49
     * @return string|false
50
     */
51
    public function getTrackUrl($term, $album = '', $artist = '')
52
    {
53
        try {
54
            return Cache::remember(md5("itunes_track_url_{$term}{$album}{$artist}"), 24 * 60 * 7, 
55
                function () use ($term, $album, $artist) {
56
                    $params = [
57
                        'term' => $term.($album ? " $album" : '').($artist ? " $artist" : ''),
58
                        'media' => 'music',
59
                        'entity' => 'song',
60
                        'limit' => 1,
61
                    ];
62
63
                    $response = (string) $this->client->get($this->endPoint, ['query' => $params])->getBody();
64
                    $response = json_decode($response);
65
66
                    if (!$response->resultCount) {
67
                        return false;
68
                    }
69
70
                    $trackUrl = $response->results[0]->trackViewUrl;
71
72
                    if (parse_url($trackUrl, PHP_URL_QUERY)) {
73
                        $trackUrl .= '&at='.config('koel.itunes.affiliate_id');
74
                    } else {
75
                        $trackUrl .= '?at='.config('koel.itunes.affiliate_id');
76
                    }
77
78
                    return $trackUrl;
79
                }
80
            );
81
        } catch (Exception $e) {
82
            Log::error($e);
83
84
            return false;
85
        }
86
    }
87
}
88