Completed
Push — master ( d919b4...0e4636 )
by Francesco
05:43
created

SegmentRepository   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 213
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 8
Bugs 1 Features 2
Metric Value
wmc 19
c 8
b 1
f 2
lcom 1
cbo 7
dl 0
loc 213
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B add() 0 29 3
A remove() 0 12 1
A update() 0 20 2
A findOneById() 0 20 2
C findAll() 0 43 7
A isCacheEnabled() 0 4 1
A disableCache() 0 4 1
A enableCache() 0 4 1
1
<?php
2
3
namespace Audiens\AppnexusClient\repository;
4
5
use Audiens\AppnexusClient\CacheableInterface;
6
use Audiens\AppnexusClient\entity\Segment;
7
use Audiens\AppnexusClient\exceptions\RepositoryException;
8
use Doctrine\Common\Cache\Cache;
9
use GuzzleHttp\Client;
10
use GuzzleHttp\ClientInterface;
11
12
/**
13
 * Class SegmentRepository
14
 */
15
class SegmentRepository implements CacheableInterface
16
{
17
18
    const BASE_URL = 'https://api.adnxs.com/segment/';
19
20
    /** @var Client */
21
    protected $client;
22
23
    /** @var  int */
24
    protected $memberId;
25
26
    /** @var  Cache */
27
    protected $cache;
28
29
    /** @var bool */
30
    protected $cacheEnabled;
31
32
    const CACHE_NAMESPACE = 'appnexus_segment_repository_find_all';
33
34
    const CACHE_EXPIRATION = 3600;
35
36
    /**
37
     * SegmentRepository constructor.
38
     *
39
     * @param ClientInterface $client
40
     * @param Cache|null      $cache
41
     */
42
    public function __construct(ClientInterface $client, Cache $cache = null)
43
    {
44
        $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...
45
        $this->cache = $cache;
46
        $this->cacheEnabled = $cache instanceof Cache;
47
    }
48
49
    /**
50
     * @param Segment $segment
51
     *
52
     * @return RepositoryResponse
53
     * @throws \Exception
54
     */
55
    public function add(Segment $segment)
56
    {
57
58
        $compiledUrl = self::BASE_URL.$segment->getMemberId();
59
60
        $payload = [
61
            'segment' => $segment->toArray(),
62
        ];
63
64
        $response = $this->client->request('POST', $compiledUrl, ['body' => json_encode($payload)]);
65
66
        $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...
67
68
        if ($repositoryResponse->isSuccessful()) {
69
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 $id
87
     * @param $memberId
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 \Exception
109
     */
110
    public function update(Segment $segment)
111
    {
112
113
        if (!$segment->getId()) {
114
            throw new \Exception('name me - missing id');
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 array|mixed|null
164
     * @throws \Exception
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
            return null;
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
            throw new \Exception('name me -missing index');
195
        }
196
197
        foreach ($responseContent['response']['segments'] as $segmentArray) {
198
            $result[] = Segment::fromArray($segmentArray);
199
        }
200
201
202
        if ($this->isCacheEnabled()) {
203
            $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
204
        }
205
206
        return $result;
207
208
    }
209
210
    /**
211
     * @return boolean
212
     */
213
    public function isCacheEnabled()
214
    {
215
        return $this->cacheEnabled;
216
    }
217
218
    public function disableCache()
219
    {
220
        $this->cacheEnabled = false;
221
    }
222
223
    public function enableCache()
224
    {
225
        $this->cacheEnabled = true;
226
    }
227
}
228