Test Setup Failed
Push — master ( 8c71bd...8904e4 )
by Phan
03:42
created

YouTube   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 4
dl 0
loc 74
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 3
A enabled() 0 4 1
A searchVideosRelatedToSong() 0 11 3
A search() 0 16 2
1
<?php
2
3
namespace App\Services;
4
5
use Cache;
6
use App\Models\Song;
7
use GuzzleHttp\Client;
8
9
class YouTube extends RESTfulService
10
{
11
    /**
12
     * Construct an instance of YouTube service.
13
     *
14
     * @param string      $key    The YouTube API key
15
     * @param Client|null $client The Guzzle HTTP client
16
     */
17
    public function __construct($key = null, Client $client = null)
18
    {
19
        parent::__construct(
20
            $key ?: config('koel.youtube.key'),
21
            null,
22
            'https://www.googleapis.com/youtube/v3',
23
            $client ?: new Client()
24
        );
25
    }
26
27
    /**
28
     * Determine if our application is using YouTube.
29
     *
30
     * @return bool
31
     */
32
    public function enabled()
33
    {
34
        return (bool) config('koel.youtube.key');
35
    }
36
37
    /**
38
     * Search for YouTube videos related to a song.
39
     *
40
     * @param Song   $song
41
     * @param string $pageToken
42
     *
43
     * @return object|false
44
     */
45
    public function searchVideosRelatedToSong(Song $song, $pageToken = '')
46
    {
47
        $q = $song->title;
48
49
        // If the artist is worth noticing, include them into the search.
50
        if (!$song->artist->is_unknown && !$song->artist->is_various) {
51
            $q .= " {$song->artist->name}";
52
        }
53
54
        return $this->search($q, $pageToken);
55
    }
56
57
    /**
58
     * Search for YouTube videos by a query string.
59
     *
60
     * @param string $q         The query string
61
     * @param string $pageToken YouTube page token (e.g. for next/previous page)
62
     * @param int    $perPage   Number of results per page
63
     *
64
     * @return object|false
65
     */
66
    public function search($q, $pageToken = '', $perPage = 10)
67
    {
68
        if (!$this->enabled()) {
69
            return false;
70
        }
71
72
        $uri = sprintf('search?part=snippet&type=video&maxResults=%s&pageToken=%s&q=%s',
73
            $perPage,
74
            urlencode($pageToken),
75
            urlencode($q)
76
        );
77
78
        return Cache::remember(md5("youtube_$uri"), 60 * 24 * 7, function () use ($uri) {
79
            return $this->get($uri);
80
        });
81
    }
82
}
83