Completed
Push — master ( b8323d...c7c022 )
by Anton
06:31 queued 04:22
created

PartnerClient::getLoginsByCampaign()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 10
ccs 5
cts 5
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
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\Common\StringCollection;
21
use Yandex\Market\Partner\Exception\PartnerRequestException;
22
use Yandex\Market\Partner\Models;
23
24
/**
25
 * Class PartnerClient
26
 *
27
 * @category Yandex
28
 * @package Market
29
 *
30
 * @author   Alexander Khaylo <[email protected]>
31
 * @created  04.11.13 12:48
32
 */
33
class PartnerClient extends AbstractServiceClient
34
{
35
36
    /**
37
     * Order is being processed
38
     */
39
    const ORDER_STATUS_PROCESSING = 'PROCESSING';
40
41
    /**
42
     * Order submitted to the delivery
43
     */
44
    const ORDER_STATUS_DELIVERY = 'DELIVERY';
45
46
    /**
47
     *  Order delivered to the point of self-delivery
48
     */
49
    const ORDER_STATUS_PICKUP = 'PICKUP';
50
51
    /**
52
     * The order is received by the buyer
53
     */
54
    const ORDER_STATUS_DELIVERED = 'DELIVERED';
55
56
    /**
57
     * Order canceled.
58
     */
59
    const ORDER_STATUS_CANCELLED = 'CANCELLED';
60
61
    //Sub-statuses for status CANCELLED
62
    // - the buyer is not finalized the reserved order on time
63
    const ORDER_SUBSTATUS_RESERVATION_EXPIRED = 'RESERVATION_EXPIRED';
64
    // - the buyer did not pay for the order ( for the type of payment PREPAID)
65
    const ORDER_SUBSTATUS_USER_NOT_PAID = 'USER_NOT_PAID';
66
    // - failed to communicate with the buyer
67
    const ORDER_SUBSTATUS_USER_UNREACHABLE = 'USER_UNREACHABLE';
68
    // - buyer canceled the order for cause
69
    const ORDER_SUBSTATUS_USER_CHANGED_MIND = 'USER_CHANGED_MIND';
70
    // - the buyer is not satisfied with the terms of delivery
71
    const ORDER_SUBSTATUS_USER_REFUSED_DELIVERY = 'USER_REFUSED_DELIVERY';
72
    // - the buyer did not fit the goods
73
    const ORDER_SUBSTATUS_USER_REFUSED_PRODUCT = 'USER_REFUSED_PRODUCT';
74
    // - shop can not fulfill the order
75
    const ORDER_SUBSTATUS_SHOP_FAILED = 'SHOP_FAILED';
76
    // - the buyer is not satisfied with the quality of the goods
77
    const ORDER_SUBSTATUS_USER_REFUSED_QUALITY = 'USER_REFUSED_QUALITY';
78
    // - buyer changes the composition of the order
79
    const ORDER_SUBSTATUS_REPLACING_ORDER = 'REPLACING_ORDER';
80
    //- store does not process orders on time
81
    const ORDER_SUBSTATUS_PROCESSING_EXPIRED = 'PROCESSING_EXPIRED';
82
83
    //Способ оплаты заказа
84
    //предоплата через Яндекс;
85
    const PAYMENT_METHOD_YANDEX = 'YANDEX';
86
    //предоплата напрямую магазину,
87
    //не принимающему предоплату через Яндекс.
88
    const PAYMENT_METHOD_SHOP_PREPAID = 'SHOP_PREPAID';
89
    // наличный расчет при получении заказа;
90
    const PAYMENT_METHOD_CASH_ON_DELIVERY = 'CASH_ON_DELIVERY';
91
    // оплата банковской картой при получении заказа.
92
    const PAYMENT_METHOD_CARD_ON_DELIVERY = 'CARD_ON_DELIVERY';
93
94
    //Типы доставки
95
    //курьерская доставка
96
    const DELIVERY_TYPE_DELIVERY = 'DELIVERY';
97
    //самовывоз
98
    const DELIVERY_TYPE_PICKUP = 'PICKUP';
99
    //почта
100
    const DELIVERY_TYPE_POST = 'POST';
101
102
    const ORDER_DECLINE_REASON_OUT_OF_DATE = 'OUT_OF_DATE';
103
104
    /**
105
     * Requested version of API
106
     * @var string
107
     */
108
    private $version = 'v2';
109
110
    /**
111
     * Application id
112
     *
113
     * @var string
114
     */
115
    protected $clientId;
116
117
    /**
118
     * User login
119
     *
120
     * @var string
121
     */
122
    protected $login;
123
124
    /**
125
     * Campaign Id
126
     *
127
     * @var string
128
     */
129
    protected $campaignId;
130
131
    /**
132
     * API domain
133
     *
134
     * @var string
135
     */
136
    protected $serviceDomain = 'api.partner.market.yandex.ru';
137
138
    /**
139
     * Get url to service resource with parameters
140
     *
141
     * @param string $resource
142
     * @see http://api.yandex.ru/market/partner/doc/dg/concepts/method-call.xml
143
     * @return string
144
     */
145 17
    public function getServiceUrl($resource = '')
146
    {
147 17
        return $this->serviceScheme . '://' . $this->serviceDomain . '/'
148 17
        . $this->version . '/' . $resource;
149
    }
150
151
    /**
152
     * @param string $token access token
153
     */
154 19
    public function __construct($token = '')
155
    {
156 19
        $this->setAccessToken($token);
157 19
    }
158
159
    /**
160
     * @param string $clientId
161
     */
162 1
    public function setClientId($clientId)
163
    {
164 1
        $this->clientId = $clientId;
165 1
    }
166
167
    /**
168
     * @param string $login
169
     */
170 1
    public function setLogin($login)
171
    {
172 1
        $this->login = $login;
173 1
    }
174
175
    /**
176
     * @param string $campaignId
177
     */
178 1
    public function setCampaignId($campaignId)
179
    {
180 1
        $this->campaignId = $campaignId;
181 1
    }
182
183
    /**
184
     * @return string
185
     */
186 1
    public function getCampaignId()
187
    {
188 1
        return $this->campaignId;
189
    }
190
191
    /**
192
     * @return string
193
     */
194 1
    public function getClientId()
195
    {
196 1
        return $this->clientId;
197
    }
198
199
    /**
200
     * @return string
201
     */
202 1
    public function getLogin()
203
    {
204 1
        return $this->login;
205
    }
206
207
    /**
208
     * Sends a request
209
     *
210
     * @param string $method HTTP method
211
     * @param string $uri URI object or string.
212
     * @param array $options Request options to apply.
213
     *
214
     * @return Response
215
     *
216
     * @throws ForbiddenException
217
     * @throws UnauthorizedException
218
     * @throws PartnerRequestException
219
     */
220 5 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...
221
    {
222
        try {
223 5
            $response = $this->getClient()->request($method, $uri, $options);
224 5
        } catch (ClientException $ex) {
225 4
            $result = $ex->getResponse();
226 4
            $code = $result->getStatusCode();
227 4
            $message = $result->getReasonPhrase();
228
229 4
            $body = $result->getBody();
230 4
            if ($body) {
231 4
                $jsonBody = json_decode($body);
232 4
                if ($jsonBody && isset($jsonBody->error) && isset($jsonBody->error->message)) {
233 1
                    $message = $jsonBody->error->message;
234 1
                }
235 4
            }
236
237 4
            if ($code === 403) {
238 1
                throw new ForbiddenException($message);
239
            }
240
241 3
            if ($code === 401) {
242 2
                throw new UnauthorizedException($message);
243
            }
244
245 1
            throw new PartnerRequestException(
246 1
                'Service responded with error code: "' . $code . '" and message: "' . $message . '"',
247
                $code
248 1
            );
249
        }
250
251 1
        return $response;
252
    }
253
254
    /**
255
     * Get OAuth data for header request
256
     *
257
     * @see http://api.yandex.ru/market/partner/doc/dg/concepts/authorization.xml
258
     *
259
     * @return string
260
     */
261 1
    public function getAccessToken()
262
    {
263 1
        return 'oauth_token=' . parent::getAccessToken() . ', oauth_client_id=' . $this->getClientId()
264 1
        . ', oauth_login=' . $this->getLogin();
265
    }
266
267
    /**
268
     * Get Balance Campaign
269
     * @link https://tech.yandex.ru/market/partner/doc/dg/reference/get-campaigns-id-balance-docpage/
270
     *
271
     * @return Models\Balance
272
     */
273 1 View Code Duplication
    public function getBalance()
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...
274
    {
275 1
        $resource = 'campaigns/' . $this->campaignId . '/balance.json';
276
277 1
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
278
279 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
280
281 1
        $getBalanceResponse = new Models\GetBalanceResponse($decodedResponseBody);
282 1
        return $getBalanceResponse->getBalance();
283
    }
284
285
    /**
286
     * Get User Campaigns
287
     *
288
     * Returns the user to the list of campaigns Yandex.market.
289
     * The list coincides with the list of campaigns
290
     * that are displayed in the partner interface Yandex.Market on page "My shops."
291
     *
292
     * @see http://api.yandex.ru/market/partner/doc/dg/reference/get-campaigns.xml
293
     *
294
     * @return Models\Campaigns
295
     */
296 1 View Code Duplication
    public function getCampaigns()
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...
297
    {
298 1
        $resource = 'campaigns.json';
299
300 1
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
301
302 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
303
304 1
        $getCampaignsResponse = new Models\GetCampaignsResponse($decodedResponseBody);
305 1
        return $getCampaignsResponse->getCampaigns();
306
    }
307
    
308
    /**
309
     * Get User Campaigns by Login
310
     *
311
     * @link https://tech.yandex.ru/market/partner/doc/dg/reference/get-campaigns-by-login-docpage/
312
     *
313
     * @return Models\Campaigns
314
     */
315 View Code Duplication
    public function getCampaignsByLogin($login)
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...
316
    {
317
        $resource = 'campaigns/by_login/' . $login . '.json';
318
319
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
320
321
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
322
323
        $getCampaignsResponse = new Models\GetCampaignsResponse($decodedResponseBody);
324
        return $getCampaignsResponse->getCampaigns();
325
    }
326
327
    /**
328
     * Get logins by campaign id
329
     *
330
     * @link https://tech.yandex.ru/market/partner/doc/dg/reference/get-campaigns-id-logins-docpage/
331
     *
332
     * @return StringCollection
333
     */
334 1
    public function getLoginsByCampaign()
335
    {
336 1
        $resource = 'campaigns/' . $this->campaignId . '/logins.json';
337
338 1
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
339
340 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
341
342 1
        return StringCollection::init($decodedResponseBody['logins']);
343
    }
344
345
    /**
346
     * Get outlets by campaign id
347
     * @param array $params ['page' => (int) 0-100, 'pageSize' => (int) 50]
348
     *
349
     * @link https://tech.yandex.ru/market/partner/doc/dg/reference/get-campaigns-id-outlets-docpage/
350
     *
351
     * @return Models\GetOutletsResponse
352
     */
353 1
    public function getOutletsResponse($params = [])
354
    {
355 1
        $resource = 'campaigns/' . $this->campaignId . '/outlets.json';
356 1
        $resource .= '?' . http_build_query($params);
357
358 1
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
359
360 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
361
362 1
        return new Models\GetOutletsResponse($decodedResponseBody);
363
    }
364
365
    /**
366
     * Get only outlets data without pagination
367
     *
368
     * @param array $params
369
     * @return null|Models\Outlets
370
     */
371
    public function getOutlets($params = [])
372
    {
373
        return $this->getOutletsResponse($params)->getOutlets();
374
    }
375
376
    /**
377
     * Get outlet info
378
     *
379
     * @param $outletId
380
     *
381
     * @link https://tech.yandex.ru/market/partner/doc/dg/reference/get-campaigns-id-outlets-id-docpage/
382
     *
383
     * @return null|Models\Outlet
384
     */
385 1
    public function getOutlet($outletId)
386
    {
387 1
        $resource = 'campaigns/' . $this->campaignId . '/outlets/' . $outletId . '.json';
388
389 1
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
390
391 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
392
393 1
        $getOrderResponse = new Models\GetOutletResponse($decodedResponseBody);
394 1
        return $getOrderResponse->getOutlet();
395
    }
396
397
398
    /**
399
     * Get information about orders by campaign id
400
     *
401
     * @param array $params
402
     *
403
     * Returns information on the requested orders.
404
     * Available filtering by date ordering and order status.
405
     * The maximum range of dates in a single request for a resource - 30 days.
406
     *
407
     * @see http://api.yandex.ru/market/partner/doc/dg/reference/get-campaigns-id-orders.xml
408
     *
409
     * @return Models\GetOrdersResponse
410
     */
411 1
    public function getOrdersResponse($params = [])
412
    {
413 1
        $resource = 'campaigns/' . $this->campaignId . '/orders.json';
414 1
        $resource .= '?' . http_build_query($params);
415
416 1
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
417
418 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
419
420 1
        return new Models\GetOrdersResponse($decodedResponseBody);
421
    }
422
423
    /**
424
     * Get only orders data without pagination
425
     *
426
     * @param array $params
427
     * @return null|Models\Orders
428
     */
429 1
    public function getOrders($params = [])
430
    {
431 1
        return $this->getOrdersResponse($params)->getOrders();
432
    }
433
434
    /**
435
     * Get order info
436
     *
437
     * @param int $orderId
438
     * @return Models\Order
439
     *
440
     * @link http://api.yandex.ru/market/partner/doc/dg/reference/get-campaigns-id-orders-id.xml
441
     */
442 6 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...
443
    {
444 6
        $resource = 'campaigns/' . $this->campaignId . '/orders/' . $orderId . '.json';
445
446 6
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
447
448 2
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
449
450 2
        $getOrderResponse = new Models\GetOrderResponse($decodedResponseBody);
451 2
        return $getOrderResponse->getOrder();
452
    }
453
454
    /**
455
     * Get Region
456
     *
457
     * @return Models\Region
458
     *
459
     * @link https://tech.yandex.ru/market/partner/doc/dg/reference/get-campaigns-id-region-docpage/
460
     */
461 1 View Code Duplication
    public function getRegion()
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...
462
    {
463 1
        $resource = 'campaigns/' . $this->campaignId . '/region.json';
464
465 1
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
466
467 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
468 1
        $getRegionResponse = new Models\GetRegionResponse($decodedResponseBody);
469 1
        return $getRegionResponse->getRegion();
470
    }
471
472
    /**
473
     * Get Campaign settings
474
     *
475
     * @retun Models\Settings
476
     *
477
     * @link https://tech.yandex.ru/market/partner/doc/dg/reference/get-campaigns-id-settings-docpage/
478
     */
479 1 View Code Duplication
    public function getSettings()
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...
480
    {
481 1
        $resource = 'campaigns/' . $this->campaignId . '/settings.json';
482
       
483 1
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
484
485 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
486
       
487 1
        $getSettingsResponse = new Models\GetSettingsResponse($decodedResponseBody);
488 1
        return $getSettingsResponse->getSettings();
489
    }
490
  
491
    /**
492
     * @param $method [main | main-daily | main-weekly | main-monthly]
493
     * @param array $params
494
     * @return Models\Stats
495
     *
496
     * @link https://tech.yandex.ru/market/partner/doc/dg/reference/get-campaigns-id-stats-main-docpage/
497
     */
498 1
    public function getStats($method, $params = [])
499
    {
500 1
        $resource = 'campaigns/' . $this->campaignId . '/stats/' . $method . '.json';
501 1
        $resource .= '?' . http_build_query($params);
502
503 1
        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));
