Completed
Push — master ( 3a1449...d95c29 )
by Jean
02:46
created

Transport   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 125
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 10
dl 0
loc 125
ccs 0
cts 75
cp 0
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A findQuotes() 0 8 2
B createSession() 0 27 3
B poll() 0 40 4
A setPollUrl() 0 5 1
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\History\ElasticSearch\ElasticSearchWriterTrait;
12
use Jeancsil\FlightSpy\History\ElasticSearch\MappingProcessor;
13
use Psr\Log\LoggerAwareTrait;
14
15
class Transport
16
{
17
    use LoggerAwareTrait;
18
    use ElasticSearchWriterTrait;
19
20
    const LIVE_PRICING = '/apiservices/pricing/v1.0';
21
22
    /**
23
     * @var \GuzzleHttp\Client
24
     */
25
    private $client;
26
27
    /**
28
     * @var string
29
     */
30
    private $pollUrl;
31
32
    /**
33
     * @param ClientInterface $client
34
     */
35
    public function __construct(ClientInterface $client)
36
    {
37
        $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...
38
    }
39
40
    /**
41
     * @param SessionParameters $parameters
42
     * @param bool $newSession
43
     * @return \stdClass
44
     */
45
    public function findQuotes(SessionParameters $parameters, $newSession)
46
    {
47
        if ($newSession) {
48
            $this->createSession($parameters);
49
        }
50
51
        return $this->poll();
52
    }
53
54
    /**
55
     * @param SessionParameters $parameters
56
     * @throws \Exception
57
     */
58
    private function createSession(SessionParameters $parameters)
59
    {
60
        try {
61
            $parametersArray = $parameters->toArray();
62
63
            $request = $this
64
                ->client
65
                ->post(static::LIVE_PRICING, ['form_params' => $parametersArray]);
66
67
            if (!isset($request->getHeaders()['Location'][0])) {
68
                throw new \Exception('Location not found for the poll');
69
            }
70
71
            $this->setPollUrl($request->getHeaders()['Location'][0], $parametersArray['apiKey']);
72
            sleep(1);
73
        } catch (BadResponseException $e) {
74
            $this->logger->error(
75
                sprintf(
76
                    "[Transport::createSession]\nStatusCode: %d\nBody: %s",
77
                    $e->getResponse()->getStatusCode(),
78
                    $e->getResponse()->getBody()
79
                )
80
            );
81
82
            throw $e;
83
        }
84
    }
85
86
    /**
87
     * @return \stdClass
88
     */
89
    private function poll()
90
    {
91
        try {
92
            $response = $this
93
                ->client
94
                ->get($this->pollUrl);
95
96
            $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...
97
            $contents = str_replace("'", '\'', $response->getBody()->getContents());
98
99
            $arrayContent = \GuzzleHttp\json_decode($contents, true);
100
            if (!is_array($arrayContent)) {
101
                $this->logger->critical(
102
                    sprintf('Expecting $arrayContent to be an array. %s given.', gettype($arrayContent))
103
                );
104
                return;
105
            }
106
107
            $this->getElasticSearchWriter()
108
                ->setProcessor(new MappingProcessor())
109
                ->write($arrayContent);
110
111
            return (object) $arrayContent;
112
        } catch (BadResponseException $e) {
113
            $this->logger->error(
114
                sprintf(
115
                    "[Transport::pool]\nStatusCode: %d\nBody: %s",
116
                    $e->getResponse()->getStatusCode(),
117
                    $e->getResponse()->getBody()
118
                )
119
            );
120
        } catch (\Exception $e) {
121
            $this->logger->error(
122
                sprintf(
123
                    "[Transport::pool]\nException:\n%s",
124
                    $e->getMessage()
125
                )
126
            );
127
        }
128
    }
129
130
    /**
131
     * @param string $url
132
     * @param string $apiKey
133
     */
134
    private function setPollUrl($url, $apiKey)
135
    {
136
        $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...
137
        $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...
138
    }
139
}
140