UnleashedAPI   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 130
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 67
dl 0
loc 130
rs 10
c 1
b 0
f 0
wmc 12

1 Method

Rating   Name   Duplication   Size   Complexity  
F sendCall() 0 89 12
1
<?php
2
3
namespace AntonyThorpe\SilverShopUnleashed;
4
5
use GuzzleHttp\Client;
0 ignored issues
show
Bug introduced by
The type GuzzleHttp\Client 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...
6
use GuzzleHttp\Exception\ClientException;
0 ignored issues
show
Bug introduced by
The type GuzzleHttp\Exception\ClientException 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...
7
use Monolog\Handler\StreamHandler;
0 ignored issues
show
Bug introduced by
The type Monolog\Handler\StreamHandler 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...
8
use Monolog\Level;
0 ignored issues
show
Bug introduced by
The type Monolog\Level 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...
9
use Monolog\Logger;
0 ignored issues
show
Bug introduced by
The type Monolog\Logger 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...
10
use Monolog\Formatter\LineFormatter;
0 ignored issues
show
Bug introduced by
The type Monolog\Formatter\LineFormatter 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...
11
use SilverStripe\Core\Config\Configurable;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Core\Config\Configurable 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...
12
13
/**
14
 * Settings to incorporate Unleashed API into a Guzzle Http Client
15
 * @link https://apidocs.unleashedsoftware.com/AuthenticationHelp
16
 */
17
class UnleashedAPI
18
{
19
    use Configurable;
20
21
    /**
22
     * Log calls if failed
23
     */
24
    private static bool $logfailedcalls = false;
0 ignored issues
show
introduced by
The private property $logfailedcalls is not used, and could be removed.
Loading history...
25
26
    /**
27
     * Log calls if failed
28
     */
29
    private static bool $logsuccessfulcalls = false;
0 ignored issues
show
introduced by
The private property $logsuccessfulcalls is not used, and could be removed.
Loading history...
30
31
    /**
32
     * Guzzle debug setting
33
     */
34
    private static bool $debug = false;
0 ignored issues
show
introduced by
The private property $debug is not used, and could be removed.
Loading history...
35
36
    /**
37
     * id from Unleashed
38
     */
39
    private static string $id = '';
0 ignored issues
show
introduced by
The private property $id is not used, and could be removed.
Loading history...
40
41
    /**
42
     * key from Unleashed
43
     */
44
    private static string $key = '';
0 ignored issues
show
introduced by
The private property $key is not used, and could be removed.
Loading history...
45
46
    /**
47
     * For the header to enable API tracking
48
     */
49
    private static string $client_type = '';
0 ignored issues
show
introduced by
The private property $client_type is not used, and could be removed.
Loading history...
50
51
    /**
52
     * Send asynchronous request to Restful endpoint
53
     * @param string $method Http Request Method
54
     * @param string $uri the Restful endpoint and query
55
     * @param array $options for Guzzle Request
56
     * @return mixed either the Guzzle Response Interface or an Guzzle Request Exception
57
     */
58
    public static function sendCall(string $method, string $uri, array $options = []): mixed
59
    {
60
        $config = [];
61
        if ($uri !== '' && $uri !== '0') {
62
            $config['base_url'] = $uri;
63
        }
64
65
        if (isset($options['query'])) {
66
            $config['query'] = $options['query'];
67
        }
68
69
        // create the params for the base64_enclose
70
        $params = '';
71
        if (isset($config['base_url'])) {
72
            $params = parse_url($config['base_url'], PHP_URL_QUERY) ?? '';
73
        }
74
75
        if (isset($config['query'])) {
76
            if ($params) {
77
                $params .= '&';
78
            }
79
80
            $params .= urldecode(http_build_query($config['query']));
81
        }
82
83
        // add the headers
84
        $config['headers'] = [
85
            'Content-Type' => 'application/json',
86
            'Accept' => 'application/json',
87
            'api-auth-id' => static::config()->get('id'),
88
            'api-auth-signature' => base64_encode(hash_hmac('sha256', $params, (string) static::config()->get('key'), true))
89
        ];
90
91
        if (static::config()->get('client_type')) {
92
            $config['headers']['client-type'] = static::config()->get('client_type');
93
        }
94
95
        // finish params for the base64_enclose
96
97
        $client = new Client($config);
98
99
        if (static::config()->get('debug')) {
100
            $options['debug'] = true;
101
        }
102
103
        try {
104
            $response = $client->request($method, $uri, $options);
105
            if (static::config()->get('logsuccessfulcalls')) {
106
                $line_formatter = new LineFormatter(
107
                    null, // Format of message in log, default [%datetime%] %channel%.%level_name%: %message% %context% %extra%\n
108
                    null, // Datetime format
109
                    true, // allowInlineLineBreaks option, default false
110
                    true  // discard empty Square brackets in the end, default false
111
                );
112
                $logger = new Logger(_t('UnleashedAPI.UnleashedSuccessful', 'unleashed-successful'));
0 ignored issues
show
Bug introduced by
The function _t was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

112
                $logger = new Logger(/** @scrutinizer ignore-call */ _t('UnleashedAPI.UnleashedSuccessful', 'unleashed-successful'));
Loading history...
113
                $stream_handler = new StreamHandler(_t('UnleashedAPI.UnleashedSuccessfulFilename', './z_unleashed-successful.log'), Level::Info);
114
                $stream_handler->setFormatter($line_formatter);
115
                $logger->pushHandler($stream_handler);
116
                $logger->info(_t('UnleashedAPI.RequestSuccessTitle', 'Request successful') . '\n');
117
                $logger->info(_t('UnleashedAPI.Method', 'Request method: ') . $method);
118
                $logger->info(_t('UnleashedAPI.Uri', 'Request uri: ') . $uri);
119
                $logger->info(_t('UnleashedAPI.Options', 'Request options: '));
120
                $logger->info(print_r($options, true));
121
                $logger->info(_t('UnleashedAPI.ResponseContent', 'Response Content: '));
122
                $logger->info(print_r($response->getBody()->getContents(), true));
123
            }
124
125
            return $response;
126
127
        } catch (ClientException $clientException) {
128
            if (static::config()->get('logfailedcalls')) {
129
                $line_formatter = new LineFormatter(
130
                    null, // Format of message in log, default [%datetime%] %channel%.%level_name%: %message% %context% %extra%\n
131
                    null, // Datetime format
132
                    true, // allowInlineLineBreaks option, default false
133
                    true  // discard empty Square brackets in the end, default false
134
                );
135
                $logger = new Logger(_t('UnleashedAPI.UnleashedClientException', 'unleashed-client-exception'));
136
                $stream_handler = new StreamHandler(_t('UnleashedAPI.UnleashedClientExceptionFilename', './z_unleashed-client-exception.log'), Level::Info);
137
                $stream_handler->setFormatter($line_formatter);
138
                $logger->pushHandler($stream_handler);
139
                $logger->info(_t('UnleashedAPI.ClientExceptionTitle', 'Request failed'). '\n');
140
                $logger->info($clientException->getMessage());
141
                $logger->info(print_r($clientException->getResponse()->getBody()->getContents(), true));
142
                $logger->info($clientException->getRequest()->getMethod());
143
                $logger->info(print_r($clientException->getRequest()->getHeaders(), true));
144
            }
145
146
            return $clientException;
147
        }
148
    }
149
}
150