Completed
Push — master ( b3d933...e7435a )
by Francesco
02:21
created

SegmentRepository::enableCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
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\entity\Segment;
6
use Audiens\AppnexusClient\exceptions\RepositoryException;
7
use Doctrine\Common\Cache\Cache;
8
use GuzzleHttp\Client;
9
use GuzzleHttp\ClientInterface;
10
11
/**
12
 * Class SegmentRepository
13
 */
14
class SegmentRepository
15
{
16
17
    const BASE_URL = 'https://api.adnxs.com/segment/';
18
19
    /** @var Client */
20
    protected $client;
21
22
    /** @var  int */
23
    protected $memberId;
24
25
    /** @var  Cache */
26
    protected $cache;
27
28
    /** @var bool */
29
    protected $cacheEnabled;
30
31
    const CACHE_NAMESPACE = 'appnexus_segment_repository_find_all';
32
33
    const CACHE_EXPIRATION = 3600;
34
35
    /**
36
     * SegmentRepository constructor.
37
     *
38
     * @param ClientInterface $client
39
     * @param Cache|null      $cache
40
     */
41
    public function __construct(ClientInterface $client, Cache $cache = null)
42
    {
43
        $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...
44
        $this->cache = $cache;
45
        $this->cacheEnabled = $cache instanceof Cache;
46
    }
47
48
    /**
49
     * @param Segment $segment
50
     *
51
     * @return RepositoryResponse
52
     * @throws \Exception
53
     */
54
    public function add(Segment $segment)
55
    {
56
57
        $compiledUrl = self::BASE_URL.$segment->getMemberId();
58
59
        $payload = [
60
            'segment' => $segment->torray(),
61
        ];
62
63
        $response = $this->client->request('POST', $compiledUrl, ['body' => json_encode($payload)]);
64
65
        $repositoryResponse = RepositoryResponse::fromResponse($response);
66
67 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...
68
69
            $stream = $response->getBody();
70
            $responseContent = json_decode($stream->getContents(), true);
71
            $stream->rewind();
72
73
            if (!(isset($responseContent['response']['segment']['id']))) {
74
                throw RepositoryException::wrongFormat(serialize($responseContent));
75
            }
76
77
            $segment->setId($responseContent['response']['segment']['id']);
78
        }
79
80
        return $repositoryResponse;
81
82
    }
83
84
    /**
85
     * @param $id
86
     * @param $memberId
87
     *
88
     * @return Segment|null
89
     */
90
    public function findOneById($id, $memberId)
91
    {
92
93
        $compiledUrl = self::BASE_URL.$memberId.'/'.$id;
94
95
        $response = $this->client->request('GET', $compiledUrl);
96
97
        $repositoryResponse = RepositoryResponse::fromResponse($response);
98
99
        if (!$repositoryResponse->isSuccessful()) {
100
            return null;
101
        }
102
103
        $stream = $response->getBody();
104
        $responseContent = json_decode($stream->getContents(), true);
105
        $stream->rewind();
106
107
        return Segment::fromArray($responseContent['response']['segment']);
108
109
    }
110
111
    /**
112
     * @param $id
113
     * @param $memberId
114
     *
115
     * @return RepositoryResponse
116
     */
117
    public function remove($id, $memberId)
118
    {
119
120
        $compiledUrl = self::BASE_URL.$memberId.'/'.$id;
121
122
        $response = $this->client->request('DELETE', $compiledUrl);
123
124
        $repositoryResponse = RepositoryResponse::fromResponse($response);
125
126
        return $repositoryResponse;
127
128
    }
129
130
    /**
131
     * @param     $memberId
132
     * @param int $start
133
     * @param int $maxResults
134
     *
135
     * @return Segment|null
136
     */
137
    public function findAll($memberId, $start = 0, $maxResults = 100)
138
    {
139
140
        if ($this->isCacheEnabled()) {
141
            $cacheKey = self::CACHE_NAMESPACE.sha1($memberId.$start.$maxResults);
142
            if ($this->cache->contains($cacheKey)) {
143
                return $this->cache->fetch($cacheKey);
144
            }
145
146
        }
147
148
        $compiledUrl = self::BASE_URL.$memberId."?start_element=$start&num_elements=$maxResults";
149
150
        $response = $this->client->request('GET', $compiledUrl);
151
152
        $repositoryResponse = RepositoryResponse::fromResponse($response);
153
154
        if (!$repositoryResponse->isSuccessful()) {
155
            return null;
156
        }
157
158
        $stream = $response->getBody();
159
        $responseContent = json_decode($stream->getContents(), true);
160
        $stream->rewind();
161
162
        $result = [];
163
164
        foreach ($responseContent['response']['segments'] as $segmentArray) {
165
            $result[] = Segment::fromArray($segmentArray);
166
        }
167
168
169
        if ($this->isCacheEnabled()) {
170
            $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
0 ignored issues
show
Bug introduced by
The variable $cacheKey does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
171
        }
172
173
        return $result;
174
175
    }
176
177
    /**
178
     * @param Segment $segment
179
     *
180
     * @return RepositoryResponse
181
     * @throws \Exception
182
     */
183
    public function update(Segment $segment)
184
    {
185
186
        if (!$segment->getId()) {
187
            throw new \Exception('name me - missing id');
188
        }
189
190
        $compiledUrl = self::BASE_URL.$segment->getMemberId().'/'.$segment->getId();
191
192
        $payload = [
193
            'segment' => $segment->torray(),
194
        ];
195
196
        $response = $this->client->request('PUT', $compiledUrl, ['body' => json_encode($payload)]);
197
198
        $repositoryResponse = RepositoryResponse::fromResponse($response);
199
200 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...
201
202
            $stream = $response->getBody();
203
            $responseContent = json_decode($stream->getContents(), true);
204
            $stream->rewind();
205
206
            if (!(isset($responseContent['response']['segment']['id']))) {
207
                throw RepositoryException::wrongFormat(serialize($responseContent));
208
            }
209
210
            $segment->setId($responseContent['response']['segment']['id']);
211
        }
212
213
        return $repositoryResponse;
214
215
    }
216
217
    /**
218
     * @return boolean
219
     */
220
    public function isCacheEnabled()
221
    {
222
        return $this->cacheEnabled;
223
    }
224
225
    public function disableCache()
226
    {
227
        $this->cacheEnabled = false;
228
    }
229
230
    public function enableCache()
231
    {
232
        $this->cacheEnabled = true;
233
    }
234
235
}
236