Completed
Push — master ( 17f60e...660cd0 )
by Francesco
05:55
created

SegmentRepository   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 185
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 14
c 1
b 0
f 0
lcom 1
cbo 9
dl 0
loc 185
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B add() 0 41 3
B findOneById() 0 27 2
B findAll() 0 45 6
A isCacheEnabled() 0 4 1
A setCacheEnabled() 0 4 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 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...
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 7 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
43
        $this->cache = $cache;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 8 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
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();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 10 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
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();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 10 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
115
        $responseContent = json_decode($stream->getContents(), true);
116
        $stream->rewind();
117
118
        $config = new Configuration(Segment::class);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 8 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
119
        $hydratorClass = $config->createFactory()->getHydratorClass();
120
        $hydrator = new $hydratorClass();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
121
        $segment = new Segment();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 7 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
122
123
        $hydrator->hydrate($responseContent['response']['segment'], $segment);
124
125
        return $segment;
126
127
    }
128
129
    /**
130
     * @param     $memberId
131
     * @param int $start
132
     * @param int $maxResults
133
     *
134
     * @return Segment|null
135
     */
136
    public function findAll($memberId, $start = 0, $maxResults = 100)
137
    {
138
139
        if ($this->isCacheEnabled()){
140
            $cacheKey = self::CACHE_NAMESPACE.sha1($memberId.$start.$maxResults);
141
            if ($this->cache->contains($cacheKey)) {
142
                return $this->cache->fetch($cacheKey);
143
            }
144
145
        }
146
147
        $compiledUrl = self::BASE_URL.$memberId."?start_element=$start&num_elements=$maxResults";
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $start instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $maxResults instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
148
149
        $response = $this->client->request('GET', $compiledUrl);
150
151
        $repositoryResponse = RepositoryResponse::fromResponse($response);
152
153
        if (!$repositoryResponse->isSuccessful()) {
154
            return null;
155
        }
156
157
        $stream = $response->getBody();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 10 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
158
        $responseContent = json_decode($stream->getContents(), true);
159
        $stream->rewind();
160
161
        $config = new Configuration(Segment::class);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 8 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
162
        $hydratorClass = $config->createFactory()->getHydratorClass();
163
        $hydrator = new $hydratorClass();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
164
165
        $result = [];
166
167
        foreach ($responseContent['response']['segments'] as $segmentArray) {
168
            $segment = new Segment();
169
            $hydrator->hydrate($segmentArray, $segment);
170
171
            $result[] = clone $segment;
172
        }
173
174
        if ($this->isCacheEnabled()) {
175
            $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...
176
        }
177
178
        return $result;
179
180
    }
181
182
    /**
183
     * @return boolean
184
     */
185
    public function isCacheEnabled()
186
    {
187
        return $this->cacheEnabled;
188
    }
189
190
    /**
191
     * @param boolean $cacheEnabled
192
     */
193
    public function setCacheEnabled($cacheEnabled)
194
    {
195
        $this->cacheEnabled = $cacheEnabled;
196
    }
197
198
199
}
200