FactomConnector::__construct()   C
last analyzed

Complexity

Conditions 14
Paths 11

Size

Total Lines 37
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
rs 5.0864
c 0
b 0
f 0
cc 14
eloc 28
nc 11
nop 5

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace AdrianMejias\FactomApi;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\RequestException;
7
use AdrianMejias\FactomApi\Exceptions\InvalidFactomApiConfig;
8
9
class FactomConnector
10
{
11
    /**
12
     * The JSON RPC spec that the API uses.
13
     *
14
     * @var string
15
     */
16
    const JSON_RPC = '2.0';
17
18
    /**
19
     * The "ID" param provided in all requests to the API.
20
     *
21
     * @var int
22
     */
23
    const REQUEST_ID = 0;
24
25
    /**
26
     * The header content type in all requests to the API.
27
     *
28
     * @var string
29
     */
30
    const HEADER_CONTENT_TYPE = 'text/plain';
31
32
    /**
33
     * The header accept in all requests to the API.
34
     *
35
     * @var string
36
     */
37
    const HEADER_ACCEPT = 'application/json';
38
39
    /**
40
     * The generic error if cannot load server properly.
41
     *
42
     * @var string
43
     */
44
    const BLANK_PAGE_ERROR = 'Page not found';
45
46
    /**
47
     * The client instance.
48
     *
49
     * @var null|GuzzleHttp\Client
50
     */
51
    protected $client = null;
52
53
    /**
54
     * The URL for all API requests.
55
     *
56
     * @var null|string
57
     */
58
    protected $url = 'http://localhost:8088/v2';
59
60
    /**
61
     * Make secure URL requests.
62
     *
63
     * @var null|bool
64
     */
65
    protected $ssl = false;
66
67
    /**
68
     * Path to the certificate file for using factomd over TLS.
69
     *
70
     * @var null
71
     */
72
    protected $certifcate = null;
73
74
    /**
75
     * The provided username for interacting with factomd
76
     * Optional.
77
     *
78
     * @var null
79
     */
80
    protected $username = null;
81
82
    /**
83
     * The provided password for interacting with factomd
84
     * Optional.
85
     *
86
     * @var null
87
     */
88
    protected $password = null;
89
90
    public function __construct(string $url, bool $ssl = false, string $certificate = null, string $username = null, string $password = null)
91
    {
92
        $this->url = $url;
93
        $this->ssl = $ssl;
94
        $this->certificate = $certificate;
0 ignored issues
show
Bug introduced by
The property certificate does not seem to exist. Did you mean certifcate?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
95
        $this->username = $username;
0 ignored issues
show
Documentation Bug introduced by
It seems like $username can also be of type string. However, the property $username is declared as type null. Maybe add an additional type 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 mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
96
        $this->password = $password;
0 ignored issues
show
Documentation Bug introduced by
It seems like $password can also be of type string. However, the property $password is declared as type null. Maybe add an additional type 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 mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
97
98
        if (! function_exists('curl_init')) {
99
            throw InvalidFactomApiConfig::noCurlFound();
100
        } elseif (empty($this->url)) {
101
            throw InvalidFactomApiConfig::noUrlDefined();
102
        } elseif (empty($this->certificate) && $this->ssl) {
0 ignored issues
show
Bug introduced by
The property certificate does not seem to exist. Did you mean certifcate?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
103
            throw InvalidFactomApiConfig::noCertificateDefined();
104
        } elseif (! empty($this->certificate) && $this->ssl) {
0 ignored issues
show
Bug introduced by
The property certificate does not seem to exist. Did you mean certifcate?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
105
            if (preg_match('/^(https:\/\/)/i', $this->url)) {
106
                throw InvalidFactomApiConfig::noSecureUrlDefined();
107
            } elseif (! file_exists($this->certificate)) {
0 ignored issues
show
Bug introduced by
The property certificate does not seem to exist. Did you mean certifcate?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
108
                throw InvalidFactomApiConfig::noCertificateExists();
109
            }
110
        } elseif (! empty($this->username) && empty($this->password)) {
111
            throw InvalidFactomApiConfig::noUsernameDefined();
112
        } elseif (empty($this->username) && ! empty($this->password)) {
113
            throw InvalidFactomApiConfig::noPasswordDefined();
114
        }
115
116
        if (! $this->ssl) {
117
            $this->certificate = null;
0 ignored issues
show
Bug introduced by
The property certificate does not seem to exist. Did you mean certifcate?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
118
        }
119
120
        $this->client = new Client([
0 ignored issues
show
Documentation Bug introduced by
It seems like new \GuzzleHttp\Client(a...lse, 'debug' => false)) of type object<GuzzleHttp\Client> is incompatible with the declared type null|object<AdrianMejias...mApi\GuzzleHttp\Client> of property $client.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
121
            'base_uri' => rtrim($this->url, '/').'/',
122
            'timeout' => 10,
123
            'http_errors' => false,
124
            'debug' => false,
125
        ]);
126
    }
