Completed
Push — master ( 2cca03...332d8f )
by Francesco
02:39
created

SegmentRepository::update()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 20
rs 9.4285
cc 2
eloc 9
nc 2
nop 1
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);
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...
66
67
        if ($repositoryResponse->isSuccessful()) {
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 RepositoryResponse
89
     */
90
    public function remove($id, $memberId)
91
    {
92
93
        $compiledUrl = self::BASE_URL.$memberId.'/'.$id;
94
95
        $response = $this->client->request('DELETE', $compiledUrl);
96
97
        $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...
98
99
        return $repositoryResponse;
100
101
    }
102
103
    /**
104
     * @param Segment $segment
105
     *
106
     * @return RepositoryResponse
107
     * @throws \Exception
108
     */
109
    public function update(Segment $segment)
110
    {
111
112
        if (!$segment->getId()) {
113
            throw new \Exception('name me - missing id');
114
        }
115
116
        $compiledUrl = self::BASE_URL.$segment->getMemberId().'/'.$segment->getId();
117
118
        $payload = [
119
            'segment' => $segment->torray(),
120
        ];
121
122
        $response = $this->client->request('PUT', $compiledUrl, ['body' => json_encode($payload)]);
123
124
        $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...
125
126
        return $repositoryResponse;
127
128
    }
129
130
    /**
131
     * @param $id
132
     * @param $memberId
133
     *
134
     * @return Segment|null
135
     */
136
    public function findOneById($id, $memberId)
137
    {
138
139
        $compiledUrl = self::BASE_URL.$memberId.'/'.$id;
140
141
        $response = $this->client->request('GET', $compiledUrl);
142
143
        $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...
144
145
        if (!$repositoryResponse->isSuccessful()) {
146
            return null;
147
        }
148
149
        $stream = $response->getBody();
150
        $responseContent = json_decode($stream->getContents(), true);
151
        $stream->rewind();
152
153
        return Segment::fromArray($responseContent['response']['segment']);
154
155
    }
156
157
    /**
158
     * @param     $memberId
159
     * @param int $start
160
     * @param int $maxResults
161
     *
162
     * @return Segment[]|null
163
     */
164
    public function findAll($memberId, $start = 0, $maxResults = 100)
165
    {
166
167
        if ($this->isCacheEnabled()) {
168
            $cacheKey = self::CACHE_NAMESPACE.sha1($memberId.$start.$maxResults);
169
            if ($this->cache->contains($cacheKey)) {
170
                return $this->cache->fetch($cacheKey);
171
            }
172
173
        }
174
175
        $compiledUrl = self::BASE_URL.$memberId."?start_element=$start&num_elements=$maxResults";
176
177
        $response = $this->client->request('GET', $compiledUrl);
178
179
        $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...
180
181
        if (!$repositoryResponse->isSuccessful()) {
182
            return null;
183
        }
184
185
        $stream = $response->getBody();
186
        $responseContent = json_decode($stream->getContents(), true);
187
        $stream->rewind();
188
189
        $result = [];
190
191
        foreach ($responseContent['response']['segments'] as $segmentArray) {
192
            $result[] = Segment::fromArray($segmentArray);
193
        }
194
195
196
        if ($this->isCacheEnabled()) {
197
            $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...
198
        }
199
200
        return $result;
201
202
    }
203
204
    /**
205
     * @return boolean
206
     */
207
    public function isCacheEnabled()
208
    {
209
        return $this->cacheEnabled;
210
    }
211
212
    public function disableCache()
213
    {
214
        $this->cacheEnabled = false;
215
    }
216
217
    public function enableCache()
218
    {
219
        $this->cacheEnabled = true;
220
    }
221
222
}
223