Completed
Push — master ( baa97e...0f40a6 )
by Vragov
05:13 queued 02:16
created

RequestService::getClient()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
cc 3
nc 2
nop 0
1
<?php
2
3
namespace OmnideskBundle\Service;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\HandlerStack;
7
use GuzzleHttp\Middleware;
8
use Psr\Http\Message\ResponseInterface;
9
10
/**
11
 * Class RequestService
12
 * @package OmnideskBundle\Service
13
 */
14
class RequestService
15
{
16
    /**
17
     * @var array
18
     */
19
    protected $config;
20
21
    /**
22
     * @var Client
23
     */
24
    protected $client;
25
26
    /**
27
     * @var int|null
28
     */
29
    protected $callsLeft;
30
31
    /**
32
     * RequestService constructor.
33
     * @param array  $config
34
     */
35
    public function __construct(array $config)
36
    {
37
        $this->client = $this->getClient();
38
        $this->config = $config;
39
    }
40
41
    /**
42
     * @return int|null
43
     */
44
    public function getCallsLeft()
45
    {
46
        return $this->callsLeft;
47
    }
48
49
    /**
50
     * @param string $url
51
     * @param array  $params
52
     * @return array
53
     */
54 View Code Duplication
    public function post($url, array $params = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
55
    {
56
        $response = $this->client->post($this->getUrl($url), [
57
            'headers' => $this->getHeaders(),
58
            'auth' => $this->getAuth(),
59
            'json' => $params,
60
        ]);
61
62
        return json_decode((string) $response->getBody(), true);
63
    }
64
65
    /**
66
     * @param string $url
67
     * @param string $name
68
     * @param array  $params
69
     * @return array
70
     */
71
    public function postMultipart($url, $name, array $params = [])
72
    {
73
        $multipart = [];
74
75
        foreach ($params as $key => $param) {
76
            if ($key !== 'attachments' && $key !== 'custom_fields') {
77
                $multipart[] = [
78
                    'name' => "{$name}[{$key}]",
79
                    'contents' => $param,
80
                ];
81
            }
82
        }
83
84
        if (isset($params['attachments']) && $attachments = (array) $params['attachments']) {
85
            foreach ($attachments as $key => $attachment) {
86
                $multipart[] = [
87
                    'name' => "{$name}[attachments][{$key}]",
88
                    'contents' => fopen($attachment, 'rb'),
89
                ];
90
            }
91
        }
92
93
        if (isset($params['custom_fields']) && $fields = (array) $params['custom_fields']) {
94
            foreach ($fields as $key => $field) {
95
                $multipart[] = [
96
                    'name' => "{$name}[custom_fields][{$key}]",
97
                    'contents' => $field,
98
                ];
99
            }
100
        }
101
102
        $response = $this->client->post($this->getUrl($url), [
103
            'auth' => $this->getAuth(),
104
            'multipart' => $multipart,
105
        ]);
106
107
        return json_decode((string) $response->getBody(), true);
108
    }
109
110
    /**
111
     * @param string $url
112
     * @param array  $params
113
     * @return array
114
     */
115 View Code Duplication
    public function get($url, array $params = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
116
    {
117
        $response = $this->client->get($this->getUrl($url), [
118
            'headers' => $this->getHeaders(),
119
            'auth' => $this->getAuth(),
120
            'query' => $params,
121
        ]);
122
123
        return json_decode((string) $response->getBody(), true);
124
    }
125
126
    /**
127
     * @param string $url
128
     * @param array  $params
129
     * @return array
130
     */
131 View Code Duplication
    public function put($url, array $params = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
132
    {
133
        $response = $this->client->put($this->getUrl($url), [
134
            'headers' => $this->getHeaders(),
135
            'auth' => $this->getAuth(),
136
            'json' => $params,
137
        ]);
138
139
        return json_decode((string) $response->getBody(), true);
140
    }
141
142
    /**
143
     * @param string $url
144
     * @return int
145
     */
146
    public function delete($url)
147
    {
148
        $response = $this->client->delete($this->getUrl($url), [
149
            'headers' => $this->getHeaders(),
150
            'auth' => $this->getAuth(),
151
        ]);
152
153
        return $response->getStatusCode();
154
    }
155
156
    /**
157
     * @return Client
158
     */
159
    protected function getClient()
160
    {
161
        if (!$this->client) {
162
            $stack = HandlerStack::create();
163
164
            $stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
165
                $this->callsLeft = $response->getHeaderLine('api_calls_left') ?: null;
0 ignored issues
show
Documentation Bug introduced by
It seems like $response->getHeaderLine...pi_calls_left') ?: null can also be of type string. However, the property $callsLeft is declared as type integer|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
166
167
                return $response;
168
            }));
169
170
            $this->client = new Client(['handler' => $stack]);
171
        }
172
173
        return $this->client;
174
    }
175
176
    /**
177
     * @param string $url
178
     * @return string
179
     */
180
    protected function getUrl($url)
181
    {
182
        return sprintf('https://%s.omnidesk.ru/api/%s.json', $this->config['domain'], $url);
183
    }
184
185
    /**
186
     * @return array
187
     */
188
    protected function getHeaders()
189
    {
190
        return [
191
            'Content-Type' => 'application/json',
192
            'Content-Length' => 0,
193
        ];
194
    }
195
196
    /**
197
     * @return array
198
     */
199
    protected function getAuth()
200
    {
201
        return [
202
            $this->config['email'],
203
            $this->config['key'],
204
        ];
205
    }
206
}
207