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

Reports::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 11
dl 0
loc 17
rs 10
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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