127
128
    /**
129
     * Call the requested endpoint.
130
     *
131
     * @param string $actionName
0 ignored issues
show
Documentation introduced by
There is no parameter named $actionName. Did you maybe mean $action?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
132
     * @param array $params
133
     * @param array $extraOptions
134
     *
135
     * @return object|string
136
     *
137
     * @throws Exception When a Guzzle error occurs
138
     */
139
    public function callEndpoint(string $action, string $method, array $params = [], array $extraOptions = [])
140
    {
141
        // Check our method...
142
        if (! in_array(strtoupper($method), ['GET', 'POST'])) {
143
            throw InvalidFactomApiConfig::invalidMethodCalled();
144
        }
145
146
        $options = [
147
            'headers' => [
148
                'Content-Type' => self::HEADER_CONTENT_TYPE,
149
                'Accept' => self::HEADER_ACCEPT,
150
            ],
151
            // 'verify' => false,
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
152
            'json' => [
153
                'jsonrpc' => self::JSON_RPC,
154
                'id' => self::REQUEST_ID,
155
                'method' => strtolower($action),
156
                'params' => $params,
157
            ],
158
        ] + $extraOptions;
159
160
        // Append certificate verification
161
        // if ($this->ssl) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
162
        // $options['verify'] = $this->certificate;
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
163
        // $options['cert'] = [
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
164
        //     'cert' => [
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...
165
        //         $this->certificate,
166
        //         $this->password
167
        //     ],
168
        // ];
169
        // }
170
171
        // Append authentication to params
172
        if (! empty($this->username) && ! empty($this->password)) {
173
            $options['auth'] = [
174
                'username' => $this->username,
175
                'password' => $this->password,
176
            ];
177
        }
178
179
        $response = null;
180
        $error = null;
181
182
        // Make the call to factom server
183
        try {
184
            $response = $this->client->{strtolower($method)}($this->url, $options);
185
        } catch (RequestException $e) {
186
            $error = $e->getMessage();
187
        }
188
189
        if (! empty($error)) {
190
            throw InvalidFactomApiConfig::invalidApiResponse($error, $action);
191
        }
192
193
        $status_code = $response->getStatusCode();
194
        $reason_phrase = $response->getReasonPhrase();
195
        $body = (string) $response->getBody()->getContents();
196
197
        // Check for empty body
198
        if (empty($body)) {
199
            throw InvalidFactomApiConfig::emptyApiResponse($action);
200
        } elseif ($status_code != 200) {
201
            throw InvalidFactomApiConfig::invalidApiResponse($reason_phrase, $action);
202
        }
203
204
        // return Json
205
        if ($json_body = json_decode($body)) {
206
            // Check for empty result
207
            if (empty($json_body->result)) {
208
                throw InvalidFactomApiConfig::emptyApiResponse($action);
209
            }
210
211
            return $json_body->result;
212
        }
213
214
        // return Response
215
        return $body;
216
    }
217
}
218