Passed
Push — master ( b0aadc...3b2e67 )
by Scrutinizer
02:03 queued 17s
created

Config   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 114
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 48
c 0
b 0
f 0
dl 0
loc 114
rs 10
wmc 13

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 22 2
A setOptionalSettings() 0 20 6
A setDefaultSettings() 0 6 1
A requestApiInstance() 0 13 2
A generateUrlApiInstance() 0 9 2
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
 * - Authors, copyright, license, usage and etc.:
9
 *   - See: https://github.com/KEINOS/Mastodon_StreamingAPI_Config/
10
 *
11
 * Note:
12
 * - Non static public methods or properties must be defined here.
13
 * - Only the public method "__construct()" is defined in "ConfigProtectedMethods".
14
 * - Static methods and properties must be defined in "ConfigStaticMethods".
15
 * - Protected methods/properties must be defined in "ConfigProtectedMethods".
16
 * - Class constants must be defined in "ConfigConstants".
17
 *
18
 * Debug:
19
 * - To test and analyze the scripts:
20
 *   - Run: `$ composer test all verbose` (Composer is required)
21
 */
22
23
declare(strict_types=1);
24
25
namespace KEINOS\MSTDN_TOOLS\Config;
26
27
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...
28
29
/**
30
 * This class holds and provides Mastodon server, a.k.a instance, information to
31
 * receive server-sent messages from Mastodon Streaming API.
32
 */
33
class Config implements ConfigInterface
34
{
35
    use PropertiesTrait;
36
    use StaticMethodsTrait;
37
38
    //public const CRLF = "\r\n";
39
    //public const ENDPOINT_API_STREAM_PUBLIC = '/api/v1/streaming/public';
40
    //public const ENDPOINT_API_STREAM_LOCAL  = '/api/v1/streaming/public/local';
41
    public const ACCESS_TOKEN_DEFAULT = '';
42
    public const CACHE_PREFIX_DEFAULT = 'mstdn_tools_cache_';
43
    public const CACHE_TTL_DEFAULT    = 60 * 60 * 1; // 1 hour
44
    public const ENDPOINT_API_INSTANCE_DEFAULT = '/api/v1/instance';
45
    public const FLAG_USE_CACHE_DEFAULT = true;
46
47
    /**
48
     * {@inheritdoc}
49
     *
50
     * @param  array<string,mixed> $settings
51
     * @return void
52
     * @throws \Exception
53
     */
54
    public function __construct(array $settings)
55
    {
56
        /* Set must settings */
57
        if (isset($settings['url_host'])) {
58
            $this->setUrlHost($settings['url_host']);
59
        } else {
60
            $msg = '"url_host" key missing. URL of the Mastodon server/instance is required.';
61
            throw new \Exception($msg);
62
        }
63
64
        /* Set default settings */
65
        $this->setDefaultSettings();
66
67
        /* Set optional settings */
68
        $this->setOptionalSettings($settings);
69
70
        $url_api_instance = $this->generateUrlApiInstance();
71
        $this->setUrlApiInstance($url_api_instance);
72
73
        /* Set host info from API method of Instance */
74
        $info_instance = $this->requestApiInstance();
75
        $this->setInfoInstance($info_instance);
76
    }
77
78
    /**
79
     * @return array<mixed,mixed>
80
     * @throws \Exception
81
     */
82
    protected function requestApiInstance(): array
83
    {
84
        try {
85
            $client_http      = HttpClient::create();
86
            $url_api_instance = $this->getUrlApiInstance();
87
88
            // Get contents as array
89
            $response = $client_http->request('GET', $url_api_instance);
90
            return $response->toArray();
91
        } catch (\Exception $e) {
92
            $msg = 'Error while getting the server info from the API.' . PHP_EOL
93
                 . '- Error details: ' . $e->getMessage() . PHP_EOL;
94
            throw new \Exception($msg);
95
        }
96
    }
97
98
    protected function setDefaultSettings(): void
99
    {
100
        $this->setAccessToken(self::ACCESS_TOKEN_DEFAULT);
101
        $this->setEndpointApiInstance(self::ENDPOINT_API_INSTANCE_DEFAULT);
102
        $this->setFlagUseCache(self::FLAG_USE_CACHE_DEFAULT);
103
        $this->setIdHashSelf(strval(hash_file('md5', __FILE__)));
104
    }
105
106
    /**
107
     * @param  array<string,mixed> $settings
108
     * @return void
109
     * @throws \Exception
110
     */
111
    protected function setOptionalSettings(array $settings): void
112
    {
113
        if (isset($settings['access_token'])) {
114
            $this->setAccessToken($settings['access_token']);
115
        }
116
117
        if (isset($settings['endpoint_api_instance'])) {
118
            $this->setEndpointApiInstance($settings['endpoint_api_instance']);
119
        }
120
121
        if (isset($settings['flag_use_cache'])) {
122
            $this->setFlagUseCache($settings['setFlagUseCache']);
123
        }
124
125
        if (isset($settings['id_hash_self'])) {
126
            $this->setIdHashSelf($settings['setIdHashSelf']);
127
        }
128
129
        if (isset($settings['ttl_cache'])) {
130
            $this->setTtlCache($settings['ttl_cache']);
131
        }
132
    }
133
134
    /**
135
     * @return string
136
     * @throws \Exception
137
     */
138
    protected function generateUrlApiInstance(): string
139
    {
140
        $url_api_instance = rtrim($this->getUrlHost(), '/') . $this->getEndpointApiInstance();
141
        if (! self::isUrlAlive($url_api_instance)) {
142
            $msg = 'Invalid settings given. Can NOT access to the endpoint URL. URL: '
143
                 . $url_api_instance . PHP_EOL;
144
            throw new \Exception($msg);
145
        }
146
        return $url_api_instance;
147
    }
148
}
149