Skip to content
This repository was archived by the owner on Mar 23, 2024. It is now read-only.

Commit 0a0858d

Browse files
committed
:octocat: examples cleanup
1 parent 1081d98 commit 0a0858d

16 files changed

+93
-256
lines changed

examples/OAuthExampleSessionStorage.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ public function getAccessToken(string $service = null):AccessToken{
7979
}
8080
}
8181

82-
throw new OAuthStorageException('token not found');
82+
throw new OAuthStorageException(sprintf('token for service "%s" not found', $service));
8383
}
8484

8585
}

examples/Providers/GitHub/gist-spotify-top-tracks.php

+4-6
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,7 @@
88
* @license MIT
99
*/
1010

11-
namespace chillerlan\OAuthAppExamples\GitHub;
12-
1311
use chillerlan\HTTP\Utils\MessageUtil;
14-
use RuntimeException;
15-
use function sprintf;
1612

1713
/**
1814
* invoke the spotify client first
@@ -22,12 +18,14 @@
2218
require_once __DIR__.'/../Spotify/spotify-common.php';
2319

2420
/**
25-
* @var \chillerlan\OAuth\Providers\GitHub $github
26-
* @var \Psr\Log\LoggerInterface $logger
21+
* @var \OAuthProviderFactory $factory
22+
* @var \chillerlan\OAuth\Providers\GitHub $github
2723
*/
2824

2925
require_once __DIR__.'/github-common.php';
3026

27+
$logger = $factory->getLogger();
28+
3129
$gistID = null; // set to null to create a new gist
3230
$gistname = '🎵 My Spotify Top Tracks';
3331
$description = 'auto generated spotify track list';

examples/Providers/GitHub/github-common.php

+2-18
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,11 @@
66
* @license MIT
77
*/
88

9-
namespace chillerlan\OAuthAppExamples\GitHub;
10-
11-
use chillerlan\OAuth\Core\AccessToken;
129
use chillerlan\OAuth\Providers\GitHub;
1310

1411
$ENVVAR = 'GITHUB';
1512

16-
/**
17-
* @var \Psr\Http\Client\ClientInterface $http
18-
* @var \chillerlan\Settings\SettingsContainerInterface $options
19-
* @var \chillerlan\OAuth\Storage\OAuthStorageInterface $storage
20-
* @var \Psr\Log\LoggerInterface $logger
21-
* @var string $CFGDIR
22-
*/
23-
2413
require_once __DIR__.'/../../provider-example-common.php';
2514

26-
$github = new GitHub($http, $options, $logger);
27-
$github->setStorage($storage);
28-
29-
if(!$storage->hasAccessToken('GitHub')){
30-
$token = (new AccessToken)->fromJSON(file_get_contents($CFGDIR.'/GitHub.token.json'));
31-
$github->storeAccessToken($token);
32-
}
15+
/** @var \OAuthProviderFactory $factory */
16+
$github = $factory->getProvider(GitHub::class, $ENVVAR);

examples/Providers/LastFM/cache/.gitkeep

Whitespace-only changes.

examples/Providers/LastFM/lastfm-common.php

+3-20
Original file line numberDiff line numberDiff line change
@@ -7,28 +7,11 @@
77
* @license MIT
88
*/
99

10-
namespace chillerlan\OAuthExamples\Providers\LastFM;
11-
12-
use chillerlan\OAuth\Core\AccessToken;
1310
use chillerlan\OAuth\Providers\LastFM;
14-
use function file_get_contents;
1511

1612
$ENVVAR = 'LASTFM';
1713

18-
/**
19-
* @var \Psr\Http\Client\ClientInterface $http
20-
* @var \chillerlan\Settings\SettingsContainerInterface $options
21-
* @var \chillerlan\OAuth\Storage\OAuthStorageInterface $storage
22-
* @var \Psr\Log\LoggerInterface $logger
23-
* @var string $CFGDIR
24-
*/
25-
26-
require_once __DIR__.'/../provider-api-example-common.php';
27-
28-
$lfm = new LastFM($http, $options, $logger);
29-
$lfm->setStorage($storage);
14+
require_once __DIR__.'/../../provider-example-common.php';
3015

31-
if(!$storage->hasAccessToken()){
32-
$token = (new AccessToken)->fromJSON(file_get_contents(($CFGDIR ?? '').'/LastFM.token.json'));
33-
$lfm->storeAccessToken($token);
34-
}
16+
/** @var \OAuthProviderFactory $factory */
17+
$lfm = $factory->getProvider(LastFM::class, $ENVVAR);

examples/Providers/LastFM/topalbum-patchwork.php

+15-49
Original file line numberDiff line numberDiff line change
@@ -13,55 +13,16 @@
1313
* @noinspection PhpComposerExtensionStubsInspection
1414
*/
1515