504
505 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
506
507 1
        $getStatsResponse = new Models\GetStatsResponse($decodedResponseBody);
508 1
        return $getStatsResponse->getMainStats();
509
    }
510
511
    /**
512
     * Send changed status to Yandex.Market
513
     *
514
     * @param int $orderId
515
     * @param string $status
516
     * @param null|string $subStatus
517
     * @return Models\Order
518
     *
519
     * @link http://api.yandex.ru/market/partner/doc/dg/reference/put-campaigns-id-orders-id-status.xml
520
     */
521 1
    public function setOrderStatus($orderId, $status, $subStatus = null)
522
    {
523 1
        $resource = 'campaigns/' . $this->campaignId . '/orders/' . $orderId . '/status.json';
524
525
        $data = [
526
            "order" => [
527
                "status" => $status
528 1
            ]
529 1
        ];
530 1
        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...
531 1
            $data['order']['substatus'] = $subStatus;
532 1
        }
533
534 1
        $response = $this->sendRequest(
535 1
            'PUT',
536 1
            $this->getServiceUrl($resource),
537
            [
538
                'json' => $data
539 1
            ]
540 1
        );
541
542 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
543
544 1
        $updateOrderStatusResponse = new Models\UpdateOrderStatusResponse($decodedResponseBody);
