Completed
Push — master ( e7435a...ed4f51 )
by Francesco
03:00
created

UserSegmentRepository::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
3
namespace Audiens\AppnexusClient\repository;
4
5
use Audiens\AppnexusClient\Auth;
6
use Audiens\AppnexusClient\entity\UserSegment;
7
use Doctrine\Common\Cache\Cache;
8
use GuzzleHttp\Client;
9
use GuzzleHttp\ClientInterface;
10
11
/**
12
 * Class UserSegmentRepository
13
 */
14
class UserSegmentRepository
15
{
16
17
    const BASE_URL = 'http://api.appnexus.com/batch-segment';
18
//    const BASE_URL_ADNXS = 'http://sand.api.appnexus.com/batch-segment';
19
20
    /** @var  \SplQueue */
21
    protected $userSegments;
22
23
    /** @var Client|Auth */
24
    protected $client;
25
26
    /** @var  int */
27
    protected $memberId;
28
29
    /** @var  Cache */
30
    protected $cache;
31
32
    /** @var bool */
33
    protected $cacheEnabled;
34
35
    const CACHE_NAMESPACE = 'appnexus_segment_user_upload';
36
37
    const CACHE_EXPIRATION = 3600;
38
39
    /**
40
     * SegmentRepository constructor.
41
     *
42
     * @param ClientInterface $client
43
     * @param Cache|null      $cache
44
     */
45
    public function __construct(ClientInterface $client, Cache $cache = null)
46
    {
47
        $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...
48
        $this->cache = $cache;
49
        $this->cacheEnabled = $cache instanceof Cache;
50
51
    }
52
53
54
    /**
55
     * @param $fileAsString
56
     * @param $memberId
57
     *
58
     * @return RepositoryResponse
59
     * @throws \Exception
60
     */
61
    public function upload($fileAsString,$memberId){
62
63
        $tempFile = tmpfile();
64
65
        fwrite($tempFile, $fileAsString);
66
        fseek($tempFile, 0);
67
68
69
        $url = $this->getUploadUrl($memberId);
70
71
        $contentPayload = [
0 ignored issues
show
Unused Code introduced by
$contentPayload is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
72
            # Content-Disposition: form-data; name="file"; filename="/the/full/path/of/image/file/you/want/to/upload.png"
73
            'Content-Disposition' => sprintf('form-data; name="%s"; filename="%s"', 'file', $myFile),
0 ignored issues
show
Bug introduced by
The variable $myFile does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
74
            # Content-Type: application/octet-stream
75
            # 'Content-Type' => 'application/octet-stream'
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
76
        ];
77
78
        $response = $this->client->request('PUT', $url, ['body' => $tempFile]);
79
80
        $stream = $response->getBody();
81
82
        $responseContent = json_decode($stream->getContents(), true);
83
84
85
        print_r($responseContent);die();
0 ignored issues
show
Coding Style Compatibility introduced by
The method upload() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
86
87
88
89
90
        fclose($tempFile); // this removes the file
0 ignored issues
show
Unused Code introduced by
fclose($tempFile); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
91
92
93
    }
94
95
96
97
    /**
98
     * @param $memberId
99
     *
100
     * @return string
101
     * @throws \Exception
102
     */
103
    public function getUploadUrl($memberId)
104
    {
105
106
        $compiledUrl = self::BASE_URL.'?member_id='.$memberId;
107
108
        $response = $this->client->request('POST', $compiledUrl);
109
110
        $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...
111
112
        if (!$repositoryResponse->isSuccessful()) {
113
            throw new \Exception('name me');
114
        }
115
116
        if (!isset($responseContent['response']['batch_segment_upload_job']['upload_url'])) {
0 ignored issues
show
Bug introduced by
The variable $responseContent seems only to be defined at a later point. As such the call to isset() seems to always evaluate to false.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
117
            throw new \Exception('name me');
118
        }
119
120
        $stream = $response->getBody();
121
        $responseContent = json_decode($stream->getContents(), true);
122
        $stream->rewind();
123
124
        return $responseContent['response']['batch_segment_upload_job']['upload_url'];
125
126
    }
127
128
129
    /**
130
     * @return boolean
131
     */
132
    public function isCacheEnabled()
133
    {
134
        return $this->cacheEnabled;
135
    }
136
137
    public function disableCache()
138
    {
139
        $this->cacheEnabled = false;
140
    }
141
142
    public function enableCache()
143
    {
144
        $this->cacheEnabled = true;
145
    }
146
147
}
148