Completed
Push — master ( aed180...cec8e0 )
by Hans
06:47
created

Spotify::assertValidAccessToken()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 10
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 10
loc 10
rs 9.4285
ccs 0
cts 9
cp 0
cc 3
eloc 5
nc 3
nop 1
crap 12
1
<?php
2
3
namespace HansOtt\Lastify\Services;
4
5
use HansOtt\Lastify\SyncProgress;
6
use HansOtt\Lastify\TrackInfo;
7
use HansOtt\Lastify\SyncResult;
8
use InvalidArgumentException;
9
use SpotifyWebAPI\SpotifyWebAPI;
10
use HansOtt\Lastify\TrackCollection;
11
use HansOtt\Lastify\TrackInfo\Artist;
12
use HansOtt\Lastify\CanManagePlaylists;
13
use HansOtt\Lastify\Exception\PlaylistDoesNotExist;
14
15
final class Spotify implements CanManagePlaylists
16
{
17
    private $api;
18
19
    private $userId = null;
20
21
    public function __construct(SpotifyWebAPI $api)
22
    {
23
        $this->api = $api;
24
    }
25
26
    public static function connect($accessToken)
27
    {
28
        static::assertValidAccessToken($accessToken);
0 ignored issues
show
Comprehensibility introduced by
Since HansOtt\Lastify\Services\Spotify is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
29
        $api = new SpotifyWebAPI();
30
        $api->setAccessToken($accessToken);
31
32
        return new static($api);
33
    }
34
35 View Code Duplication
    private static function assertValidAccessToken($accessToken)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
36
    {
37
        if (!is_string($accessToken)) {
38
            throw new InvalidArgumentException('The access token should be a string, instead got:' . gettype($accessToken));
39
        }
40
41
        if (empty($accessToken)) {
42
            throw new InvalidArgumentException('The access token cannot be empty');
43
        }
44
    }
45
46
    private function getSearchQuery(TrackInfo $info)
47
    {
48
        $addArtistName = function($artistNames, Artist $artist) {
49
            return $artistNames . $artist->getName();
50
        };
51
52
        $artistNames = array_reduce($info->getArtists(), $addArtistName, '');
53
54
        return $info->getName() . ' ' . $artistNames;
55
    }
56
57
    private function getTrackId(TrackInfo $track)
58
    {
59
        $options = [
60
            'type' => 'track',
61
        ];
62
63
        $query = $this->getSearchQuery($track);
64
        $result = $this->api->search($query, $options);
65
66
        $tracks = is_array($result->tracks->items) ? $result->tracks->items : [];
67
68
        if (empty($tracks)) {
69
            return null;
70
        }
71
72
        $firstMatch = array_shift($tracks);
73
74
        return !empty($firstMatch->id) ? $firstMatch->id : null;
75
    }
76
77
    private function fetchUserPlaylists()
78
    {
79
        $response = $this->api->getMyPlaylists();
80
81
        return isset($response->items) ? $response->items : [];
82
    }
83
84
    public function getPlaylistId($name)
85
    {
86
        $playlists = $this->fetchUserPlaylists();
87
88
        foreach ($playlists as $playlist) {
89
            if ($playlist->name == $name) {
90
                return $playlist->id;
91
            }
92
        }
93
94
        throw new PlaylistDoesNotExist($name);
95
    }
96
97
    private function getUserId()
98
    {
99
        if (isset($this->userId)) {
100
            return $this->userId;
101
        }
102
103
        $user = $this->api->me();
104
        $userId = (int) $user->id;
105
        $this->userId = $userId;
106
107
        return $userId;
108
    }
109
110
    public function createPlaylist($name)
111
    {
112
        $this->assertValidPlaylistName($name);
113
114
        $options = [
115
            'name' => $name
116
        ];
117
118
        $createdPlaylist = $this->api->createUserPlaylist($this->getUserId(), $options);
119
120
        return $createdPlaylist->id;
121
    }
122
123 View Code Duplication
    private function assertValidPlaylistName($name)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
124
    {
125
        if (!is_string($name)) {
126
            throw new InvalidArgumentException('The playlist name should be a string, instead got:' . gettype($name));
127
        }
128
        if (empty($name)) {
129
            throw new InvalidArgumentException('The playlist name cannot be empty');
130
        }
131
    }
132
133
    public function replacePlaylistTracks($playlistId, TrackCollection $newTracks, SyncProgress $progress)
134
    {
135
        $syncResult = new SyncResult();
136
        $trackIds = [];
137
138
        foreach ($newTracks as $track) {
139
            $progress->step($track);
140
            $trackId = $this->getTrackId($track);
141
142
            if (empty($trackId)) {
143
                $syncResult->addIgnoredTrack($track);
144
            }
145
            else {
146
                $trackIds[] = $trackId;
147
            }
148
        }
149
150
        $this->api->replaceUserPlaylistTracks(
151
            $this->getUserId(),
152
            $playlistId,
153
            $trackIds
154
        );
155
156
        return $syncResult;
157
    }
158
}
159