Completed
Push — master ( 735ffd...9b092c )
by Anton
8s
created

PartnerClient::sendRequest()   C

Complexity

Conditions 8
Paths 10

Size

Total Lines 33
Code Lines 20

Duplication

Lines 33
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 5
Bugs 2 Features 1
Metric Value
c 5
b 2
f 1
dl 33
loc 33
ccs 0
cts 21
cp 0
rs 5.3846
cc 8
eloc 20
nc 10
nop 3
crap 72
1
<?php
2
/**
3
 * Yandex PHP Library
4
 *
5
 * @copyright NIX Solutions Ltd.
6
 * @link https://github.com/nixsolutions/yandex-php-library
7
 */
8
9
/**
10
 * @namespace
11
 */
12
namespace Yandex\Market\Partner;
13
14
use Psr\Http\Message\UriInterface;
15
use Yandex\Common\AbstractServiceClient;
16
use GuzzleHttp\Psr7\Response;
17
use GuzzleHttp\Exception\ClientException;
18
use Yandex\Common\Exception\ForbiddenException;
19
use Yandex\Common\Exception\UnauthorizedException;
20
use Yandex\Market\Partner\Exception\PartnerRequestException;
21
use Yandex\Market\Partner\Models;
22
23
/**
24
 * Class PartnerClient
25
 *
26
 * @category Yandex
27
 * @package Market
28
 *
29
 * @author   Alexander Khaylo <[email protected]>
30
 * @created  04.11.13 12:48
31
 */
