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

UserUpload::isCacheEnabled()   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 0
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\UploadTicket;
9
use Audiens\AppnexusClient\entity\UploadJobStatus;
10
use Audiens\AppnexusClient\exceptions\UploadException;
11
use Audiens\AppnexusClient\repository\RepositoryResponse;
12
use Doctrine\Common\Cache\Cache;
13
use GuzzleHttp\Client;
14
use GuzzleHttp\ClientInterface;
15
16
/**
17
 * Class UserSegmentRepository
18
 */
19
class UserUpload implements CacheableInterface
20
{
21
22
    use CachableTrait;
23
24
    const BASE_URL = 'http://api.adnxs.com/batch-segment';
25
26
    /** @var  \SplQueue */
27
    protected $userSegments;
28
29
    /** @var Client|Auth */
30
    protected $client;
31
32
    /** @var  int */
33
    protected $memberId;
34
35
    /** @var  Cache */
36
    protected $cache;
37
38
    /** @var bool */
39
    protected $cacheEnabled;
40
41
    const CACHE_NAMESPACE = 'appnexus_segment_user_upload';
42
43
    const CACHE_EXPIRATION = 3600;
44
45
    /**
46
     * SegmentRepository constructor.
47
     *
48
     * @param ClientInterface $client
49
     * @param Cache|null      $cache
50
     */
51 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...
52
    {
53
        $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...
54
        $this->cache = $cache;
55
        $this->cacheEnabled = $cache instanceof Cache;
56
57
    }
58
59
    /**
60
     * @param $memberId
61
     * @param $fileAsString
62
     *
63
     * @return UploadJobStatus
64
     * @throws UploadException
65
     */
66
    public function upload($memberId, $fileAsString)
67
    {
68
        if (empty($fileAsString)) {
69
            throw UploadException::emptyFile();
70
        }
71
72
        $tempFile = tmpfile();
73
        fwrite($tempFile, $fileAsString);
74
        fseek($tempFile, 0);
75
76
        $job = $this->getUploadTicket($memberId);
77
78
        $response = $this->client->request('POST', $job->getUploadUrl(), ['body' => $tempFile]);
79
80
        $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...
81
82
        if (!$repositoryResponse->isSuccessful()) {
83
            throw UploadException::failed($repositoryResponse);
84
        }
85
86
        return $this->getJobStatus($job);
87
88
    }
89
90
    /**
91
     * @param $memberId
92
     *
93
     * @return UploadJobStatus
94
     * @throws UploadException
95
     */
96
    public function getUploadTicket($memberId)
97
    {
98
99
        $compiledUrl = self::BASE_URL.'?member_id='.$memberId;
100
101
        $response = $this->client->request('POST', $compiledUrl);
102
103
        $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...
104
105
        if (!$repositoryResponse->isSuccessful()) {
106
            throw UploadException::failed($repositoryResponse);
107
        }
108
109
        if (!isset($repositoryResponse->getResponseAsArray()['response']['batch_segment_upload_job'])) {
110
            throw UploadException::missingIndex('response->batch_segment_upload_job');
111
        }
112
113
        $uploadJob = UploadTicket::fromArray(
114
            $repositoryResponse->getResponseAsArray()['response']['batch_segment_upload_job']
115
        );
116
117
        return $uploadJob;
118
119
    }
120
121
    /**
122
     * @param UploadTicket $uploadTicket
123
     *
124
     * @return UploadJobStatus
125
     * @throws UploadException
126
     */
127
    public function getJobStatus(UploadTicket $uploadTicket)
128
    {
129
130
        $compiledUrl = self::BASE_URL."?member_id={$uploadTicket->getMemberId()}&job_id={$uploadTicket->getJobId()}";
131
132
        $response = $this->client->request('GET', $compiledUrl);
133
134
        $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...
135
136
        if (!$repositoryResponse->isSuccessful()) {
137
            throw UploadException::failed($repositoryResponse);
138
        }
139
140
        if (!isset($repositoryResponse->getResponseAsArray()['response']['batch_segment_upload_job'][0])) {
141
            throw UploadException::missingIndex('response->batch_segment_upload_job->0');
142
        }
143
144
        $uploadJobStatus = UploadJobStatus::fromArray(
145
            $repositoryResponse->getResponseAsArray()['response']['batch_segment_upload_job'][0]
146
        );
147
148
        return $uploadJobStatus;
149
150
    }
151
152
153
    /**
154
     * @param     $memberId
155
     * @param int $start
156
     * @param int $maxResults
157
     *
158
     * @return UploadJobStatus[]
159
     * @throws \Exception
160
     */
161
    public function getUploadHistory($memberId, $start = 0, $maxResults = 100)
162
    {
163
164
        $compiledUrl = self::BASE_URL."?member_id=$memberId&start_element=$start&num_elements=$maxResults";
165
166
        $response = $this->client->request('GET', $compiledUrl);
167
168
        $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...
169
170
        if (!$repositoryResponse->isSuccessful()) {
171
            throw UploadException::failed($repositoryResponse);
172
        }
173
174
        if (!isset($repositoryResponse->getResponseAsArray()['response']['batch_segment_upload_job'][0])) {
175
            throw UploadException::missingIndex('response->batch_segment_upload_job->0');
176
        }
177
178
        $uploadStatuses = [];
179
180
        $responseAsArray = $repositoryResponse->getResponseAsArray();
181
182
        foreach ($responseAsArray['response']['batch_segment_upload_job'] as $response) {
183
            $uploadStatuses[] = UploadJobStatus::fromArray($response);
184
        }
185
186
        return $uploadStatuses;
187
188
    }
189
}
190