Report::getReportStatus()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 9.472
c 0
b 0
f 0
cc 4
nc 4
nop 1
1
<?php
2
3
namespace Audiens\AppnexusClient\service;
4
5
use Audiens\AppnexusClient\Auth;
6
use Audiens\AppnexusClient\CachableTrait;
7
use Audiens\AppnexusClient\CacheableInterface;
8
use Audiens\AppnexusClient\entity\ReportStatus;
9
use Audiens\AppnexusClient\entity\ReportTicket;
10
use Audiens\AppnexusClient\exceptions\ReportException;
11
use Audiens\AppnexusClient\repository\RepositoryResponse;
12
use Doctrine\Common\Cache\Cache;
13
use GuzzleHttp\ClientInterface;
14
15
class Report implements CacheableInterface
16
{
17
18
    use CachableTrait;
19
20
    public const BASE_URL                  = 'http://api.adnxs.com/report';
21
    public const BASE_URL_DOWNLOAD         = 'http://api.adnxs.com/';
22
    public const SANDBOX_BASE_URL          = 'http://api-test.adnxs.com/report';
23
    public const SANDBOX_BASE_URL_DOWNLOAD = 'http://api-test.adnxs.com/';
24
    public const CACHE_NAMESPACE = 'appnexus_report';
25
    public const CACHE_EXPIRATION = 3600;
26
    public const REVENUE_REPORT
27
        = [
28
            'report' => [
29
                'report_type' => 'seller_platform_billing',
30
                'timezone' => 'PST',
31
                'report_interval' => 'last_7_days',
32
                'name' => 'Weekly SSP Revenue Report',
33
                'columns' => [
34
                    0 => 'day',
35
                    1 => 'seller_member_id',
36
                    2 => 'publisher_id',
37
                    3 => 'publisher_name',
38
                    4 => 'publisher_code',
39
                    5 => 'buyer_member_id',
40
                    6 => 'buyer_member_name',
41
                    7 => 'imps',
42
                    8 => 'imps_delivered',
43
                    9 => 'seller_revenue',
44
                ],
45
            ],
46
        ];
47
48
    public const SEGMENT_LOAD_REPORT_CUMULATIVE_VC
49
        = [
50
            'report' => [
51
                'report_type' => 'segment_load',
52
                'timezone' => 'PST',
53
                'report_interval' => 'month_to_date',
54
                'name' => 'Cumulative VC report',
55
                'columns' => [
56
                    'avg_daily_uniques',
57
                    'month',
58
                ],
59
60
                'groups' => [
61
                    'month',
62
63
                ],
64
                'orders' => [
65
                    'avg_daily_uniques',
66
                ],
67
            ],
68
        ];
69
70
    public const SEGMENT_LOAD_REPORT_DAILY_VC
71
        = [
72
            'report' => [
73
                'report_type' => 'segment_load',
74
                'timezone' => 'PST',
75
                'report_interval' => 'today',
76
                'name' => 'Cumulative VC report',
77
                'columns' => [
78
                    'daily_uniques',
79
                    'day',
80
                ],
81
82
                'groups' => [
83
                    'day',
84
85
                ],
86
                'orders' => [
87
                    'daily_uniques',
88
                ],
89
            ],
90
        ];
91
92
    /** @var  \SplQueue */
93
    protected $userSegments;
94
95
    /** @var ClientInterface|Auth */
96
    protected $client;
97
98
    /** @var  int */
99
    protected $memberId;
100
101
    /** @var  Cache */
102
    protected $cache;
103
104
    /** @var string */
105
    protected $baseUrl;
106
107
    /** @var  string */
108
    protected $baseUrlDownload;
109
110
    public function __construct(ClientInterface $client, Cache $cache)
111
    {
112
        $this->client = $client;
113
        $this->cache  = $cache;
114
115
        $this->baseUrl         = self::BASE_URL;
116
        $this->baseUrlDownload = self::BASE_URL_DOWNLOAD;
117
    }
118
119
    /**
120
     * @return string
121
     */
122
    public function getBaseUrl()
123
    {
124
        return $this->baseUrl;
125
    }
126
127
    /**
128
     * @param string $baseUrl
129
     */
130
    public function setBaseUrl($baseUrl)
131
    {
132
        $this->baseUrl = $baseUrl;
133
    }
134
135
    /**
136
     * @return string
137
     */
138
    public function getBaseUrlDownload()
139
    {
140
        return $this->baseUrlDownload;
141
    }
142
143
    /**
144
     * @param string $baseUrlDownload
145
     */
146
    public function setBaseUrlDownload($baseUrlDownload)
147
    {
148
        $this->baseUrlDownload = $baseUrlDownload;
149
    }
150
151
    /**
152
     * @param array $reportFormat
153
     *
154
     * @return ReportTicket
155
     * @throws ReportException
156
     */
157
    public function getReportTicket($reportFormat = self::REVENUE_REPORT)
158
    {
159
        $compiledUrl = $this->baseUrl;
160
161
        $response = $this->client->request('POST', $compiledUrl, ['body' => json_encode($reportFormat)]);
162
163
        $repositoryResponse = RepositoryResponse::fromResponse($response);
164
165
        if (!$repositoryResponse->isSuccessful()) {
166
            throw ReportException::failed($repositoryResponse);
167
        }
168
169
        if (!isset($repositoryResponse->getResponseAsArray()['response']['report_id'])) {
170
            throw ReportException::missingIndex('response->report_id');
171
        }
172
173
        $reportTicket = ReportTicket::fromArray(
174
            $repositoryResponse->getResponseAsArray()['response']
175
        );
176
177
        return $reportTicket;
178
    }
179
180
    /**
181
     * @param ReportTicket $reportTicket
182
     *
183
     * @return ReportStatus
184
     * @throws ReportException
185
     */
186
    public function getReportStatus(ReportTicket $reportTicket)
187
    {
188
        $compiledUrl = $this->baseUrl.'?id='.$reportTicket->getReportId();
189
190
        $response = $this->client->request('GET', $compiledUrl);
191
192
        $repositoryResponse = RepositoryResponse::fromResponse($response);
193
194
        if (!$repositoryResponse->isSuccessful()) {
195
            throw ReportException::failed($repositoryResponse);
196
        }
197
198
        if (!isset($repositoryResponse->getResponseAsArray()['response']['report'])) {
199
            throw ReportException::missingIndex('response->report');
200
        }
201
202
        if (!isset($repositoryResponse->getResponseAsArray()['response']['execution_status'])) {
203
            throw ReportException::missingIndex('response->execution_status');
204
        }
205
206
        /** @var ReportStatus $reportStatus */
207
        $reportStatus = ReportStatus::fromArray($repositoryResponse->getResponseAsArray()['response']['report']);
208
        $reportStatus->setStatus($repositoryResponse->getResponseAsArray()['response']['execution_status']);
209
        $reportStatus->setReportId($reportTicket->getReportId());
210
        $reportStatus->setCached($reportTicket->getCached());
211
212
        return $reportStatus;
213
    }
214
215
    /**
216
     * @param ReportStatus $reportStatus
217
     *
218
     * @return array
219
     * @throws ReportException
220
     */
221
    public function getReport(ReportStatus $reportStatus)
222
    {
223
        if (!$reportStatus->isReady()) {
224
            throw ReportException::validation('report status not ready');
225
        }
226
227
        if (!$reportStatus->getUrl()) {
228
            throw ReportException::validation('missing url in the report status');
229
        }
230
231
        $cacheKey = self::CACHE_NAMESPACE.sha1($reportStatus->getUrl());
232
233
        if ($this->cache->contains($cacheKey)) {
234
            return $this->cache->fetch($cacheKey);
235
        }
236
237
        $compiledUrl = $this->baseUrlDownload.$reportStatus->getUrl();
238
239
        $response = $this->client->request('GET', $compiledUrl);
240
241
        $lines  = explode(PHP_EOL, $response->getBody()->getContents());
242
        $result = [];
243
        foreach ($lines as $line) {
244
            if (!empty($line)) {
245
                $result[] = str_getcsv($line);
246
            }
247
        }
248
249
        $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
250
251
        return $result;
252
    }
253
}
254