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

SegmentRepository::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 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Audiens\AppnexusClient\repository;
4
5
use Audiens\AppnexusClient\CachableTrait;
6
use Audiens\AppnexusClient\CacheableInterface;
7
use Audiens\AppnexusClient\entity\Segment;
8
use Audiens\AppnexusClient\exceptions\RepositoryException;
9
use Doctrine\Common\Cache\Cache;
10
use GuzzleHttp\Client;
11
use GuzzleHttp\ClientInterface;
12
13
/**
14
 * Class SegmentRepository
15
 */
16
class SegmentRepository implements CacheableInterface
17
{
18
19
    use CachableTrait;
20
21
    const BASE_URL = 'https://api.adnxs.com/segment/';
22
23
    /** @var Client */
24
    protected $client;
25
26
    /** @var  int */
27
    protected $memberId;
28
29
    /** @var  Cache */
30
    protected $cache;
31
32
33
    const CACHE_NAMESPACE = 'appnexus_segment_repository_find_all';
34
35
    const CACHE_EXPIRATION = 3600;
36
37
    /**
38
     * SegmentRepository constructor.
39
     *
40
     * @param ClientInterface $client
41
     * @param Cache|null      $cache
42
     */
43
    public function __construct(ClientInterface $client, Cache $cache = null)
44
    {
45
        $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...
46
        $this->cache = $cache;
47
        $this->cacheEnabled = $cache instanceof Cache;
48
    }
49
50
    /**
51
     * @param Segment $segment
52
     *
53
     * @return RepositoryResponse
54
     * @throws RepositoryException
55
     */
56
    public function add(Segment $segment)
57
    {
58
59
        $compiledUrl = self::BASE_URL.$segment->getMemberId();
60
61
        $payload = [
62
            'segment' => $segment->toArray(),
63
        ];
64
65
        $response = $this->client->request('POST', $compiledUrl, ['body' => json_encode($payload)]);
66
67
        $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...
68
69
        if ($repositoryResponse->isSuccessful()) {
70
            $stream = $response->getBody();
71
            $responseContent = json_decode($stream->getContents(), true);
72
            $stream->rewind();
73
74
            if (!(isset($responseContent['response']['segment']['id']))) {
75
                throw RepositoryException::wrongFormat(serialize($responseContent));
76
            }
77
78
            $segment->setId($responseContent['response']['segment']['id']);
79
        }
80
81
        return $repositoryResponse;
82
83
    }
84
85
    /**
86
     * @param $memberId
87
     * @param $id
88
     *
89
     * @return RepositoryResponse
90
     */
91
    public function remove($memberId, $id)
92
    {
93
94
        $compiledUrl = self::BASE_URL.$memberId.'/'.$id;
95
96
        $response = $this->client->request('DELETE', $compiledUrl);
97
98
        $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...
99
100
        return $repositoryResponse;
101
102
    }
103
104
    /**
105
     * @param Segment $segment
106
     *
107
     * @return RepositoryResponse
108
     * @throws RepositoryException
109
     */
110
    public function update(Segment $segment)
111
    {
112
113
        if (!$segment->getId()) {
114
            throw RepositoryException::missingId($segment);
115
        }
116
117
        $compiledUrl = self::BASE_URL.$segment->getMemberId().'/'.$segment->getId();
118
119
        $payload = [
120
            'segment' => $segment->toArray(),
121
        ];
122
123
        $response = $this->client->request('PUT', $compiledUrl, ['body' => json_encode($payload)]);
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
        return $repositoryResponse;
128
129
    }
130
131
    /**
132
     * @param $id
133
     * @param $memberId
134
     *
135
     * @return Segment|null
136
     */
137
    public function findOneById($memberId, $id)
138
    {
139
140
        $compiledUrl = self::BASE_URL.$memberId.'/'.$id;
141
142
        $response = $this->client->request('GET', $compiledUrl);
143
144
        $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...
145
146
        if (!$repositoryResponse->isSuccessful()) {
147
            return null;
148
        }
149
150
        $stream = $response->getBody();
151
        $responseContent = json_decode($stream->getContents(), true);
152
        $stream->rewind();
153
154
        return Segment::fromArray($responseContent['response']['segment']);
155
156
    }
157
158
    /**
159
     * @param     $memberId
160
     * @param int $start
161
     * @param int $maxResults
162
     *
163
     * @return Segment[]|null
164
     * @throws RepositoryException
165
     */
166
    public function findAll($memberId, $start = 0, $maxResults = 100)
167
    {
168
169
        $cacheKey = self::CACHE_NAMESPACE.sha1($memberId.$start.$maxResults);
170
171
        if ($this->isCacheEnabled()) {
172
            if ($this->cache->contains($cacheKey)) {
173
                return $this->cache->fetch($cacheKey);
174
            }
175
        }
176
177
        $compiledUrl = self::BASE_URL.$memberId."?start_element=$start&num_elements=$maxResults";
178
179
        $response = $this->client->request('GET', $compiledUrl);
180
181
        $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...
182
183
        if (!$repositoryResponse->isSuccessful()) {
184
            throw RepositoryException::failed($repositoryResponse);
185
        }
186
187
        $stream = $response->getBody();
188
        $responseContent = json_decode($stream->getContents(), true);
189
        $stream->rewind();
190
191
        $result = [];
192
193
        if (!$responseContent['response']['segments']) {
194
            $responseContent['response']['segments'] = [];
195
        }
196
197
        foreach ($responseContent['response']['segments'] as $segmentArray) {
198
            $result[] = Segment::fromArray($segmentArray);
199
        }
200
201
        if ($this->isCacheEnabled()) {
202
            $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
203
        }
204
205
        return $result;
206
207
    }
208
}
209