Passed
Push — master ( 796371...61ca61 )
by Andrey
03:07
created

NovaPoshta::getResponse()   F

Complexity

Conditions 19
Paths 258

Size

Total Lines 99
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

Changes 9
Bugs 1 Features 0
Metric Value
cc 19
eloc 55
nc 258
nop 4
dl 0
loc 99
rs 2.9583
c 9
b 1
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Daaner\NovaPoshta;
4
5
use Daaner\NovaPoshta\Contracts\NovaPoshtaInterface;
6
use Exception;
7
use Illuminate\Support\Facades\Http;
8
use Illuminate\Support\Facades\Log;
9
10
class NovaPoshta implements NovaPoshtaInterface
11
{
12
    protected $baseUri;
13
    protected $point;
14
15
    protected $api;
16
    protected $url;
17
    protected $dev;
18
19
    /**
20
     * NovaPoshta constructor main settings.
21
     */
22
    public function __construct()
23
    {
24
        $this->baseUri = config('novaposhta.base_uri');
25
        $this->point = config('novaposhta.point');
26
        $this->dev = config('novaposhta.dev');
27
        $this->getApi();
28
        $this->url = $this->baseUri.$this->point;
29
    }
30
31
    /**
32
     * @return string
33
     */
34
    public function getApi(): string
35
    {
36
        if (! $this->api) {
37
            $this->api = config('novaposhta.api_key');
38
        }
39
40
        return $this->api;
41
    }
42
43
    /**
44
     * Устанавливаем другой API ключ.
45
     *
46
     * @param  string  $api
47
     */
48
    public function setApi(string $api): void
49
    {
50
        $this->api = $api;
51
    }
52
53
    /**
54
     * @param  string  $model
55
     * @param  string  $calledMethod
56
     * @param  array|null  $methodProperties
57
     * @param  bool  $auth
58
     * @return array
59
     */
60
    public function getResponse(string $model, string $calledMethod, ?array $methodProperties, bool $auth = true): array
61
    {
62
        $url = $this->url.'/'.$model.'/'.$calledMethod;
63
        $body = [];
64
        $info = '';
65
66
        $body['modelName'] = $model;
67
        $body['calledMethod'] = $calledMethod;
68
        $body['methodProperties'] = $methodProperties;
69
70
        if ($auth) {
71
            $body['apiKey'] = $this->api;
72
        }
73
74
        $response = Http::timeout(config('novaposhta.http_response_timeout', 3))
75
            ->retry(config('novaposhta.http_retry_max_time', 2), config('novaposhta.http_retry_delay', 200))
76
            ->withHeaders([
77
                'Accept' => 'application/json',
78
                'Content-Type' => 'application/json',
79
            ])
80
            ->post($url, $body);
81
82
        if ($response->failed()) {
83
            return [
84
                'success' => false,
85
                'result' => null,
86
                'info' => trans('novaposhta::novaposhta.error_data'),
87
            ];
88
        }
89
90
        $answer = $response->json();
91
        if ($auth === false && isset($answer[0])) {
92
            /**
93
             * Костыль для Новой Почты.
94
             * Спасибо Вам большое, что нормально не выдаете ответ :).
95
             */
96
            $answer = $answer[0];
97
        }
98
99
        if (! isset($answer['success']) || ! isset($answer['data']) || empty($answer['data'])) {
100
            /**
101
             * Что-то не так в ответе.
102
             */
103
            $info = trans('novaposhta::novaposhta.error_answer');
0 ignored issues
show
Unused Code introduced by
The assignment to $info is dead and can be removed.
Loading history...
104
            $success = false;
105
            $result = null;
106
        } else {
107
            $success = $answer['success'];
108
            $result = $answer['data'];
109
        }
110
111
        /**
112
         * Ошибки, либо уведомления.
113
         */
114
        $info = [];
115
        if (isset($answer['warnings']) && $answer['warnings']) {
116
            $info['warnings'] = $answer['warnings'];
117
118
            if ($answer['errors']) {
119
                $info['errors'] = $answer['errors'];
120
                if ($answer['errorCodes']) {
121
                    foreach ($answer['errorCodes'] as $err) {
122
                        $info['StatusCode'] = $err;
123
                        $info['StatusLocale'] = __('novaposhta::novaposhta.statusCode.'.$err);
124
                    }
125
                }
126
            }
127
        }
128
129
        if (! $info && isset($answer['info']) && $answer['info']) {
130
            $info['info'] = $answer['info'];
131
        }
132
133
        $return = [
134
            'success' => $success,
135
            'result' => $result,
136
            'info' => $info,
137
        ];
138
139
        if ($this->dev) {
140
            /**
141
             * Test and Dev.
142
             */
143
            Log::debug('= = = = = = = = = = = = = = = = = = = =');
144
            Log::debug($model.' / '.$calledMethod.' // apiKey: '.$auth);
145
            Log::debug('--------------------');
146
147
            if ($methodProperties) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $methodProperties of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
148
                try {
149
                    Log::notice(json_encode($methodProperties));
150
                } catch (Exception $e) {
151
                    Log::notice('method json_encode error');
152
                }
153
            }
154
155
            $return['dev'] = $answer;
156
        }
157
158
        return $return;
159
    }
160
}
161