Test Failed
Branch v4.x (b7bab7)
by Dmitry
09:55
created

Reports   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 172
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 47
dl 0
loc 172
rs 10
c 1
b 0
f 0
wmc 18

8 Methods

Rating   Name   Duplication   Size   Complexity  
A setSkipReportHeader() 0 4 1
A getHeaders() 0 13 3
B handleResponse() 0 42 6
A setSkipColumnHeader() 0 4 1
A setReturnMoneyInMicros() 0 7 4
A setSkipReportSummary() 0 4 1
A setProcessingMode() 0 5 1
A get() 0 17 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gladyshev\Yandex\Direct\Service;
6
7
use function Gladyshev\Yandex\Direct\get_param_names;
8
9
final class Reports extends \Gladyshev\Yandex\Direct\AbstractService
10
{
11
    private $skipReportHeader = false;
12
    private $skipReportSummary = false;
13
    private $headers = [];
14
15
    /**
16
     * Спецификация отчета.
17
     *
18
     * @param $SelectionCriteria
19
     * @param $Goals
20
     * @param $FieldNames
21
     * @param $ReportName
22
     * @param $ReportType
23
     * @param $DateRangeType
24
     * @param $Format
25
     * @param $IncludeVAT
26
     * @param $IncludeDiscount
27
     * @param $Page
28
     * @param $OrderBy
29
     *
30
     * @return array
31
     *
32
     * @throws \Throwable
33
     * @throws \ReflectionException
34
     *
35
     * @see https://tech.yandex.ru/direct/doc/reports/spec-docpage/
36
     */
37
    public function get(
38
        $SelectionCriteria,
39
        $FieldNames,
40
        $ReportName,
41
        $ReportType,
42
        $DateRangeType,
43
        $Page = null,
44
        $OrderBy = null,
45
        $IncludeVAT = 'YES',
46
        $IncludeDiscount = 'YES',
47
        $Format = 'TSV',
48
        $Goals = []
49
    ): array {
50
        $params = compact(get_param_names(__METHOD__));
51
52
        return $this->call([
53
            'params' => $params
54
        ]);
55
    }
56
57
    /**
58
     * Режим формирования отчета: online, offline или auto.
59
     * Отсутствие заголовка эквивалентно значению auto.
60
     *
61
     * @param $processingMode
62
     * @return $this
63
     * @see https://tech.yandex.ru/direct/doc/reports/headers-docpage/
64
     */
65
    public function setProcessingMode($processingMode): self
66
    {
67
        $this->headers['processingMode'] = $processingMode;
68
69
        return $this;
70
    }
71
72
    /**
73
     * Если заголовок указан, денежные значения в отчете возвращаются в валюте с точностью до двух знаков после
74
     * запятой. Если не указан, денежные значения возвращаются в виде целых чисел — сумм в валюте,
75
     * умноженных на 1 000 000.
76
     *
77
     * @param $returnMoneyInMicros
78
     * @return $this
79
     * @see https://tech.yandex.ru/direct/doc/reports/headers-docpage/
80
     */
81
    public function setReturnMoneyInMicros($returnMoneyInMicros): self
82
    {
83
        if (is_numeric($returnMoneyInMicros) || is_bool($returnMoneyInMicros)) {
84
            $returnMoneyInMicros = $returnMoneyInMicros ? 'true' : 'false';
85
        }
86
        $this->headers['returnMoneyInMicros'] = $returnMoneyInMicros;
87
        return $this;
88
    }
89
90
    /**
91
     * Не выводить в отчете строку с названием отчета и диапазоном дат.
92
     * @return $this
93
     * @see https://tech.yandex.ru/direct/doc/reports/headers-docpage/
94
     */
95
    public function setSkipReportHeader(): self
96
    {
97
        $this->headers['skipReportHeader'] = 'true';
98
        return $this;
99
    }
100
101
    /**
102
     * Не выводить в отчете строку с названиями полей.
103
     *
104
     * @return $this
105
     * @see https://tech.yandex.ru/direct/doc/reports/headers-docpage/
106
     */
107
    public function setSkipColumnHeader(): self
108
    {
109
        $this->headers['skipColumnHeader'] = 'true';
110
        return $this;
111
    }
112
113
    /**
114
     * Не выводить в отчете строку с количеством строк статистики.
115
     *
116
     * @see https://tech.yandex.ru/direct/doc/reports/headers-docpage/
117
     */
118
    public function setSkipReportSummary(): self
119
    {
120
        $this->skipReportSummary = true;
121
        return $this;
122
    }
123
124
    protected function handleResponse(
125
        \Psr\Http\Message\RequestInterface $request,
126
        \Psr\Http\Message\ResponseInterface $response
127
    ): array {
128
        $contents = $response->getBody()->getContents();
129
130
        if ($response->getStatusCode() >= 400) {
131
            $parsedBody = json_decode($contents, true);
132
            if ($parsedBody && !empty($parsedBody['error'])) {
133
                throw new \Gladyshev\Yandex\Direct\Exception\ErrorResponseException(
134
                    $parsedBody['error']['error_string'],
135
                    $parsedBody['error']['error_detail'],
136
                    (int)$parsedBody['error']['error_code'],
137
                    $request,
138
                    $response
139
                );
140
            }
141
142
            throw new \Gladyshev\Yandex\Direct\Exception\ErrorResponseException(
143
                'Unexpected API response.',
144
                $contents,
145
                0,
146
                $request,
147
                $response
148
            );
149
        }
150
151
        $result = [
152
            'request_id' => current($response->getHeader('RequestId'))
153
        ];
154
155
        if ($response->getStatusCode() == 201
156
            || $response->getStatusCode() == 202
157
        ) {
158
            $result['retryIn'] = $response->getHeaders()['retryIn'];
159
160
            return $result;
161
        }
162
163
        $result['report'] = $contents;
164
165
        return $result;
166
    }
167
168
    protected function getHeaders(): array
169
    {
170
        $headers = parent::getHeaders();
171
172
        if ($this->skipReportHeader) {
173
            $headers['skipReportHeader'] = 'true';
174
        }
175
176
        if ($this->skipReportSummary) {
177
            $headers['skipReportSummary'] = 'true';
178
        }
179
180
        return $headers;
181
    }
182
}
183