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

StaticMethodsTrait::requestApi()   A

Complexity

Conditions 5
Paths 13

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 19
c 1
b 0
f 0
nc 13
nop 2
dl 0
loc 30
rs 9.3222
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\Config;
13
14
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...
15
16
trait StaticMethodsTrait
17
{
18
    /**
19
     * @param  string $access_token
20
     * @return bool
21
     */
22
    public static function isCompliantAccessToken(string $access_token): bool
23
    {
24
        if (empty(trim($access_token))) {
25
            return false;
26
        }
27
28
        if (! self::isStringAlphaNumeric($access_token)) {
29
            return false;
30
        }
31
32
        // Mastodon's token is 64 byte in length
33
        if (64 !== strlen($access_token)) {
34
            return false;
35
        }
36
37
        return true;
38
    }
39
40
    public static function isStringAlphaNumeric(string $string): bool
41
    {
42
        // Some server doesn't enable ctype_alnum by default
43
        //return ctype_alnum($string);
44
45
        return (preg_match('/^[a-zA-Z0-9]+$/', $string) > 0);
46
    }
47
    /**
48
     * @param  string $url   The target URL of the server.
49
     * @return bool          Returns true if the URL is 200 status.
50
     */
51
    public static function isUrlAlive(string $url): bool
52
    {
53
        $client_http = HttpClient::create();
54
55
        $response = $client_http->request('HEAD', $url);
56
57
        return (200 === $response->getStatusCode());
58
    }
59
60
    /**
61
     * Checks if the URL protocol is "http:".
62
     *
63
     * @param  string $url
64
     * @return bool
65
     */
66
    public static function isUrlProtocolHttp(string $url): bool
67
    {
68
        $target = 'http:';
69
70
        return ($target === substr(trim($url), 0, strlen($target)));
71
    }
72
73
    /**
74
     * Request to the Mastodon API endpoint. The endpoint must return in JSON.
75
     *
76
     * @param  string $url_api         URL to the API's endpoint.
77
     * @param  string $access_token    (Optional)
78
     * @return array<mixed,mixed>
79
     * @throws \Exception
80
     */
81
    public static function requestApi(string $url_api, string $access_token = ''): array
82
    {
83
        try {
84
            if (self::isUrlProtocolHttp($url_api)) {
85
                $msg = 'Not in "https:" protocol. We do not allow "http:" protocol.';
86
                throw new \Exception($msg);
87
            }
88
89
            $header = [];
90
            if (! empty(trim($access_token))) {
91
                if (! self::isCompliantAccessToken($access_token)) {
92
                    $msg = 'Invalid access token format.';
93
                    throw new \Exception($msg);
94
                }
95
                $header = [
96
                    'headers' => [
97
                        'Authorization' => "Bearer ${access_token}",
98
                    ]
99
                ];
100
            }
101
102
            $client_http = HttpClient::create();
103
            $response = $client_http->request('GET', $url_api, $header);
104
105
            // Get contents as array
106
            return $response->toArray();
107
        } catch (\Exception $e) {
108
            $msg = 'Error while requesting to the server.' . PHP_EOL
109
                 . '- Error details: ' . $e->getMessage() . PHP_EOL;
110
            throw new \Exception($msg);
111
        }
112
    }
113
}
114