Passed
Push — master ( cc0804...5222f0 )
by Scrutinizer
01:15
created

ConfigProtectedMethods::setToken()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 1
dl 0
loc 19
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of the keinos/mastodon-streaming-api-config package.
5
 *
6
 * - Authors, copyright, license, usage and etc.:
7
 *   - See: https://github.com/KEINOS/Mastodon_StreamingAPI_Config/
8
 */
9
10
declare(strict_types=1);
11
12
namespace KEINOS\MSTDN_TOOLS;
13
14
use Symfony\Component\HttpClient\HttpClient as HttpClient;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpClient\HttpClient was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
16
/**
17
 * Parent class of \KEINOS\MSTDN_TOOLS\Config class.
18
 *
19
 * Note that the only public method allowed is "__construct()". Other public
20
 * methods and properties must be defined in "Config" child class.
21
 */
22
class ConfigProtectedMethods extends ConfigStaticMethods
23
{
24
    /** @var string */
25
    protected $url_host;
26
    /** @var string */
27
    protected $url_api_instance;
28
    /** @var array<mixed,mixed> */
29
    protected $info_server;
30
    /** @var string */
31
    protected $access_token = '';
32
33
    public function __construct(string $url_host, string $access_token = '')
34
    {
35
        $this->setUrlHost($url_host);
36
        $this->setToken($access_token);
37
        $this->setServerInfo();
38
    }
39
40
    protected function getAccessToken(): string
41
    {
42
        return $this->access_token;
43
    }
44
45
    /**
46
     * @return array<mixed,mixed>
47
     */
48
    protected function getContentsAsArray(string $url_api): array
49
    {
50
        try {
51
            /** @phan-suppress-next-line PhanUndeclaredClassMethod */
52
            $client_http = HttpClient::create();
53
            $response = $client_http->request('GET', $url_api);
54
            // Get contents as array
55
            return $response->toArray();
56
        } catch (\Exception $e) {
57
            $msg = 'Error while setting server info.' . PHP_EOL
58
                 . '- Error details: ' . $e->getMessage() . PHP_EOL;
59
            throw new \Exception($msg);
60
        }
61
    }
62
63
    protected function setServerInfo(): void
64
    {
65
        $url_api = rtrim($this->url_host, '/') . self::ENDPOINT_API_INFO_INSTANCE;
66
        $info    = $this->getContentsAsArray($url_api);
67
        // Set property
68
        $this->url_api_instance = $url_api;
69
        $this->info_server = $info;
70
    }
71
72
    /**
73
     * @param  string $access_token
74
     * @return void
75
     * @throws \Exception            If the token is in bad format.
76
     */
77
    protected function setToken(string $access_token): void
78
    {
79
        if (empty($access_token)) {
80
            return;
81
        }
82
83
        if (! self::isAlphaNumeric($access_token)) {
84
            $msg = 'Invalid access token. Should be alpha numeric.';
85
            throw new \Exception($msg);
86
        }
87
88
        // Mastodon's token is 64 byte in length
89
        if (64 !== strlen($access_token)) {
90
            $msg = 'Invalid access token. Should be 64 chars in length.';
91
            throw new \Exception($msg);
92
        }
93
94
        // Set property
95
        $this->access_token = $access_token;
96
    }
97
98
    /**
99
     * @param  string $url_host  The URL of Mastodon server/instance.
100
     * @return void
101
     * @throws \Exception        If the server isn't available.
102
     */
103
    protected function setUrlHost(string $url_host): void
104
    {
105
        try {
106
            if (self::isUrlProtocolHttp($url_host)) {
107
                $msg = 'Not in "https:" protocol. We do not allow "http:" protocol.';
108
                throw new \Exception($msg);
109
            }
110
111
            /** @phan-suppress-next-line PhanUndeclaredClassMethod */
112
            $client_http = HttpClient::create();
113
114
            $response = $client_http->request('HEAD', $url_host);
115
            if (200 !== $response->getStatusCode()) {
116
                throw new \Exception('The server did not return 200 status.');
117
            }
118
            // Set property
119
            $this->url_host = $url_host;
120
        } catch (\Exception $e) {
121
            $msg = 'Error while setting server host URL.' . PHP_EOL
122
                 . '- Error details: ' . $e->getMessage() . PHP_EOL;
123
            throw new \Exception($msg);
124
        }
125
    }
126
}
127