Transport::poll()   B
last analyzed

Complexity

Conditions 5
Paths 17

Size

Total Lines 47
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 47
ccs 0
cts 41
cp 0
rs 8.5125
c 0
b 0
f 0
cc 5
eloc 30
nc 17
nop 0
crap 30
1
<?php
2
/**
3
 * @author Jean Silva <[email protected]>
4
 * @license MIT
5
 */
6
namespace Jeancsil\FlightSpy\Api\Http;
7
8
use GuzzleHttp\ClientInterface;
9
use GuzzleHttp\Exception\BadResponseException;
10
use Jeancsil\FlightSpy\Api\DataTransfer\SessionParameters;
11
use Jeancsil\FlightSpy\Service\ElasticSearch\ElasticSearchWriterTrait;
12
use Jeancsil\FlightSpy\History\ElasticSearch\MappingProcessor;
13
use Psr\Log\LoggerAwareTrait;
14
15
class Transport implements TransportInterface
16
{
17
    use LoggerAwareTrait;
18
    use ElasticSearchWriterTrait;
19
20
    const LIVE_PRICING = '/apiservices/pricing/v1.0';
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 11 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...
21
    const WAITING_TIME_IN_MILLIS = 500000;
22
23
    /**
24
     * @var \GuzzleHttp\Client
25
     */
26
    private $client;
27
28
    /**
29
     * @var string
30
     */
31
    private $pollUrl;
32
33
    /**
34
     * @param ClientInterface $client
35
     */
36
    public function __construct(ClientInterface $client)
37
    {
38
        $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...
39
    }
40
41
    /**
42
     * @param SessionParameters $parameters
43
     * @param bool $newSession
44
     * @return \stdClass
45
     */
46
    public function findQuotes(SessionParameters $parameters, $newSession)
47
    {
48
        if ($newSession) {
49
            $this->createSession($parameters);
50
        }
51
52
        return $this->poll();
53
    }
54
55
    /**
56
     * @param SessionParameters $parameters
57
     * @throws \Exception
58
     */
59
    private function createSession(SessionParameters $parameters)
60
    {
61
        try {
62
            $parametersArray = $parameters->toArray();
63
64
            $request = $this
65
                ->client
66
                ->post(static::LIVE_PRICING, ['form_params' => $parametersArray]);
67
68
            if (!isset($request->getHeaders()['Location'][0])) {
69
                throw new \Exception('Location not found for the poll');
70
            }
71
72
            $this->setPollUrl($request->getHeaders()['Location'][0], $parametersArray['apiKey']);
73
            usleep(static::WAITING_TIME_IN_MILLIS);
74
        } catch (BadResponseException $e) {
75
            $this->logger->error(
76
                sprintf(
77
                    "[Transport::createSession]\nStatusCode: %d\nBody: %s",
78
                    $e->getResponse()->getStatusCode(),
79
                    $e->getResponse()->getBody()
80
                )
81
            );
82
83
            throw $e;
84
        }
85
    }
86
87
    /**
88
     * @return \stdClass
89
     */
90
    private function poll()
91
    {
92
        try {
93
            $response = $this
94
                ->client
95
                ->get($this->pollUrl);
96
97
            $this->logger->info("HTTPStatusCode: " . $response->getStatusCode());
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal HTTPStatusCode: does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
98
99
            if ($response->getStatusCode() != 200) {
100
                return;
101
            }
102
103
            $arrayContent = \GuzzleHttp\json_decode(
104
                str_replace("'", '\'', $response->getBody()->getContents()),
105
                true
106
            );
107
108
            if (!is_array($arrayContent)) {
109
                $this->logger->critical(
110
                    sprintf('Expecting $arrayContent to be an array. %s given.', gettype($arrayContent))
111
                );
112
                return;
113
            }
114
115
            $this->getElasticSearchWriter()
116
                ->setProcessor(new MappingProcessor())
117
                ->write($arrayContent);
118
119
            return (object) $arrayContent;
120
        } catch (BadResponseException $e) {
121
            $this->logger->error(
122
                sprintf(
123
                    "[Transport::pool]\nStatusCode: %d\nBody: %s",
124
                    $e->getResponse()->getStatusCode(),
125
                    $e->getResponse()->getBody()
126
                )
127
            );
128
        } catch (\Exception $e) {
129
            $this->logger->error(
130
                sprintf(
131
                    "[Transport::pool]\nException:\n%s",
132
                    $e->getMessage()
133
                )
134
            );
135
        }
136
    }
137
138
    /**
139
     * @param string $url
140
     * @param string $apiKey
141
     */
142
    private function setPollUrl($url, $apiKey)
143
    {
144
        $this->pollUrl = "$url?apiKey=$apiKey&sorttype=price&sortorder=asc";
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $url 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 $apiKey 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...
145
        $this->logger->debug("Pool url is: $this->pollUrl");
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $this 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...
146
    }
147
}
148