friendship ended with social-app. php is my new best friend
1<?php
2/**
3 * Class Tumblr
4 *
5 * @created 22.10.2017
6 * @author Smiley <smiley@chillerlan.net>
7 * @copyright 2017 Smiley
8 * @license MIT
9 *
10 * @noinspection PhpUnused
11 */
12declare(strict_types=1);
13
14namespace chillerlan\OAuth\Providers;
15
16use chillerlan\HTTP\Utils\MessageUtil;
17use chillerlan\OAuth\Core\{AccessToken, AuthenticatedUser, OAuth1Provider, UserInfo};
18use function sprintf;
19
20/**
21 * Tumblr OAuth1
22 *
23 * @link https://www.tumblr.com/docs/en/api/v2#oauth1-authorization
24 */
25class Tumblr extends OAuth1Provider implements UserInfo{
26
27 public const IDENTIFIER = 'TUMBLR';
28
29 protected string $requestTokenURL = 'https://www.tumblr.com/oauth/request_token';
30 protected string $authorizationURL = 'https://www.tumblr.com/oauth/authorize';
31 protected string $accessTokenURL = 'https://www.tumblr.com/oauth/access_token';
32 protected string $apiURL = 'https://api.tumblr.com';
33 protected string|null $userRevokeURL = 'https://www.tumblr.com/settings/apps';
34 protected string|null $apiDocs = 'https://www.tumblr.com/docs/en/api/v2';
35 protected string|null $applicationURL = 'https://www.tumblr.com/oauth/apps';
36
37 /** @codeCoverageIgnore */
38 public function me():AuthenticatedUser{
39 $json = $this->getMeResponseData('/v2/user/info');
40
41 $userdata = [
42 'data' => $json,
43 'handle' => $json['response']['user']['name'],
44 'url' => sprintf('https://www.tumblr.com/%s', $json['response']['user']['name']),
45 ];
46
47 return new AuthenticatedUser($userdata);
48 }
49
50 /**
51 * Exchange the current token for an OAuth2 token - this will invalidate the OAuth1 token.
52 *
53 * @link https://www.tumblr.com/docs/en/api/v2#v2oauth2exchange---oauth1-to-oauth2-token-exchange
54 *
55 * @throws \chillerlan\OAuth\Providers\ProviderException
56 */
57 public function exchangeForOAuth2Token():AccessToken{
58 $response = $this->request(path: '/v2/oauth2/exchange', method: 'POST');
59 $status = $response->getStatusCode();
60 $json = MessageUtil::decodeJSON($response);
61
62 if($status === 200){
63 $token = $this->createAccessToken();
64
65 $token->accessToken = $json->access_token;
66 $token->refreshToken = $json->refresh_token;
67 $token->expires = $json->expires_in;
68 $token->extraParams = ['scope' => $json->scope, 'token_type' => $json->token_type];
69
70 $this->storage->storeAccessToken($token, $this->name);
71
72 return $token;
73 }
74
75 if(isset($json->meta, $json->meta->msg)){
76 throw new ProviderException($json->meta->msg);
77 }
78
79 throw new ProviderException(sprintf('token exchange error HTTP/%s', $status));
80 }
81
82}