WindguruAPI::_getOnlineData()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 52
rs 9.0472
c 0
b 0
f 0
cc 4
nc 4
nop 0

How to fix   Long Method   

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
 * File WindguruAPI.php
4
 *
5
 * PHP Version 5
6
 *
7
 * @category PHP
8
 * @package  WindguruIO
9
 * @author   Voidtek <[email protected]>
10
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
11
 * @link     https://github.com/voidtek/windguru.io
12
 */
13
14
namespace voidtek\WindguruIO;
15
16
use Http\Discovery\HttpClientDiscovery;
17
use Http\Discovery\MessageFactoryDiscovery;
18
use Monolog\Logger;
19
use Monolog\Handler\StreamHandler;
20
21
/**
22
 * WindguruAPI Class
23
 *
24
 * @category Class
25
 * @package  WindguruIO
26
 * @author   Voidtek <[email protected]>
27
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
28
 * @link     https://github.com/voidtek/windguru.io
29
 */
30
class WindguruAPI
31
{
32
33
    /**
34
     * The default Windguru endpoint template.
35
     * Example: 'https://www.windguru.cz/int/iapi.php?q=ads_spot&id_spot%5B%5D=42'
36
     *
37
     * @var string;
38
    */
39
    const ENDPOINT='https://www.windguru.cz';
40
    const LOGFOLDER='logs';
41
    const CACHEFOLDER='cache';
42
    const CACHETIME=10*60;   // secondes
43
44
    /**
45
     * Private Id of the Spot
46
     *
47
     * @var string
48
     */
49
    private $_idSpot;
50
51
    /**
52
     * Private data of the Spot
53
     *
54
     * @var SimpleXMLElement
55
     */
56
    private $_data;
57
58
    /**
59
     * Private HttpClient
60
     *
61
     * @var HttpClient
62
     */
63
    private $_httpClient;
64
65
    /**
66
     * Private MessageFactory
67
     *
68
     * @var MessageFactory
69
     */
70
    private $_messageFactory;
71
72
    /**
73
     * Private MessageFactory
74
     *
75
     * @var MessageFactory
76
     */
77
    private $_log;
78
79
    /**
80
     * Constructor WindguruAPI
81
     *
82
     * @param HttpClient|null     $httpClient     The HttpClient parameter.
83
     * @param MessageFactory|null $messageFactory The messageFactory parameter.
84
     */
85
    public function __construct(
86
        HttpClient $httpClient = null,
87
        MessageFactory $messageFactory = null
88
    ) {
89
        date_default_timezone_set('UTC');
90
91
        $this->_httpClient = $httpClient ?: HttpClientDiscovery::find();
0 ignored issues
show
Documentation Bug introduced by
It seems like $httpClient ?: \Http\Dis...ClientDiscovery::find() can also be of type object<Http\Client\HttpClient>. However, the property $_httpClient is declared as type object<voidtek\WindguruIO\HttpClient>. 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...
92
        $this->_messageFactory = $messageFactory ?: MessageFactoryDiscovery::find();
0 ignored issues
show
Documentation Bug introduced by
It seems like $messageFactory ?: \Http...actoryDiscovery::find() can also be of type object<Http\Message\MessageFactory>. However, the property $_messageFactory is declared as type object<voidtek\WindguruIO\MessageFactory>. 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...
93
94
        if (!file_exists(self::CACHEFOLDER)) {
95
            mkdir(self::CACHEFOLDER, 0777, true);
96
        }
97
98
        if (!file_exists(self::LOGFOLDER)) {
99
            mkdir(self::LOGFOLDER, 0777, true);
100
        }
101
102
        $this->_log = new Logger('WindguruAPI');
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Monolog\Logger('WindguruAPI') of type object<Monolog\Logger> is incompatible with the declared type object<voidtek\WindguruIO\MessageFactory> of property $_log.

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...
103
        $this->_log->pushHandler(
104
            new StreamHandler(
105
                self::LOGFOLDER . '/' . date('Ymd') . '.log',
106
                Logger::WARNING
107
            )
108
        );
109
    }
110
111
    /**
112
     * Set the Id of the Spot.
113
     *
114
     * @param string $idSpot The id of the spot.
115
     *
116
     * @return nothing
117
     */
118
    public function setSpot($idSpot)
119
    {
120
        $this->_idSpot = $idSpot;
121
    }
122
123
    /**
124
     * Get the Id of the Spot.
125
     *
126
     * @return string
127
     */
128
    public function getSpot()
129
    {
130
        return $this->_idSpot;
131
    }
132
133
    /**
134
     * Set Data from Online source.
135
     *
136
     * @return DOMDocument
137
     */
138
    public function getData()
139
    {
140
        if (file_exists(self::CACHEFOLDER.'/'.$this->_idSpot)) {
141
            $this->_getCacheData();
142
        } else {
143
            $this->_getOnlineData();
144
        }
145
    }
146
147
    /**
148
     * Set Data from Online source.
149
     *
150
     * @return DOMDocument
151
     */
152
    private function _getOnlineData()
153
    {
154
        $request = $this->_messageFactory
155
            ->createRequest(
156
                'GET',
157
                self::ENDPOINT.'/'.$this->_idSpot
158
            );
159
160
        try {
161
            $response = $this->_httpClient->sendRequest($request);
162
        } catch (\Http\Client\Exception $e) {
163
            throw new \RuntimeException('Something happened during HTTP request');
164
        }
165
166
        $domDoc = new \DOMDocument();
167
        libxml_use_internal_errors(true);
168
        $domDoc->loadHtml($response->getBody());
169
        libxml_use_internal_errors(false);
170
        $element = $domDoc->getElementById('forecasts-page');
171
        $nodes = $element->childNodes;
172
173
        $xml = new \SimpleXMLElement('<xml/>');
174
        $xml->addAttribute('updated', time());
175
        $number = 1;
176
177
        foreach ($nodes as $node) {
178
            if ($node->nodeName == "script") {
179
                $nodeData = $xml->addChild('tab');
180
                $nodeData->addChild('number', $number);
181
                $nodeData->addChild(
182
                    'wg_fcst_tab_data',
183
                    $this->_extractVariableIntoScript(
184
                        $node->nodeValue,
185
                        'wg_fcst_tab_data_'.$number
186
                    )
187
                );
188
                $nodeData->addChild(
189
                    'wgopts',
190
                    $this->_extractVariableIntoScript(
191
                        $node->nodeValue,
192
                        'wgopts_'.$number
193
                    )
194
                );
195
                $number++;
196
            }
197
        }
198
199
        $this->_data = $xml;
0 ignored issues
show
Documentation Bug introduced by
It seems like $xml of type object<SimpleXMLElement> is incompatible with the declared type object<voidtek\WindguruIO\SimpleXMLElement> of property $_data.

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...
200
        $this->_setCacheData();
201
202
        $this->_log->warning($this->_idSpot . ": Load online data.");
203
    }
204
205
    /**
206
     * Extract value of a variable into the JS.
207
     *
208
     * @param string $script   The String.
209
     * @param string $variable The variable.
210
     *
211
     * @return string
212
     */
213
    private function _extractVariableIntoScript($script, $variable)
214
    {
215
        preg_match('/var ' . $variable . ' = (.*);/', $script, $m);
216
        return $m[1];
217
    }
218
219
    /**
220
     * Set the data of the Spot on cache.
221
     *
222
     * @return nothing
223
     */
224
    private function _setCacheData()
225
    {
226
        // todo assert notNull $this->_data.
227
228
        file_put_contents(
229
            self::CACHEFOLDER.'/'.$this->_idSpot,
230
            $this->_data->asXML()
231
        );
232
    }
233
234
    /**
235
     * Get the data of the Spot of cache.
236
     *
237
     * @return string/NULL.
0 ignored issues
show
Documentation introduced by
The doc-type string/NULL. could not be parsed: Unknown type name "string/NULL." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
238
     */
239
    private function _getCacheData()
240
    {
241
        $current = file_get_contents(self::CACHEFOLDER.'/'.$this->_idSpot);
242
        $xml = new \SimpleXMLElement($current);
243
        if (time() - $xml['updated'] <= self::CACHETIME) {
244
            $this->_data = $xml;
0 ignored issues
show
Documentation Bug introduced by
It seems like $xml of type object<SimpleXMLElement> is incompatible with the declared type object<voidtek\WindguruIO\SimpleXMLElement> of property $_data.

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...
245
            $this->_log->warning($this->_idSpot . ": Load cache data.");
246
        } else {
247
            $this->_getOnlineData();
248
        }
249
    }
250
251
}
252