Completed
Push — master ( 709db1...ea2eeb )
by luca
21:44
created

addSegmentsToMemberDataSharing()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 38
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 16
nc 5
nop 2
1
<?php
2
3
namespace Audiens\AppnexusClient\repository;
4
5
use Audiens\AppnexusClient\CachableTrait;
6
use Audiens\AppnexusClient\CacheableInterface;
7
use Audiens\AppnexusClient\entity\MemberDataSharing;
8
use Audiens\AppnexusClient\entity\MemberDataSharingSegment;
9
use Audiens\AppnexusClient\exceptions\RepositoryException;
10
use Doctrine\Common\Cache\Cache;
11
use GuzzleHttp\Client;
12
use GuzzleHttp\ClientInterface;
13
14
/**
15
 * Class CategoryRepository
16
 */
17
class MemberDataSharingRepository implements CacheableInterface
18
{
19
    use CachableTrait;
20
21
    const BASE_URL = 'https://api.adnxs.com/member-data-sharing/';
22
23
    const SANDBOX_BASE_URL = 'http://api-test.adnxs.com/member-data-sharing/';
24
25
    /** @var Client */
26
    protected $client;
27
28
    /** @var  int */
29
    protected $memberId;
30
31
    /** @var  Cache */
32
    protected $cache;
33
34
    /** @var  string */
35
    protected $baseUrl;
36
37
    const CACHE_NAMESPACE = 'appnexus_member_data_sharing_find_all';
38
39
    const CACHE_EXPIRATION = 3600;
40
41
    /**
42
     * SegmentRepository constructor.
43
     *
44
     * @param ClientInterface $client
45
     * @param Cache|null $cache
46
     */
47 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...
48
    {
49
        $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...
50
        $this->cache        = $cache;
51
        $this->cacheEnabled = $cache instanceof Cache;
52
        $this->baseUrl      = self::BASE_URL;
53
    }
54
55
    /**
56
     * @return string
57
     */
58
    public function getBaseUrl()
59
    {
60
        return $this->baseUrl;
61
    }
62
63
    /**
64
     * @param string $baseUrl
65
     */
66
    public function setBaseUrl($baseUrl)
67
    {
68
        $this->baseUrl = $baseUrl;
69
    }
70
71
    /**
72
     * @param int $start
73
     * @param int $maxResults
74
     * @return array|MemberDataSharing[]
75
     * @throws RepositoryException
76
     */
77 View Code Duplication
    public function findAll($start = 0, $maxResults = 100)
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...
78
    {
79
80
        $cacheKey = self::CACHE_NAMESPACE . sha1($start . $maxResults);
81
82
        if ($this->isCacheEnabled()) {
83
            if ($this->cache->contains($cacheKey)) {
84
                return $this->cache->fetch($cacheKey);
85
            }
86
        }
87
88
        $compiledUrl = $this->baseUrl . "?start_element=$start&num_elements=$maxResults";
89
90
        $response = $this->client->request('GET', $compiledUrl);
91
92
        $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...
93
94
        if (!$repositoryResponse->isSuccessful()) {
95
            throw RepositoryException::failed($repositoryResponse);
96
        }
97
98
        $stream          = $response->getBody();
99
        $responseContent = json_decode($stream->getContents(), true);
100
        $stream->rewind();
101
102
        $result = [];
103
104
        if (!$responseContent['response']['member_data_sharings']) {
105
            $responseContent['response']['member_data_sharings'] = [];
106
        }
107
108
        foreach ($responseContent['response']['member_data_sharings'] as $dataArray) {
109
            $result[] = MemberDataSharing::fromArray($dataArray);
110
        }
111
112
        if ($this->isCacheEnabled()) {
113
            $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
114
        }
115
116
        return $result;
117
    }
118
119
    /**
120
     * @param $buyerId
121
     * @param string $memberId
122
     * @return array|MemberDataSharing[]
123
     * @throws RepositoryException
124
     */
125
    public function findByBuyerId($buyerId, $memberId)
126
    {
127
128
        $cacheKey = self::CACHE_NAMESPACE . sha1($buyerId . $memberId);
129
130
        if ($this->isCacheEnabled()) {
131
            if ($this->cache->contains($cacheKey)) {
132
                return $this->cache->fetch($cacheKey);
133
            }
134
        }
135
136
        $compiledUrl = $this->baseUrl . "?data_member_id=$memberId&buyer_member_id=$buyerId";
137
138
        $response = $this->client->request('GET', $compiledUrl);
139
140
        $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...
141
142
        if (!$repositoryResponse->isSuccessful()) {
143
            throw RepositoryException::failed($repositoryResponse);
144
        }
145
146
        $stream          = $response->getBody();
147
        $responseContent = json_decode($stream->getContents(), true);
148
        $stream->rewind();
149
150
        $result = [];
151
152
        if (!$responseContent['response']['member_data_sharings']) {
153
            $responseContent['response']['member_data_sharings'] = [];
154
        }
155
156
        foreach ($responseContent['response']['member_data_sharings'] as $dataArray) {
157
            $memberDataSharing = MemberDataSharing::fromArray($dataArray);
158
159
            $segments = [];
160
161 View Code Duplication
            if (!empty($memberDataSharing->getSegments() && count($memberDataSharing->getSegments()) > 0)) {
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...
162
                foreach ($memberDataSharing->getSegments() as $s) {
163
                    $segments[] = MemberDataSharingSegment::fromArray($s);
0 ignored issues
show
Documentation introduced by
$s is of type object<Audiens\AppnexusC...mberDataSharingSegment>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
164
                }
165
            }
166
            $memberDataSharing->setSegments($segments);
167
168
            $result[] = $memberDataSharing;
169
        }
170
171
        if ($this->isCacheEnabled()) {
172
            $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
173
        }
174
175
        return $result;
176
    }
177
178
    /**
179
     * @param $recordId
180
     * @return array|MemberDataSharing[]
181
     * @throws RepositoryException
182
     */
183
    public function findById($id)
184
    {
185
186
        $cacheKey = self::CACHE_NAMESPACE . sha1($id);
187
188
        if ($this->isCacheEnabled()) {
189
            if ($this->cache->contains($cacheKey)) {
190
                return $this->cache->fetch($cacheKey);
191
            }
192
        }
193
194
        $compiledUrl = $this->baseUrl . "$id";
195
196
        $response = $this->client->request('GET', $compiledUrl);
197
198
        $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...
199
200
        if (!$repositoryResponse->isSuccessful()) {
201
            throw RepositoryException::failed($repositoryResponse);
202
        }
203
204
        $stream          = $response->getBody();
205
        $responseContent = json_decode($stream->getContents(), true);
206
        $stream->rewind();
207
208
        $result = [];
209
210
211
        if (!$responseContent['response']['member_data_sharing']) {
212
            $responseContent['response']['member_data_sharing'] = [];
213
        }
214
215
        $memberDataSharing = MemberDataSharing::fromArray($responseContent['response']['member_data_sharing']);
216
217
        $segments = [];
218
219 View Code Duplication
        if (!empty($memberDataSharing->getSegments() && count($memberDataSharing->getSegments()) > 0)) {
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...
220
            foreach ($memberDataSharing->getSegments() as $s) {
221
                $segments[] = MemberDataSharingSegment::fromArray($s);
0 ignored issues
show
Documentation introduced by
$s is of type object<Audiens\AppnexusC...mberDataSharingSegment>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
222
            }
223
        }
224
        $memberDataSharing->setSegments($segments);
225
226
        $result[] = $memberDataSharing;
227
228
229
        if ($this->isCacheEnabled()) {
230
            $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
231
        }
232
233
        return $result;
234
    }
235
236
    /**
237
     * @param MemberDataSharing $mSharing
238
     *
239
     * @return RepositoryResponse
240
     * @throws RepositoryException
241
     */
242
    public function add(MemberDataSharing $mSharing)
243
    {
244
245
        $compiledUrl = $this->baseUrl;
246
247
        $payload = [
248
            'member_data_sharing' => $mSharing->toArray(),
249
        ];
250
251
252
        if (!empty($mSharing->getSegments())) {
253
            $segmentToUpload = [];
254
255
            foreach ($mSharing->getSegments() as $segment) {
256
                $segmentToUpload[] = $segment->toArray();
257
            }
258
259
            $payload['member_data_sharing']['segments'] = $segmentToUpload;
260
        }
261
262
263
264
        $response = $this->client->request('POST', $compiledUrl, ['body' => json_encode($payload)]);
265
266
        $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...
267
268 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...
269
            $stream = $response->getBody();
270
            $responseContent = json_decode($stream->getContents(), true);
271
            $stream->rewind();
272
273
            if (!(isset($responseContent['response']['member_data_sharing']['id']))) {
274
                throw RepositoryException::wrongFormat(serialize($responseContent));
275
            }
276
277
            $mSharing->setId($responseContent['response']['member_data_sharing']['id']);
278
        }
279
280
        return $repositoryResponse;
281
    }
