Completed
Push — master ( 9e1d7e...773033 )
by
unknown
03:28
created

SegmentBillingRepository::findAll()   C

Complexity

Conditions 7
Paths 19

Size

Total Lines 44
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 44
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 21
nc 19
nop 3
1
<?php
2
3
namespace Audiens\AppnexusClient\repository;
4
5
use Audiens\AppnexusClient\CachableTrait;
6
use Audiens\AppnexusClient\CacheableInterface;
7
use Audiens\AppnexusClient\entity\SegmentBilling;
8
use Audiens\AppnexusClient\exceptions\RepositoryException;
9
use Doctrine\Common\Cache\Cache;
10
use GuzzleHttp\Client;
11
use GuzzleHttp\ClientInterface;
12
13
/**
14
 * Class SegmentBillingRepository
15
 */
16
class SegmentBillingRepository implements CacheableInterface
17
{
18
    use CachableTrait;
19
20
    const BASE_URL = 'https://api.adnxs.com/segment-billing-category';
21
22
    const SANDBOX_BASE_URL = 'http://api-test.adnxs.com/segment-billing-category';
23
24
    /** @var Client */
25
    protected $client;
26
27
    /** @var  int */
28
    protected $memberId;
29
30
    /** @var  Cache */
31
    protected $cache;
32
33
    /** @var  string */
34
    protected $baseUrl;
35
36
    const CACHE_NAMESPACE = 'appnexus_segment_billing_repository_find_all';
37
38
    const CACHE_EXPIRATION = 3600;
39
40
    /**
41
     * SegmentRepository constructor.
42
     *
43
     * @param ClientInterface $client
44
     * @param Cache|null      $cache
45
     */
46 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...
47
    {
48
        $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...
49
        $this->cache = $cache;
50
        $this->cacheEnabled = $cache instanceof Cache;
51
        $this->baseUrl = self::BASE_URL;
52
    }
53
54
    /**
55
     * @return string
56
     */
57
    public function getBaseUrl()
58
    {
59
        return $this->baseUrl;
60
    }
61
62
    /**
63
     * @param string $baseUrl
64
     */
65
    public function setBaseUrl($baseUrl)
66
    {
67
        $this->baseUrl = $baseUrl;
68
    }
69
70
71
    /**
72
     * @param SegmentBilling $segmentBilling
73
     *
74
     * @return RepositoryResponse
75
     * @throws RepositoryException
76
     */
77
    public function add(SegmentBilling $segmentBilling)
78
    {
79
80
        $compiledUrl = $this->baseUrl.'?member_id='.$segmentBilling->getMemberId();
81
82
        $payload = [
83
            'segment-billing-category' => $segmentBilling->toArray(),
84
        ];
85
86
87
        $response = $this->client->request('POST', $compiledUrl, ['body' => json_encode($payload)]);
88
89
        $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...
90
91 View Code Duplication
        if ($repositoryResponse->isSuccessful()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
92
            $stream = $response->getBody();
93
            $responseContent = json_decode($stream->getContents(), true);
94
95
            $stream->rewind();
96
97
98
            if (!(isset($responseContent['response']['segment-billing-category'][0]['id']))) {
99
                throw RepositoryException::wrongFormat(serialize($responseContent));
100
            }
101
102
            $segmentBilling->setId($responseContent['response']['segment-billing-category'][0]['id']);
103
        }
104
105
        return $repositoryResponse;
106
    }
107
108
    /**
109
     * @param SegmentBilling $segmentBilling
110
     *
111
     * @return RepositoryResponse
112
     * @throws RepositoryException
113
     */
114 View Code Duplication
    public function update(SegmentBilling $segmentBilling)
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...
115
    {
116
117
        if (!$segmentBilling->getId()) {
118
            throw RepositoryException::missingSegmentBillingId($segmentBilling);
119
        }
120
121
        $compiledUrl = $this->baseUrl.'?member_id='.$segmentBilling->getMemberId();
122
123
        $payload = [
124
            'segment-billing-category' => $segmentBilling->toArray(),
125
        ];
126
127
        $response = $this->client->request('PUT', $compiledUrl, ['body' => json_encode($payload)]);
128
129
        $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...
130
131
        return $repositoryResponse;
132
    }
133
134
    /**
135
     * @param $memberId
136
     * @param $segmentId
137
     * @return SegmentBilling
138
     * @throws RepositoryException
139
     */
140
    public function findOneBySegmentId($memberId, $segmentId)
141
    {
142
143
        $compiledUrl = $this->baseUrl.'?member_id='.$memberId.'&segment_id='.$segmentId;
144
145
146
        $response = $this->client->request('GET', $compiledUrl);
147
148
        $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...
149
150
        if (!$repositoryResponse->isSuccessful()) {
151
            throw RepositoryException::failed($repositoryResponse);
152
        }
153
154
        $stream = $response->getBody();
155
        $responseContent = json_decode($stream->getContents(), true);
156
        $stream->rewind();
157
158
        if (!$responseContent['response']['segment-billing-categories']) {
159
            return null;
160
        }
161
162
        if (count($responseContent['response']['segment-billing-categories']) > 1) {
163
            throw RepositoryException::genericFailed('Expected only one results. Found '.count($responseContent['response']['segment-billing-categories']));
164
        }
165
166
167
        return SegmentBilling::fromArray($responseContent['response']['segment-billing-categories'][0]);
168
    }
169
170
    /**
171
     * @param     $memberId
172
     * @param int $start
173
     * @param int $maxResults
174
     *
175
     * @return SegmentBilling[]|null
176
     * @throws RepositoryException
177
     */
178
    public function findAll($memberId, $start = 0, $maxResults = 100)
179
    {
180
181
        $cacheKey = self::CACHE_NAMESPACE.sha1($memberId.$start.$maxResults);
182
183
184
        if ($this->isCacheEnabled()) {
185
            if ($this->cache->contains($cacheKey)) {
186
                return $this->cache->fetch($cacheKey);
187
            }
188
        }
189
190
        $compiledUrl = $this->baseUrl.'?member_id='.$memberId.'&start_element='.$start.'&num_elements='.$maxResults;
191
192
193
        $response = $this->client->request('GET', $compiledUrl);
194
195
        $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...
196
197
        if (!$repositoryResponse->isSuccessful()) {
198
            throw RepositoryException::failed($repositoryResponse);
199
        }
200
201
        $stream = $response->getBody();
202
        $responseContent = json_decode($stream->getContents(), true);
203
        $stream->rewind();
204
205
206
        $result = [];
207
208
        if (!$responseContent['response']['segment-billing-categories']) {
209
            $responseContent['response']['segment-billing-categories'] = [];
210
        }
211
212
        foreach ($responseContent['response']['segment-billing-categories'] as $segmentBillingArray) {
213
            $result[] = SegmentBilling::fromArray($segmentBillingArray);
214
        }
215
216
        if ($this->isCacheEnabled()) {
217
            $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
218
        }
219
220
        return $result;
221
    }
222
223
    /**
224
     * @param $memberId
225
     * @param $id
226
     *
227
     * @return RepositoryResponse
228
     */
229 View Code Duplication
    public function remove($memberId, $id)
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...
230
    {
231
232
        $compiledUrl = $this->baseUrl.'?member_id='.$memberId.'&id='.$id;
233
234
        $response = $this->client->request('DELETE', $compiledUrl);
235
236
        $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...
237
238
        return $repositoryResponse;
239
    }
240
}
241