SegmentRepository   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 149
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 7
dl 0
loc 149
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A getBaseUrl() 0 4 1
A setBaseUrl() 0 4 1
A add() 0 26 3
A remove() 0 8 1
A update() 0 16 2
A findOneById() 0 18 2
A findAll() 0 36 5
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\ClientInterface;
11
12
class SegmentRepository implements CacheableInterface
13
{
14
15
    use CachableTrait;
16
17
    public const BASE_URL         = 'https://api.adnxs.com/segment/';
18
    public const SANDBOX_BASE_URL = 'http://api-test.adnxs.com/segment/';
19
    public const CACHE_NAMESPACE  = 'appnexus_segment_repository_find_all';
20
    public const CACHE_EXPIRATION = 3600;
21
22
    /** @var ClientInterface */
23
    protected $client;
24
25
    /** @var  int */
26
    protected $memberId;
27
28
    /** @var  Cache */
29
    protected $cache;
30
31
    /** @var  string */
32
    protected $baseUrl;
33
34
    public function __construct(ClientInterface $client, Cache $cache, int $memberId)
35
    {
36
        $this->client   = $client;
37
        $this->cache    = $cache;
38
        $this->memberId = $memberId;
39
        $this->baseUrl  = self::BASE_URL;
40
    }
41
42
    public function getBaseUrl(): string
43
    {
44
        return $this->baseUrl;
45
    }
46
47
    public function setBaseUrl($baseUrl)
48
    {
49
        $this->baseUrl = $baseUrl;
50
    }
51
52
    public function add(Segment $segment): RepositoryResponse
53
    {
54
        $compiledUrl = $this->baseUrl.$this->memberId;
55
56
        $payload = [
57
            'segment' => $segment->toArray(),
58
        ];
59
60
        $response = $this->client->request('POST', $compiledUrl, ['body' => json_encode($payload)]);
61
62
        $repositoryResponse = RepositoryResponse::fromResponse($response);
63
64
        if ($repositoryResponse->isSuccessful()) {
65
            $stream          = $response->getBody();
66
            $responseContent = json_decode($stream->getContents(), true);
67
            $stream->rewind();
68
69
            if (!isset($responseContent['response']['segment']['id'])) {
70
                throw RepositoryException::wrongFormat(serialize($responseContent));
71
            }
72
73
            $segment->setId($responseContent['response']['segment']['id']);
74
        }
75
76
        return $repositoryResponse;
77
    }
78
79
    public function remove($id): RepositoryResponse
80
    {
81
        $compiledUrl = $this->baseUrl.$this->memberId.'/'.$id;
82
83
        $response = $this->client->request('DELETE', $compiledUrl);
84
85
        return RepositoryResponse::fromResponse($response);
86
    }
87
88
    public function update(Segment $segment): RepositoryResponse
89
    {
90
        if (!$segment->getId()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $segment->getId() of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
91
            throw RepositoryException::missingId($segment);
92
        }
93
94
        $compiledUrl = $this->baseUrl.$this->memberId.'/'.$segment->getId();
95
96
        $payload = [
97
            'segment' => $segment->toArray(),
98
        ];
99
100
        $response = $this->client->request('PUT', $compiledUrl, ['body' => json_encode($payload)]);
101
102
        return RepositoryResponse::fromResponse($response);
103
    }
104
105
    public function findOneById($id): ?Segment
106
    {
107
        $compiledUrl = $this->baseUrl.$this->memberId.'/'.$id;
108
109
        $response = $this->client->request('GET', $compiledUrl);
110
111
        $repositoryResponse = RepositoryResponse::fromResponse($response);
112
113
        if (!$repositoryResponse->isSuccessful()) {
114
            return null;
115
        }
116
117
        $stream          = $response->getBody();
118
        $responseContent = json_decode($stream->getContents(), true);
119
        $stream->rewind();
120
121
        return Segment::fromArray($responseContent['response']['segment']);
122
    }
123
124
    public function findAll($start = 0, $maxResults = 100): ?array
125
    {
126
        $cacheKey = self::CACHE_NAMESPACE.sha1($this->memberId.$start.$maxResults);
127
128
        if ($this->cache->contains($cacheKey)) {
129
            return $this->cache->fetch($cacheKey);
130
        }
131
132
        $compiledUrl = $this->baseUrl.$this->memberId."?start_element=$start&num_elements=$maxResults";
133
134
        $response = $this->client->request('GET', $compiledUrl);
135
136
        $repositoryResponse = RepositoryResponse::fromResponse($response);
137
138
        if (!$repositoryResponse->isSuccessful()) {
139
            throw RepositoryException::failed($repositoryResponse);
140
        }
141
142
        $stream          = $response->getBody();
143
        $responseContent = json_decode($stream->getContents(), true);
144
        $stream->rewind();
145
146
        $result = [];
147
148
        if (!$responseContent['response']['segments']) {
149
            $responseContent['response']['segments'] = [];
150
        }
151
152
        foreach ($responseContent['response']['segments'] as $segmentArray) {
153
            $result[] = Segment::fromArray($segmentArray);
154
        }
155
156
        $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
157
158
        return $result;
159
    }
160
}
161