Completed
Push — master ( 8c5cc3...01b1f4 )
by Francesco
02:33
created

Report::getReport()   C

Complexity

Conditions 8
Paths 15

Size

Total Lines 37
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 37
rs 5.3846
cc 8
eloc 19
nc 15
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
    /** @var  \SplQueue */
28
    protected $userSegments;
29
30
    /** @var Client|Auth */
31
    protected $client;
32
33
    /** @var  int */
34
    protected $memberId;
35
36
    /** @var  Cache */
37
    protected $cache;
38
39
    const CACHE_NAMESPACE = 'appnexus_report';
40
41
    const CACHE_EXPIRATION = 3600;
42
43
    const REVENUE_REPORT = [
44
        'report' =>
45
            [
46
                'report_type' => 'seller_platform_billing',
47
                'timezone' => 'PST',
48
                'report_interval' => 'last_7_days',
49
                'name' => 'Weekly SSP Revenue Report',
50
                'columns' =>
51
                    [
52
                        0 => 'day',
53
                        1 => 'seller_member',
54
                        2 => 'publisher_id',
55
                        3 => 'publisher_name',
56
                        4 => 'publisher_code',
57
                        5 => 'buyer_member_id',
58
                        6 => 'buyer_member_name',
59
                        7 => 'imps',
60
                        8 => 'imps_delivered',
61
                        9 => 'seller_revenue',
62
                    ],
63
            ],
64
    ];
65
66
    /**
67
     * SegmentRepository constructor.
68
     *
69
     * @param ClientInterface $client
70
     * @param Cache|null      $cache
71
     */
72 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...
73
    {
74
        $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...
75
        $this->cache = $cache;
76
        $this->cacheEnabled = $cache instanceof Cache;
77
78
    }
79
80
    /**
81
     * @param array $reportFormat
82
     *
83
     * @return ReportTicket
84
     * @throws ReportException
85
     */
86
    public function getReportTicket($reportFormat = self::REVENUE_REPORT)
87
    {
88
89
        $compiledUrl = self::BASE_URL;
90
91
        $response = $this->client->request('POST', $compiledUrl, ['body' => json_encode($reportFormat)]);
92
93
        $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...
94
95
        if (!$repositoryResponse->isSuccessful()) {
96
            throw ReportException::failed($repositoryResponse);
97
        }
98
99
        if (!isset($repositoryResponse->getResponseAsArray()['response']['report_id'])) {
100
            throw ReportException::missingIndex('response->report_id');
101
        }
102
103
        $reportTicket = ReportTicket::fromArray(
104
            $repositoryResponse->getResponseAsArray()['response']
105
        );
106
107
        return $reportTicket;
108
109
    }
110
111
112
    /**
113
     * @param ReportTicket $reportTicket
114
     *
115
     * @return ReportStatus
116
     * @throws ReportException
117
     */
118
    public function getReportStatus(ReportTicket $reportTicket)
119
    {
120
121
        $compiledUrl = self::BASE_URL.'?id='.$reportTicket->getReportId();
122
123
        $response = $this->client->request('GET', $compiledUrl);
124
125
        $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...
126
127
        if (!$repositoryResponse->isSuccessful()) {
128
            throw ReportException::failed($repositoryResponse);
129
        }
130
131
        if (!isset($repositoryResponse->getResponseAsArray()['response']['report'])) {
132
            throw ReportException::missingIndex('response->report');
133
        }
134
135
        if (!isset($repositoryResponse->getResponseAsArray()['response']['execution_status'])) {
136
            throw ReportException::missingIndex('response->execution_status');
137
        }
138
139
        /** @var ReportStatus $reportStatus */
140
        $reportStatus = ReportStatus::fromArray($repositoryResponse->getResponseAsArray()['response']['report']);
141
        $reportStatus->setStatus($repositoryResponse->getResponseAsArray()['response']['execution_status']);
142
        $reportStatus->setReportId($reportTicket->getReportId());
143
        $reportStatus->setCached($reportTicket->getCached());
144
145
        return $reportStatus;
146
147
    }
148
149
150
    /**
151
     * @param ReportStatus $reportStatus
152
     *
153
     * @return array
154
     * @throws ReportException
155
     */
156
    public function getReport(ReportStatus $reportStatus)
157
    {
158
        if (!$reportStatus->isReady()) {
159
            throw ReportException::validation('report status not readi');
160
        }
161
162
        if (!$reportStatus->getUrl()) {
163
            throw ReportException::validation('missing url in the report status');
164
        }
165
166
        $cacheKey = self::CACHE_NAMESPACE.sha1($reportStatus->getUrl());
167
168
        if ($this->isCacheEnabled()) {
169
            if ($this->cache->contains($cacheKey)) {
170
                return $this->cache->fetch($cacheKey);
171
            }
172
        }
173
174
        $compiledUrl = self::BASE_URL_DOWNLOAD.$reportStatus->getUrl();
175
176
        $response = $this->client->request('GET', $compiledUrl);
177
178
        $lines = explode(PHP_EOL, $response->getBody()->getContents());
179
        $result = [];
180
        foreach ($lines as $line) {
181
            if (!empty($line)) {
182
                $result[] = str_getcsv($line);
183
            }
184
        }
185
186
        if ($this->isCacheEnabled()) {
187
            $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
188
        }
189
190
        return $result;
191
192
    }
193
}
194