GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

TraitRepository::setTrendUrl()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Audiens\AdobeClient\Repository;
4
5
use Audiens\AdobeClient\Auth;
6
use Audiens\AdobeClient\CachableTrait;
7
use Audiens\AdobeClient\CacheableInterface;
8
use Audiens\AdobeClient\Entity\TraitMetrics;
9
use Audiens\AdobeClient\Entity\Traits;
10
use Audiens\AdobeClient\Exceptions\RepositoryException;
11
use Doctrine\Common\Cache\Cache;
12
use GuzzleHttp\Client;
13
use GuzzleHttp\ClientInterface;
14
15
/**
16
 * Class TraitRepository
17
 */
18
class TraitRepository implements CacheableInterface
19
{
20
    use CachableTrait;
21
22
    const BASE_URL = 'https://api.demdex.com:443/v1/traits/';
23
24
    const SANDBOX_BASE_URL = 'https://api-beta.demdex.com:443/v1/traits/';
25
26
    const TRAITS_TREND_URL = 'https://bank.demdex.com/portal/api/v1/reports/traits-trend';
27
28
    const SANDBOX_TREND_URL = 'https://bank-beta.demdex.com/portal/api/v1/reports/traits-trend';
29
30
    /** @var Client */
31
    protected $client;
32
33
    /** @var  Cache */
34
    protected $cache;
35
36
    /** @var  string */
37
    protected $baseUrl;
38
39
    /** @var  string */
40
    protected $trendUrl;
41
42
    const CACHE_NAMESPACE = 'adobe_trait_repository_find_all';
43
44
    const CACHE_EXPIRATION = 3600;
45
46
    /**
47
     * TraitRepository constructor.
48
     *
49
     * @param ClientInterface $client
50
     * @param Cache|null $cache
51
     */
52 View Code Duplication
    public function __construct(ClientInterface $client, Cache $cache = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
53
    {
54
        $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...
55
        $this->cache = $cache;
56
        $this->cacheEnabled = $cache instanceof Cache;
57
        $this->baseUrl = self::BASE_URL;
58
        $this->trendUrl = self::TRAITS_TREND_URL;
59
    }
60
61
    /**
62
     * @return string
63
     */
64
    public function getBaseUrl()
65
    {
66
        return $this->baseUrl;
67
    }
68
69
    /**
70
     * @param string $baseUrl
71
     */
72
    public function setBaseUrl($baseUrl)
73
    {
74
        $this->baseUrl = $baseUrl;
75
    }
76
77
    /**
78
     * @return string
79
     */
80
    public function getTrendUrl()
81
    {
82
        return $this->trendUrl;
83
    }
84
85
    /**
86
     * @param string $trendUrl
87
     */
88
    public function setTrendUrl($trendUrl)
89
    {
90
        $this->trendUrl = $trendUrl;
91
    }
92
93
94
95
    /**
96
     * @param $id
97
     *
98
     * @return Traits|null
99
     */
100
    public function findOneById($id)
101
    {
102
103
        $compiledUrl = $this->baseUrl . $id.'?includeMetrics=true';
104
105
        $response = $this->client->request('GET', $compiledUrl);
106
107
        $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...
108
109
        if (!$repositoryResponse->isSuccessful()) {
110
            return null;
111
        }
112
113
        $stream = $response->getBody();
114
        $responseContent = json_decode($stream->getContents(), true);
115
        $stream->rewind();
116
117
        return Traits::fromArray($responseContent);
118
    }
119
120
    public function findAll()
121
    {
122
        $date = date('Y_m_d_H');
123
124
        $cacheKey = self::CACHE_NAMESPACE . sha1($date);
125
126
        if ($this->isCacheEnabled()) {
127
            if ($this->cache->contains($cacheKey)) {
128
                return $this->cache->fetch($cacheKey);
129
            }
130
        }
131
132
        $compiledUrl = $this->baseUrl . "?includeMetrics=true";
133
134
        $response = $this->client->request('GET', $compiledUrl);
135
136
137
        $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...
138
139
140
        if (!$repositoryResponse->isSuccessful()) {
141
            throw RepositoryException::genericFailed($repositoryResponse);
0 ignored issues
show
Documentation introduced by
$repositoryResponse is of type object<Audiens\AdobeClie...ory\RepositoryResponse>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
142
        }
143
144
        $stream = $response->getBody();
145
        $responseContent = json_decode($stream->getContents(), true);
146
        $stream->rewind();
147
148
        $result = [];
149
150
        foreach ($responseContent as $traitArray) {
151
            $result[] = Traits::fromArray($traitArray);
152
        }
153
154
        if ($this->isCacheEnabled()) {
155
            $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
156
        }
157
158
        return $result;
159
    }
160
161
    /**
162
     * @param $sid
163
     * @param \DateTime $startDate
164
     * @param \DateTime $endDate
165
     * @param string $dayInterval
166
     * @return array
167
     * @throws RepositoryException
168
     */
169
    public function getTrendByTrait($sid, \DateTime $startDate, \DateTime $endDate, $dayInterval = '1D')
170
    {
171
        $cacheKey = self::CACHE_NAMESPACE . sha1($startDate->getTimestamp().$endDate->getTimestamp());
172
173
        if ($this->isCacheEnabled()) {
174
            if ($this->cache->contains($cacheKey)) {
175
                return $this->cache->fetch($cacheKey);
176
            }
177
        }
178
179
        $bodyPost =
180
            [
181
                'startDate' => $startDate->getTimestamp() * 1000,
182
                'endDate' => $endDate->getTimestamp() * 1000,
183
                'interval' => $dayInterval,
184
                'sids' => [$sid],
185
                'usePartnerLevelOverlap' => false
186
            ];
187
188
        $response = $this->client->request(
189
            'POST',
190
            $this->trendUrl,
191
            [
192
                'headers' =>
193
                    [
194
                        'Content-Type' => 'application/json',
195
                    ],
196
                    'body' => \json_encode($bodyPost)
197
            ]
198
        );
199
200
        $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...
201
202
        if (!$repositoryResponse->isSuccessful()) {
203
            throw RepositoryException::genericFailed($repositoryResponse);
0 ignored issues
show
Documentation introduced by
$repositoryResponse is of type object<Audiens\AdobeClie...ory\RepositoryResponse>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
204
        }
205
206
        $stream = $response->getBody();
207
        $responseContent = json_decode($stream->getContents(), true);
208
        $stream->rewind();
209
210
211
        $result = [];
212
213
        foreach ($responseContent as $traitArray) {
214
            if (!empty($traitArray['metrics']) && count($traitArray['metrics']) > 0) {
215
                $traitObj = Traits::fromArray($traitArray);
216
217
                $traitObj->setMetrics([]);
218
219
                foreach ($traitArray['metrics'] as $timestamp => $metric) {
220
                    $traitMetric = new TraitMetrics();
221
222
                    $time = $timestamp / 1000;
223
                    $dateObj = new \DateTime();
224
                    $dateObj->setTimestamp($time);
225
                    $traitMetric->setTimestamp($dateObj);
226
                    $traitMetric->setCount($metric['count']);
227
                    $traitMetric->setUniques($metric['uniques']);
228
229
                    $traitObj->addMetrics($traitMetric);
230
                }
231
232
                $result[] = $traitObj;
233
            }
234
        }
235
236
        if ($this->isCacheEnabled()) {
237
            $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
238
        }
239
240
        return $result;
241
    }
242
}
243