Completed
Push — master ( 0fb048...b3d933 )
by Francesco
02:12
created

SegmentRepository::findOneById()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 20
rs 9.4285
cc 2
eloc 10
nc 2
nop 2
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 GeneratedHydrator\Configuration;
9
use GuzzleHttp\Client;
10
use GuzzleHttp\ClientInterface;
11
12
/**
13
 * Class SegmentRepository
14
 */
15
class SegmentRepository
16
{
17
18
    const BASE_URL = 'https://api.adnxs.com/segment/';
19
20
    /** @var Client */
21
    protected $client;
22
23
    /** @var  int */
24
    protected $memberId;
25
26
    /** @var  Cache */
27
    protected $cache;
28
29
    /** @var bool */
30
    protected $cacheEnabled;
31
32
    const CACHE_NAMESPACE  = 'appnexus_segment_repository_find_all';
33
    const CACHE_EXPIRATION = 3600;
34
35
    /**
36
     * SegmentRepository constructor.
37
     *
38
     * @param ClientInterface $client
39
     */
40
    public function __construct(ClientInterface $client, Cache $cache = null)
41
    {
42
        $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...
43
        $this->cache = $cache;
44
        $this->cacheEnabled = $cache instanceof Cache;
45
    }
46
47
    /**
48
     * @param Segment $segment
49
     *
50
     * @return RepositoryResponse
51
     * @throws \Exception
52
     */
53
    public function add(Segment $segment)
54
    {
55
56
        $compiledUrl = self::BASE_URL.$segment->getMemberId();
57
58
        $payload = [
59
            'segment' => [
60
                'active' => $segment->isActive(),
61
                'description' => $segment->getDescription(),
62
                'member_id' => $segment->getMemberId(),
63
                'code' => $segment->getCode(),
64
                'provider' => $segment->getProvider(),
65
                'price' => $segment->getPrice(),
66
                'short_name' => $segment->getName(),
67
                'expire_minutes' => $segment->getExpireMinutes(),
68
                'category' => $segment->getCategory(),
69
                'last_activity' => $segment->getLastActivity()->getTimestamp(),
70
                'enable_rm_piggyback' => $segment->isEnableRmPiggyback(),
71
            ],
72
        ];
73
74
        $response = $this->client->request('POST', $compiledUrl, ['body' => json_encode($payload)]);
75
76
        $repositoryResponse = RepositoryResponse::fromResponse($response);
77
78
        if ($repositoryResponse->isSuccessful()) {
79
80
            $stream = $response->getBody();
81
            $responseContent = json_decode($stream->getContents(), true);
82
            $stream->rewind();
83
84
            if (!(isset($responseContent['response']['segment']['id']))) {
85
                throw RepositoryException::wrongFormat(serialize($responseContent));
86
            }
87
88
            $segment->setId($responseContent['response']['segment']['id']);
89
        }
90
91
        return $repositoryResponse;
92
93
    }
94
95
    /**
96
     * @param $id
97
     * @param $memberId
98
     *
99
     * @return Segment|null
100
     */
101
    public function findOneById($id, $memberId)
102
    {
103
104
        $compiledUrl = self::BASE_URL.$memberId.'/'.$id;
105
106
        $response = $this->client->request('GET', $compiledUrl);
107
108
        $repositoryResponse = RepositoryResponse::fromResponse($response);
109
110
        if (!$repositoryResponse->isSuccessful()) {
111
            return null;
112
        }
113
114
        $stream = $response->getBody();
115
        $responseContent = json_decode($stream->getContents(), true);
116
        $stream->rewind();
117
118
        return Segment::fromArray($responseContent['response']['segment']);
119
120
    }
121
122
    /**
123
     * @param     $memberId
124
     * @param int $start
125
     * @param int $maxResults
126
     *
127
     * @return Segment|null
128
     */
129
    public function findAll($memberId, $start = 0, $maxResults = 100)
130
    {
131
132
        if ($this->isCacheEnabled()) {
133
            $cacheKey = self::CACHE_NAMESPACE.sha1($memberId.$start.$maxResults);
134
            if ($this->cache->contains($cacheKey)) {
135
                return $this->cache->fetch($cacheKey);
136
            }
137
138
        }
139
140
        $compiledUrl = self::BASE_URL.$memberId."?start_element=$start&num_elements=$maxResults";
141
142
        $response = $this->client->request('GET', $compiledUrl);
143
144
        $repositoryResponse = RepositoryResponse::fromResponse($response);
145
146
        if (!$repositoryResponse->isSuccessful()) {
147
            return null;
148
        }
149
150
        $stream = $response->getBody();
151
        $responseContent = json_decode($stream->getContents(), true);
152
        $stream->rewind();
153
154
        $result = [];
155
156
        foreach ($responseContent['response']['segments'] as $segmentArray) {
157
            $result[] = Segment::fromArray($segmentArray);
158
        }
159
160
161
        if ($this->isCacheEnabled()) {
162
            $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...
163
        }
164
165
        return $result;
166
167
    }
168
169
    /**
170
     * @return boolean
171
     */
172
    public function isCacheEnabled()
173
    {
174
        return $this->cacheEnabled;
175
    }
176
177
    /**
178
     * @param boolean $cacheEnabled
179
     */
180
    public function setCacheEnabled($cacheEnabled)
181
    {
182
        $this->cacheEnabled = $cacheEnabled;
183
    }
184
185
186
}
187