545 1
        return $updateOrderStatusResponse->getOrder();
546
    }
547
548
549
    /**
550
     * Update changed delivery parameters
551
     *
552
     * @param int $orderId
553
     * @param Models\Delivery $delivery
554
     * @return Models\Order
555
     *
556
     * Example:
557
     * PUT /v2/campaigns/10003/order/12345/delivery.json HTTP/1.1
558
     *
559
     * @link http://api.yandex.ru/market/partner/doc/dg/reference/put-campaigns-id-orders-id-delivery.xml
560
     */
561 1
    public function updateDelivery($orderId, Models\Delivery $delivery)
562
    {
563 1
        $resource = 'campaigns/' . $this->campaignId . '/orders/' . $orderId . '/delivery.json';
564
565 1
        $response = $this->sendRequest(
566 1
            'PUT',
567 1
            $this->getServiceUrl($resource),
568
            [
569
                'json' => [
570 1
                    'delivery' => $delivery->toArray()
571 1
                ]
572 1
            ]
573 1
        );
574
575 1
        $decodedResponseBody = $this->getDecodedBody($response->getBody());
576
577 1
        $updateOrderDeliveryResponse = new Models\UpdateOrderDeliveryResponse($decodedResponseBody);
578 1
        return $updateOrderDeliveryResponse->getOrder();
579
    }
580
}
581