16-
namespace chillerlan\OAuthExamples\Providers\LastFM;
17-
1816
use chillerlan\HTTP\Utils\MessageUtil;
19-
use Exception;
20-
use function array_column;
21-
use function array_shift;
22-
use function count;
23-
use function dirname;
24-
use function file_exists;
25-
use function file_get_contents;
26-
use function file_put_contents;
27-
use function header;
28-
use function imagecolorallocate;
29-
use function imagecopyresampled;
30-
use function imagecreatefromgif;
31-
use function imagecreatefromjpeg;
32-
use function imagecreatefrompng;
33-
use function imagecreatetruecolor;
34-
use function imagedestroy;
35-
use function imagefill;
36-
use function imagejpeg;
37-
use function imagesx;
38-
use function imagesy;
39-
use function intval;
40-
use function json_decode;
41-
use function json_encode;
42-
use function max;
43-
use function min;
44-
use function mkdir;
45-
use function parse_url;
46-
use function sha1;
47-
use function strlen;
48-
use function substr;
49-
use function trim;
50-
use const JSON_PRETTY_PRINT;
51-
use const PHP_URL_PATH;
52-
53-
$ENVVAR = 'LASTFM';
5417

5518
/**
56-
* @var \Psr\Log\LoggerInterface $logger
5719
* @var \chillerlan\OAuth\Providers\LastFM $lfm
5820
*/
5921

6022
require_once __DIR__.'/lastfm-common.php';
6123

62-
$urlcache = './urlcache';
63-
$imgcache = './cache'; // public access
64-
24+
$urlcache = './urlcache'; // downloaded album covers
25+
$imgcache = './cache'; // generated patchworks
6526

6627
try{
6728
$request = json_decode(file_get_contents('php://input'));
@@ -115,13 +76,19 @@
11576
continue;
11677
}
11778

118-
$path = getImage($img[(count($img) - 1)]->{'#text'}, $urlcache);
119-
$ext = substr($path, (strlen($path) - 3));
120-
$res[] = match($ext){
121-
'jpg' => imagecreatefromjpeg($path),
122-
'png' => imagecreatefrompng($path),
123-
'gif' => imagecreatefromgif($path),
124-
};
79+
try{
80+
$path = getImage($img[(count($img) - 1)]->{'#text'}, $urlcache);
81+
$ext = pathinfo($path, PATHINFO_EXTENSION);
82+
83+
$res[] = match($ext){
84+
'jpg' => imagecreatefromjpeg($path),
85+
'png' => imagecreatefrompng($path),
86+
'gif' => imagecreatefromgif($path),
87+
};
88+
}
89+
catch(Throwable){
90+
continue;
91+
}
12592
}
12693

12794
$patchwork = imagecreatetruecolor(($cols * $imageSize), ($rows * $imageSize));
@@ -160,7 +127,6 @@
160127
exit;
161128