282
283
    /**
284
     * @param $memberDataSharingId
285
     * @param MemberDataSharingSegment[] $segments
286
     * @return RepositoryResponse
287
     */
288
    public function addSegmentsToMemberDataSharing($memberDataSharingId, $segments)
289
    {
290
291
        $compiledUrl = $this->baseUrl.$memberDataSharingId;
292
293
        /** @var MemberDataSharingSegment[] $mdObject */
294
        $mdObjectArray = $this->findById($memberDataSharingId);
295
296
297
        if (count($mdObjectArray) === 0) {
298
            throw new \RuntimeException('Could not find the selected member data sharing');
299
        }
300
301
        $segmentsOld = $mdObjectArray[0]->getSegments();
302
303
        $segmentToUpload = [];
304
305
        foreach ($segmentsOld as $sOld) {
306
            $segmentToUpload[] = $sOld->toArray();
307
        }
308
309
        foreach ($segments as $segment) {
310
            $segmentToUpload[] = $segment->toArray();
311
        }
312
313
314
315
316
        $payload = [
317
            'member_data_sharing' => [
318
                'segments' => $segmentToUpload
319
            ]
320
        ];
321
322
        $response = $this->client->request('PUT', $compiledUrl, ['body' => json_encode($payload)]);
323
324
        return 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...
325
    }
326
}
327