Passed
Push — master ( 2855df...404664 )
by Scrutinizer
01:30
created

Config::getUriStreamingApi()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is the main class of the keinos/mastodon-streaming-api-config package.
5
 *
6
 * - Reference of the public methods of this class to use:
7
 *   - See: ./ConfigInterface.php
8
 *
9
 * - Authors, copyright, license, usage and etc.:
10
 *   - See: https://github.com/KEINOS/Mastodon_StreamingAPI_Config/
11
 *
12
 * Debug:
13
 * - To test and analyze the scripts run:
14
 *   - Debug: `$ composer test all verbose`
15
 *   - Help: `$ composer test help`
16
 *   - Note: Composer is required
17
 */
18
19
declare(strict_types=1);
20
21
namespace KEINOS\MSTDN_TOOLS\Config;
22
23
use Symfony\Component\HttpClient\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...
24
use KEINOS\MSTDN_TOOLS\Cache\Cache;
0 ignored issues
show
Bug introduced by
The type KEINOS\MSTDN_TOOLS\Cache\Cache 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...
25
26
/**
27
 * This class holds and provides Mastodon server, a.k.a instance, information to
28
 * receive server-sent messages from Mastodon Streaming API.
29
 */
30
class Config implements ConfigInterface
31
{
32
    /* Traits */
33
    use PropertiesTrait;    // Properties and their getter/setter methods as well
34
    use StaticMethodsTrait;
35
36
    /* Constants */
37
    public const ACCESS_TOKEN_DEFAULT = '';
38
    public const CACHE_PREFIX_DEFAULT = 'mstdn_tools_cache_';
39
    public const CACHE_TTL_DEFAULT    = 60 * 60 * 1; // 1 hour
40
    public const ENDPOINT_API_INSTANCE_DEFAULT = '/api/v1/instance';
41
    public const FLAG_USE_CACHE_DEFAULT = true;
42
43
    /* Methods */
44
45
    /**
46
     * {@inheritdoc}
47
     *
48
     * @param  array<string,mixed> $settings
49
     * @return void
50
     * @throws \Exception
51
     */
52
    public function __construct(array $settings)
53
    {
54
        /* Set must settings */
55
        if (isset($settings['url_host'])) {
56
            $this->setUrlHost($settings['url_host']);
57
        } else {
58
            $msg = '"url_host" key missing. URL of the Mastodon server/instance is required.';
59
            throw new \Exception($msg);
60
        }
61
62
        /* Set default settings */
63
        $this->setDefaultSettings();
64
65
        /* Set optional settings */
66
        $this->setOptionalSettings($settings);
67
68
        $url_api_instance = $this->generateUrlApiInstance();
69
        $this->setUrlApiInstance($url_api_instance);
70
71
        /* Set server info from API Instance method */
72
        $info_instance = $this->preloadCacheInstanceInfo();
73
        if (null === $info_instance) {
74
            $info_instance = $this->requestApiInstance();
75
        }
76
        $this->saveCacheInstanceInfo($info_instance);
77
        $this->setInfoInstance($info_instance);
78
    }
79
80
    /**
81
     * @return string
82
     * @throws \Exception
83
     */
84
    protected function generateUrlApiInstance(): string
85
    {
86
        $url_api_instance = rtrim($this->getUrlHost(), '/') . $this->getEndpointApiInstance();
87
88
        if (! self::isUrlAlive($url_api_instance)) {
89
            $msg = 'Invalid settings given. Can NOT access to the endpoint URL. URL: '
90
                 . $url_api_instance . PHP_EOL;
91
            throw new \Exception($msg);
92
        }
93
94
        return $url_api_instance;
95
    }
96
97
    /**
98
     * Get the WebSocket URI address.
99
     * @return string
100
     */
101
    public function getUriStreamingApi(): string
102
    {
103
        $info_instance = $this->getInfoInstance();
104
105
        return $info_instance['urls']['streaming_api'];
106
    }
107
108
    /**
109
     * @return null|mixed
110
     */
111
    protected function preloadCacheInstanceInfo()
112
    {
113
        $key_cache     = 'info_instance';
0 ignored issues
show
Unused Code introduced by
The assignment to $key_cache is dead and can be removed.
Loading history...
114
        $info_instance = null;
115
116
        $cache = new Cache([
117
            'ttl'    => $this->getTtlCache(),
118
            'prefix' => $this->getPrefixCache(),
119
        ]);
120
121
        if ($this->getFlagUseCache()) {
122
            $info_instance = $cache->get('info_instance');
123
        } else {
124
            $cache->clear();
125
        }
126
127
        return $info_instance;
128
    }
129
130
    /**
131
     * @param  mixed $info_instance
132
     * @return bool
133
     * @throws \Exception
134
     */
135
    protected function saveCacheInstanceInfo($info_instance): bool
136
    {
137
        try {
138
            $cache = new Cache([
139
                'ttl'    => $this->getTtlCache(),
140
                'prefix' => $this->getPrefixCache(),
141
            ]);
142
            $cache->set('info_instance', $info_instance);
143
            return true;
144
        } catch (\Exception $e) {
145
            $msg = 'Error while getting the server info from the API.' . PHP_EOL
146
                 . '- Error details: ' . $e->getMessage() . PHP_EOL;
147
            throw new \Exception($msg);
148
        }
149
    }
150
151
    /**
152
     * @return array<mixed,mixed>
153
     * @throws \Exception
154
     */
155
    protected function requestApiInstance(): array
156
    {
157
        try {
158
            $client_http      = HttpClient::create();
159
            $url_api_instance = $this->getUrlApiInstance();
160
161
            // Get contents and return as array
162
            $response = $client_http->request('GET', $url_api_instance);
163
            return $response->toArray();
164
        } catch (\Exception $e) {
165
            $msg = 'Error while getting the server info from the API.' . PHP_EOL
166
                 . '- Error details: ' . $e->getMessage() . PHP_EOL;
167
            throw new \Exception($msg);
168
        }
169
    }
170
171
    protected function setDefaultSettings(): void
172
    {
173
        $this->setAccessToken(self::ACCESS_TOKEN_DEFAULT);
174
        $this->setEndpointApiInstance(self::ENDPOINT_API_INSTANCE_DEFAULT);
175
        $this->setFlagUseCache(self::FLAG_USE_CACHE_DEFAULT);
176
        $this->setIdHashSelf(strval(hash_file('md5', __FILE__)));
177
        $this->setPrefixCache(self::CACHE_PREFIX_DEFAULT);
178
        $this->setTtlCache(self::CACHE_TTL_DEFAULT);
179
    }
180
181
    /**
182
     * @param  array<string,mixed> $settings
183
     * @return void
184
     * @throws \Exception
185
     */
186
    protected function setOptionalSettings(array $settings): void
187
    {
188
        $list_key_to_method = [
189
            'access_token'          => 'setAccessToken',
190
            'endpoint_api_instance' => 'setEndpointApiInstance',
191
            'flag_use_cache'        => 'setFlagUseCache',
192
            'prefix_cache'          => 'setPrefixCache',
193
            'id_hash_self'          => 'setIdHashSelf',
194
            'ttl_cache'             => 'setTtlCache',
195
        ];
196
197
        foreach ($settings as $key => $value) {
198
            if (isset($list_key_to_method[$key])) {
199
                $name_method = $list_key_to_method[$key];
200
                $this->$name_method($value);
201
            }
202
        }
203
    }
204
}
205