Completed
Branch v4.x (712f3d)
by Dmitry
04:56
created

Reports::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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