32
class PartnerClient extends AbstractServiceClient
33
{
34
35
    /**
36
     * Order is being processed
37
     */
38
    const ORDER_STATUS_PROCESSING = 'PROCESSING';
39
40
    /**
41
     * Order submitted to the delivery
42
     */
43
    const ORDER_STATUS_DELIVERY = 'DELIVERY';
44
45
    /**
46
     *  Order delivered to the point of self-delivery
47
     */
48
    const ORDER_STATUS_PICKUP = 'PICKUP';
49
50
    /**
51
     * The order is received by the buyer
52
     */
53
    const ORDER_STATUS_DELIVERED = 'DELIVERED';
54
55
    /**
56
     * Order canceled.
57
     */
58
    const ORDER_STATUS_CANCELLED = 'CANCELLED';
59
60
    //Sub-statuses for status CANCELLED
61
    // - the buyer is not finalized the reserved order on time
62
    const ORDER_SUBSTATUS_RESERVATION_EXPIRED = 'RESERVATION_EXPIRED';
63
    // - the buyer did not pay for the order ( for the type of payment PREPAID)
64
    const ORDER_SUBSTATUS_USER_NOT_PAID = 'USER_NOT_PAID';
65
    // - failed to communicate with the buyer
66
    const ORDER_SUBSTATUS_USER_UNREACHABLE = 'USER_UNREACHABLE';
67
    // - buyer canceled the order for cause
68
    const ORDER_SUBSTATUS_USER_CHANGED_MIND = 'USER_CHANGED_MIND';
69
    // - the buyer is not satisfied with the terms of delivery
70
    const ORDER_SUBSTATUS_USER_REFUSED_DELIVERY = 'USER_REFUSED_DELIVERY';
71
    // - the buyer did not fit the goods
72
    const ORDER_SUBSTATUS_USER_REFUSED_PRODUCT = 'USER_REFUSED_PRODUCT';
73
    // - shop can not fulfill the order
74
    const ORDER_SUBSTATUS_SHOP_FAILED = 'SHOP_FAILED';
75
    // - the buyer is not satisfied with the quality of the goods
76
    const ORDER_SUBSTATUS_USER_REFUSED_QUALITY = 'USER_REFUSED_QUALITY';
77
    // - buyer changes the composition of the order
78
    const ORDER_SUBSTATUS_REPLACING_ORDER = 'REPLACING_ORDER';
79
    //- store does not process orders on time
80
    const ORDER_SUBSTATUS_PROCESSING_EXPIRED = 'PROCESSING_EXPIRED';
81
82
    //Способ оплаты заказа
83
    //предоплата через Яндекс;
84
    const PAYMENT_METHOD_YANDEX = 'YANDEX';
85
    //предоплата напрямую магазину,
86
    //не принимающему предоплату через Яндекс.
87
    const PAYMENT_METHOD_SHOP_PREPAID = 'SHOP_PREPAID';
88
    // наличный расчет при получении заказа;
89
    const PAYMENT_METHOD_CASH_ON_DELIVERY = 'CASH_ON_DELIVERY';
90
    // оплата банковской картой при получении заказа.
91
    const PAYMENT_METHOD_CARD_ON_DELIVERY = 'CARD_ON_DELIVERY';
92
93
    //Типы доставки
94
    //курьерская доставка
95
    const DELIVERY_TYPE_DELIVERY = 'DELIVERY';
96
    //самовывоз
97
    const DELIVERY_TYPE_PICKUP = 'PICKUP';
98
    //почта
99
    const DELIVERY_TYPE_POST = 'POST';
100
101
    const ORDER_DECLINE_REASON_OUT_OF_DATE= 'OUT_OF_DATE';
102
103
    /**
104
     * Requested version of API
105
     * @var string
106
     */
107
    private $version = 'v2';
108
109
    /**
110
     * Application id
111
     *
112
     * @var string
113
     */
114
    protected $clientId;
115
116
    /**
117
     * User login
118
     *
119
     * @var string
120
     */
121
    protected $login;
122
123
    /**
124
     * Campaign Id
125
     *
126
     * @var string
127
     */
128
    protected $campaignId;
129
130
    /**
131
     * API domain
132
     *
133
     * @var string
134
     */
135
    protected $serviceDomain = 'api.partner.market.yandex.ru';
136
137
    /**
138
     * Get url to service resource with parameters
139
     *
140
     * @param string $resource
141
     * @see http://api.yandex.ru/market/partner/doc/dg/concepts/method-call.xml
142
     * @return string
143
     */
144 1
    public function getServiceUrl($resource = '')
145
    {
146 1
        return $this->serviceScheme . '://' . $this->serviceDomain . '/'
147 1
        . $this->version . '/' . $resource;
148
    }
149
150
    /**
151
     * @param string $token access token
152
     */
153 1
    public function __construct($token = '')
154
    {
155 1
        $this->setAccessToken($token);
156 1
    }
157
158
    /**
159
     * @param string $clientId
160
     */
161
    public function setClientId($clientId)
162
    {
163
        $this->clientId = $clientId;
164
    }
165
166
    /**
167
     * @param string $login
168
     */
169
    public function setLogin($login)
170
    {
171
        $this->login = $login;
172
    }
173
174
    /**
175
     * @param string $campaignId
176
     */
177
    public function setCampaignId($campaignId)
178
    {
179
        $this->campaignId = $campaignId;
180
    }
181
182
    /**
183
     * @return string
184
     */
185
    public function getClientId()
186
    {
187
        return $this->clientId;
188
    }
189
190
    /**
191
     * @return string
192
     */
193
    public function getLogin()
194
    {
195
        return $this->login;
196
    }
197
198
    /**
199
     * Sends a request
200
     *
201
     * @param string              $method  HTTP method
202
     * @param string|UriInterface $uri     URI object or string.
203
     * @param array               $options Request options to apply.
204
     *
205
     * @return Response
206
     *
207
     * @throws ForbiddenException
208
     * @throws UnauthorizedException
209
     * @throws PartnerRequestException
210
     */
211 View Code Duplication
    protected function sendRequest($method, $uri, array $options = [])
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...
212
    {
213
        try {
214
            $response = $this->getClient()->request($method, $uri, $options);
0 ignored issues
show
Bug introduced by
It seems like $uri defined by parameter $uri on line 211 can also be of type object<Psr\Http\Message\UriInterface>; however, GuzzleHttp\Client::request() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
215
        } catch (ClientException $ex) {
216
            $result = $ex->getResponse();
217
            $code = $result->getStatusCode();
218
            $message = $result->getReasonPhrase();
219
220
            $body = $result->getBody();
221
            if ($body) {
222
                $jsonBody = json_decode($body);
223
                if ($jsonBody && isset($jsonBody->error) && isset($jsonBody->error->message)) {
224
                    $message = $jsonBody->error->message;
225
                }
226
            }
227
228
            if ($code === 403) {
229
                throw new ForbiddenException($message);
230
            }
231
232
            if ($code === 401) {
233
                throw new UnauthorizedException($message);
234
            }
235
236
            throw new PartnerRequestException(
237
                'Service responded with error code: "' . $code . '" and message: "' . $message . '"',
238
                $code
239
            );
240
        }
241
242
        return $response;
243
    }
244
245
    /**
246
     * Get OAuth data for header request
247
     *
248
     * @see http://api.yandex.ru/market/partner/doc/dg/concepts/authorization.xml
249
     *
250
     * @return string
251
     */
252
    public function getAccessToken()
253
    {
254
        return 'oauth_token=' . parent::getAccessToken() . ', oauth_client_id=' . $this->getClientId()
255
        . ', oauth_login=' . $this->getLogin();
256
    }
257
258
    /**
259
     * Get User Campaigns
260
     *
261
     * Returns the user to the list of campaigns Yandex.market.
262
     * The list coincides with the list of campaigns
263
     * that are displayed in the partner interface Yandex.Market on page "My shops."
264
     *
265
     * @see http://api.yandex.ru/market/partner/doc/dg/reference/get-campaigns.xml
266
     *
267
     * @return Models\Campaigns
268
     */
269
    public function getCampaigns()
270
    {
271
        $resource = 'campaigns.json';
272
273
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
274
275
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
276
277
        $getCampaignsResponse = new Models\GetCampaignsResponse($decodedResponseBody);
278
        return $getCampaignsResponse->getCampaigns();
279
    }
280
281
282
    /**
283
     * Get information about orders by campaign id
284
     *
285
     * @param array $params
286
     *
287
     * Returns information on the requested orders.
288
     * Available filtering by date ordering and order status.
289
     * The maximum range of dates in a single request for a resource - 30 days.
290
     *
291
     * @see http://api.yandex.ru/market/partner/doc/dg/reference/get-campaigns-id-orders.xml
292
     *
293
     * @return Models\GetOrdersResponse
294
     */
295
    public function getOrdersResponse($params = [])
296
    {
297
        $resource = 'campaigns/' . $this->campaignId . '/orders.json';
298
        $resource .= '?' . http_build_query($params);
299
300
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
301
302
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
303
304
        return new Models\GetOrdersResponse($decodedResponseBody);
305
    }
306
307
308
    /**
309
     * Get only orders data without pagination
310
     *
311
     * @param array $params
312
     * @return null|Models\Orders
313
     */
314
    public function getOrders($params = [])
315
    {
316
        return $this->getOrdersResponse($params)->getOrders();
317
    }
318
319
320
    /**
321
     * Get order info
322
     *
323
     * @param int $orderId
324
     * @return Models\Order
325
     *
326
     * @link http://api.yandex.ru/market/partner/doc/dg/reference/get-campaigns-id-orders-id.xml
327
     */
328 1 View Code Duplication
    public function getOrder($orderId)
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...
329 1
    {
330 1
        $resource = 'campaigns/' . $this->campaignId . '/orders/' . $orderId . '.json';
331
332 1
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
333
334 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
335
336 1
        $getOrderResponse = new Models\GetOrderResponse($decodedResponseBody);
337 1
        return $getOrderResponse->getOrder();
338
    }
339
340
341
    /**
342
     * Send changed status to Yandex.Market
343
     *
344
     * @param int $orderId
345
     * @param string $status
346
     * @param null|string $subStatus
347
     * @return Models\Order
348
     *
349
     * @link http://api.yandex.ru/market/partner/doc/dg/reference/put-campaigns-id-orders-id-status.xml
350
     */
351
    public function setOrderStatus($orderId, $status, $subStatus = null)
352
    {
353
        $resource = 'campaigns/' . $this->campaignId . '/orders/' . $orderId . '/status.json';
354
355
        $data = [
356
            "order" => [
357
                "status" => $status
358
            ]
359
        ];
360
        if ($subStatus) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $subStatus of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
361
            $data['order']['substatus'] = $subStatus;
362
        }
363
364
        $response = $this->sendRequest(
365
            'PUT',
366
            $this->getServiceUrl($resource),
367
            [
368
                'json' => $data
369
            ]
370
        );
371
372
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
373
374
        $updateOrderStatusResponse = new Models\UpdateOrderStatusResponse($decodedResponseBody);
375
        return $updateOrderStatusResponse->getOrder();
376
    }
377
378
379
    /**
380
     * Update changed delivery parameters
381
     *
382
     * @param int $orderId
383
     * @param Models\Delivery $delivery
384
     * @return Models\Order
385
     *
386
     * Example:
387
     * PUT /v2/campaigns/10003/order/12345/delivery.json HTTP/1.1
388
     *
389
     * @link http://api.yandex.ru/market/partner/doc/dg/reference/put-campaigns-id-orders-id-delivery.xml
390
     */
391 View Code Duplication
    public function updateDelivery($orderId, Models\Delivery $delivery)
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...
392
    {
393
        $resource = 'campaigns/' . $this->campaignId . '/orders/' . $orderId . '/delivery.json';
394
395
        $response = $this->sendRequest(
396
            'PUT',
397
            $this->getServiceUrl($resource),
398
            [
399
                'json' => $delivery->toArray()
400
401
            ]
402
        );
403
404
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
405
406
        $updateOrderDeliveryResponse = new Models\UpdateOrderDeliveryResponse($decodedResponseBody);
407
        return $updateOrderDeliveryResponse->getOrder();
408
    }
409
}
410