Completed
Push — master ( 01b1f4...cd2255 )
by Francesco
03:06
created

Report::setBaseUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
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\Client;
14
use GuzzleHttp\ClientInterface;
15
16
/**
17
 * Class Report
18
 */
19
class Report implements CacheableInterface
20
{
21
22
    use CachableTrait;
23
24
    const BASE_URL          = 'http://api.adnxs.com/report';
25
    const BASE_URL_DOWNLOAD = 'http://api.adnxs.com/';
26
27
    const SANDBOX_BASE_URL          = 'http://api-test.adnxs.com/report';
28
    const SANDBOX_BASE_URL_DOWNLOAD = 'http://api-test.adnxs.com/';
29
30
31
    /** @var  \SplQueue */
32
    protected $userSegments;
33
34
    /** @var Client|Auth */
35
    protected $client;
36
37
    /** @var  int */
38
    protected $memberId;
39
40
    /** @var  Cache */
41
    protected $cache;
42
43
    const CACHE_NAMESPACE = 'appnexus_report';
44
45
    const CACHE_EXPIRATION = 3600;
46
47
    const REVENUE_REPORT = [
48
        'report' =>
49
            [
50
                'report_type' => 'seller_platform_billing',
51
                'timezone' => 'PST',
52
                'report_interval' => 'last_7_days',
53
                'name' => 'Weekly SSP Revenue Report',
54
                'columns' =>
55
                    [
56
                        0 => 'day',
57
                        1 => 'seller_member',
58
                        2 => 'publisher_id',
59
                        3 => 'publisher_name',
60
                        4 => 'publisher_code',
61
                        5 => 'buyer_member_id',
62
                        6 => 'buyer_member_name',
63
                        7 => 'imps',
64
                        8 => 'imps_delivered',
65
                        9 => 'seller_revenue',
66
                    ],
67
            ],
68
    ];
69
70
    /** @var string */
71
    protected $baseUrl;
72
73
    /** @var  string */
74
    protected $baseUrlDownload;
75
76
    /**
77
     * SegmentRepository constructor.
78
     *
79
     * @param ClientInterface $client
80
     * @param Cache|null      $cache
81
     */
82 View Code Duplication
    public function __construct(ClientInterface $client, Cache $cache = null)
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...
83
    {
84
        $this->client = $client;
0 ignored issues
show
Documentation Bug introduced by
$client is of type object<GuzzleHttp\ClientInterface>, but the property $client was declared to be of type object<GuzzleHttp\Client>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
85
        $this->cache = $cache;
86
        $this->cacheEnabled = $cache instanceof Cache;
87
88
        $this->baseUrl = self::BASE_URL;
89
        $this->baseUrlDownload = self::BASE_URL_DOWNLOAD;
90
91
    }
92
93
    /**
94
     * @return string
95
     */
96
    public function getBaseUrl()
97
    {
98
        return $this->baseUrl;
99
    }
100
101
    /**
102
     * @param string $baseUrl
103
     */
104
    public function setBaseUrl($baseUrl)
105
    {
106
        $this->baseUrl = $baseUrl;
107
    }
108
109
    /**
110
     * @return string
111
     */
112
    public function getBaseUrlDownload()
113
    {
114
        return $this->baseUrlDownload;
115
    }
116
117
    /**
118
     * @param string $baseUrlDownload
119
     */
120
    public function setBaseUrlDownload($baseUrlDownload)
121
    {
122
        $this->baseUrlDownload = $baseUrlDownload;
123
    }
124
125
126
    /**
127
     * @param array $reportFormat
128
     *
129
     * @return ReportTicket
130
     * @throws ReportException
131
     */
132
    public function getReportTicket($reportFormat = self::REVENUE_REPORT)
133
    {
134
135
        $compiledUrl = $this->baseUrl;
136
137
        $response = $this->client->request('POST', $compiledUrl, ['body' => json_encode($reportFormat)]);
138
139
        $repositoryResponse = RepositoryResponse::fromResponse($response);
0 ignored issues
show
Compatibility introduced by
$response of type object<Psr\Http\Message\ResponseInterface> is not a sub-type of object<GuzzleHttp\Psr7\Response>. It seems like you assume a concrete implementation of the interface Psr\Http\Message\ResponseInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
140
141
        if (!$repositoryResponse->isSuccessful()) {
142
            throw ReportException::failed($repositoryResponse);
143
        }
144
145
        if (!isset($repositoryResponse->getResponseAsArray()['response']['report_id'])) {
146
            throw ReportException::missingIndex('response->report_id');
147
        }
148
149
        $reportTicket = ReportTicket::fromArray(
150
            $repositoryResponse->getResponseAsArray()['response']
151
        );
152
153
        return $reportTicket;
154
155
    }
156
157
158
    /**
159
     * @param ReportTicket $reportTicket
160
     *
161
     * @return ReportStatus
162
     * @throws ReportException
163
     */
164
    public function getReportStatus(ReportTicket $reportTicket)
165
    {
166
167
        $compiledUrl = $this->baseUrl.'?id='.$reportTicket->getReportId();
168
169
        $response = $this->client->request('GET', $compiledUrl);
170
171
        $repositoryResponse = RepositoryResponse::fromResponse($response);
0 ignored issues
show
Compatibility introduced by
$response of type object<Psr\Http\Message\ResponseInterface> is not a sub-type of object<GuzzleHttp\Psr7\Response>. It seems like you assume a concrete implementation of the interface Psr\Http\Message\ResponseInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
172
173
        if (!$repositoryResponse->isSuccessful()) {
174
            throw ReportException::failed($repositoryResponse);
175
        }
176
177
        if (!isset($repositoryResponse->getResponseAsArray()['response']['report'])) {
178
            throw ReportException::missingIndex('response->report');
179
        }
180
181
        if (!isset($repositoryResponse->getResponseAsArray()['response']['execution_status'])) {
182
            throw ReportException::missingIndex('response->execution_status');
183
        }
184
185
        /** @var ReportStatus $reportStatus */
186
        $reportStatus = ReportStatus::fromArray($repositoryResponse->getResponseAsArray()['response']['report']);
187
        $reportStatus->setStatus($repositoryResponse->getResponseAsArray()['response']['execution_status']);
188
        $reportStatus->setReportId($reportTicket->getReportId());
189
        $reportStatus->setCached($reportTicket->getCached());
190
191
        return $reportStatus;
192
193
    }
194
195
196
    /**
197
     * @param ReportStatus $reportStatus
198
     *
199
     * @return array
200
     * @throws ReportException
201
     */
202
    public function getReport(ReportStatus $reportStatus)
203
    {
204
        if (!$reportStatus->isReady()) {
205
            throw ReportException::validation('report status not ready');
206
        }
207
208
        if (!$reportStatus->getUrl()) {
209
            throw ReportException::validation('missing url in the report status');
210
        }
211
212
        $cacheKey = self::CACHE_NAMESPACE.sha1($reportStatus->getUrl());
213
214
        if ($this->isCacheEnabled()) {
215
            if ($this->cache->contains($cacheKey)) {
216
                return $this->cache->fetch($cacheKey);
217
            }
218
        }
219
220
        $compiledUrl = $this->baseUrlDownload.$reportStatus->getUrl();
221
222
        $response = $this->client->request('GET', $compiledUrl);
223
224
        $lines = explode(PHP_EOL, $response->getBody()->getContents());
225
        $result = [];
226
        foreach ($lines as $line) {
227
            if (!empty($line)) {
228
                $result[] = str_getcsv($line);
229
            }
230
        }
231
232
        if ($this->isCacheEnabled()) {
233
            $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
234
        }
235
236
        return $result;
237
238
    }
239
}
240