162129
function getImage(string $url, string $urlcache):string{
163-
164130
$path = parse_url($url, PHP_URL_PATH);
165131

166132
if(file_exists($urlcache.$path)){

examples/Providers/LastFM/urlcache/.gitkeep

Whitespace-only changes.

examples/Providers/Spotify/MixesDBTrackSearch.php

+6-21
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,7 @@
88
* @license MIT
99
*/
1010

11-
namespace chillerlan\OAuthExamples\Providers\Spotify;
12-
1311
use chillerlan\HTTP\Utils\MessageUtil;
14-
use function array_column;
15-
use function array_map;
16-
use function array_merge;
17-
use function explode;
18-
use function file_get_contents;
19-
use function implode;
20-
use function json_decode;
21-
use function preg_replace;
22-
use function sprintf;
23-
use function str_replace;
24-
use function strtotime;
25-
use function trim;
26-
use function usleep;
2712

2813
/**
2914
*
@@ -35,11 +20,11 @@ class MixesDBTrackSearch extends SpotifyClient{
3520
*/
3621
public function getTracks(
3722
string $clubnightsJSON,
38-
int $since,
39-
int $until,
40-
array $find = [],
41-
int $limit = 5,
42-
bool $playlistPerSet = false,
23+
int $since,
24+
int $until,
25+
array $find = [],
26+
int $limit = 5,
27+
bool $playlistPerSet = false,
4328
):void{
4429
$clubnights = json_decode(file_get_contents($clubnightsJSON), true);
4530
$tracks = [];
@@ -69,7 +54,7 @@ public function getTracks(
6954

7055
$this->logger->info(sprintf('search: %s', $track));
7156

72-
$response = $this->spotify->request('/v1/search', [
57+
$response = $this->request('/v1/search', [
7358
'q' => $this->getSearchTerm($track),
7459
'type' => 'track',
7560
'limit' => $limit,

examples/Providers/Spotify/SpotifyClient.php

+26-29
Original file line numberDiff line numberDiff line change
@@ -8,32 +8,23 @@
88
* @license MIT
99
*/
1010

11-
namespace chillerlan\OAuthExamples\Providers\Spotify;
12-
1311
use chillerlan\HTTP\Utils\MessageUtil;
12+
use chillerlan\OAuth\OAuthOptions;
1413
use chillerlan\OAuth\Providers\Spotify;
14+
use chillerlan\OAuth\Storage\MemoryStorage;
15+
use chillerlan\OAuth\Storage\OAuthStorageInterface;
16+
use chillerlan\Settings\SettingsContainerInterface;
17+
use Psr\Http\Client\ClientInterface;
18+
use Psr\Http\Message\RequestFactoryInterface;
19+
use Psr\Http\Message\StreamFactoryInterface;
20+
use Psr\Http\Message\UriFactoryInterface;
1521
use Psr\Log\LoggerInterface;
1622
use Psr\Log\NullLogger;
17-
use RuntimeException;
18-
use function array_chunk;
19-
use function array_map;
20-
use function array_values;
21-
use function file_exists;
22-
use function file_get_contents;
23-
use function file_put_contents;
24-
use function json_decode;
25-
use function json_encode;
26-
use function rtrim;
27-
use function sprintf;
28-
use function usleep;
29-
use const JSON_PRETTY_PRINT;
30-
use const JSON_UNESCAPED_SLASHES;
31-
use const JSON_UNESCAPED_UNICODE;
3223

3324
/**
3425
*
3526
*/
36-
abstract class SpotifyClient{
27+
class SpotifyClient extends Spotify{
3728

3829
protected const sleepTimer = 250000; // sleep between requests (µs)
3930

@@ -43,13 +34,19 @@ abstract class SpotifyClient{
4334
protected array $artists = [];
4435
protected array $albums = [];
4536

46-
/**
47-
*
48-
*/
4937
public function __construct(
50-
protected Spotify $spotify,
51-
protected LoggerInterface $logger = new NullLogger(),
38+
OAuthOptions|SettingsContainerInterface $options,
39+
ClientInterface $http,
40+
RequestFactoryInterface $requestFactory,
41+
StreamFactoryInterface $streamFactory,
42+
UriFactoryInterface $uriFactory,
43+
OAuthStorageInterface $storage = new MemoryStorage,
44+
LoggerInterface $logger = new NullLogger
5245
){
46+
parent::__construct($options, $http, $requestFactory, $streamFactory, $uriFactory, $storage, $logger);
47+
48+
// set the servicename to the original provider's name so that we use the same tokens
49+
$this->serviceName = 'Spotify';
5350
$this->getMe();
5451
}
5552

@@ -95,7 +92,7 @@ protected function loadFromFile(array $vars, string $dir):bool{
9592
* fetch the currently authenticated user
9693
*/
9794
protected function getMe():void{
98-
$me = $this->spotify->request('/v1/me');
95+
$me = $this->me();
9996

10097
if($me->getStatusCode() !== 200){
10198
throw new RuntimeException('could not fetch data from /me endpoint');
@@ -125,7 +122,7 @@ public function getFollowedArtists():array{
125122
];
126123

127124
do{
128-
$meFollowing = $this->spotify->request('/v1/me/following', $params);
125+
$meFollowing = $this->request('/v1/me/following', $params);
129126
$data = MessageUtil::decodeJSON($meFollowing);
130127

131128
if($meFollowing->getStatusCode() === 200){
@@ -167,7 +164,7 @@ public function getArtistReleases():array{
167164

168165
foreach($this->artists as $artistID => $artist){
169166
// WTB bulk endpoint /artists/albums?ids=artist_id1,artist_id2,...
170-
$artistAlbums = $this->spotify->request(sprintf('/v1/artists/%s/albums', $artistID), ['market' => $this->market]);
167+
$artistAlbums = $this->request(sprintf('/v1/artists/%s/albums', $artistID), ['market' => $this->market]);
171168

172169
if($artistAlbums->getStatusCode() !== 200){
173170
$this->logger->warning(sprintf('could not fetch albums for artist "%s"', $artist->name));
@@ -212,7 +209,7 @@ public function getPlaylist(string $playlistID):array{
212209
$retry = 0;
213210

214211
do{
215-
$response = $this->spotify->request(sprintf('/v1/playlists/%s/tracks', $playlistID), $params);
212+
$response = $this->request(sprintf('/v1/playlists/%s/tracks', $playlistID), $params);
216213

217214
if($retry > 3){
218215
throw new RuntimeException('error while retrieving playlist');
@@ -254,7 +251,7 @@ public function getPlaylist(string $playlistID):array{
254251
*/
255252
public function createPlaylist(string $name, string $description):string{
256253

257-
$createPlaylist = $this->spotify->request(
254+
$createPlaylist = $this->request(
258255
path : sprintf('/v1/users/%s/playlists', $this->id),
259256
method : 'POST',
260257
body : [
@@ -296,7 +293,7 @@ public function addTracks(string $playlistID, array $trackIDs):static{
296293

297294
foreach($uris as $i => $chunk){
298295

299-
$playlistAddTracks = $this->spotify->request(
296+
$playlistAddTracks = $this->request(
300297
path : sprintf('/v1/playlists/%s/tracks', $playlistID),
301298
method : 'POST',
302299
body : ['uris' => $chunk],

0 commit comments

Comments
 (0)