1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* (c) Christian Gripp <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Core23\LastFm\Service; |
13
|
|
|
|
14
|
|
|
use Core23\LastFm\Client\ApiClientInterface; |
15
|
|
|
use Core23\LastFm\Exception\ApiException; |
16
|
|
|
use Core23\LastFm\Exception\NotFoundException; |
17
|
|
|
use Core23\LastFm\Session\Session; |
18
|
|
|
use Core23\LastFm\Session\SessionInterface; |
19
|
|
|
use Psr\Log\LoggerAwareInterface; |
20
|
|
|
use Psr\Log\LoggerAwareTrait; |
21
|
|
|
use Psr\Log\NullLogger; |
22
|
|
|
|
23
|
|
|
final class AuthService implements LoggerAwareInterface, AuthServiceInterface |
24
|
|
|
{ |
25
|
|
|
use LoggerAwareTrait; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var string |
29
|
|
|
*/ |
30
|
|
|
private $authUrl; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @var ApiClientInterface |
34
|
|
|
*/ |
35
|
|
|
private $client; |
36
|
|
|
|
37
|
|
|
public function __construct(ApiClientInterface $connection, string $authUrl = 'http://www.last.fm/api/auth/') |
38
|
|
|
{ |
39
|
|
|
$this->client = $connection; |
40
|
|
|
$this->authUrl = $authUrl; |
41
|
|
|
$this->logger = new NullLogger(); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function createSession(string $token): ?SessionInterface |
45
|
|
|
{ |
46
|
|
|
try { |
47
|
|
|
$response = $this->client->signedCall('auth.getSession', [ |
48
|
|
|
'token' => $token, |
49
|
|
|
]); |
50
|
|
|
|
51
|
|
|
return new Session($response['session']['name'], $response['session']['key'], $response['session']['subscriber']); |
52
|
|
|
} catch (ApiException $e) { |
53
|
|
|
$this->logger->warning(sprintf('Error getting session for "%s" token.', $token), [ |
54
|
|
|
'exception' => $e, |
55
|
|
|
]); |
56
|
|
|
} catch (NotFoundException $e) { |
57
|
|
|
$this->logger->info(sprintf('No session was found for "%s" token.', $token), [ |
58
|
|
|
'exception' => $e, |
59
|
|
|
]); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return null; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function createToken(): ?string |
66
|
|
|
{ |
67
|
|
|
$response = $this->client->signedCall('auth.getToken'); |
68
|
|
|
|
69
|
|
|
return $response['token'] ?? null; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function getAuthUrl(string $callbackUrl): string |
73
|
|
|
{ |
74
|
|
|
return $this->authUrl.'?api_key='.$this->client->getApiKey().'&cb='.$callbackUrl; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|