ForecastIO::doFetchCurrent()   C
last analyzed

Complexity

Conditions 7
Paths 7

Size

Total Lines 51
Code Lines 38

Duplication

Lines 18
Ratio 35.29 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 18
loc 51
ccs 0
cts 40
cp 0
rs 6.9743
cc 7
eloc 38
nc 7
nop 1
crap 56

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
 *
4
 * PHP version 5.5
5
 *
6
 * @package Forecast
7
 * @author  Sergey V.Kuzin <[email protected]>
8
 * @license MIT
9
 */
10
11
namespace Forecast;
12
13
14
use Forecast\Helper\Point;
15
use Psr\Cache\CacheItemPoolInterface;
16
use Psr\Log\LoggerInterface;
17
18
/**
19
 * Получение информации о погоде с сервиса forecast.io.
20
 *
21
 * Для работы необходимо получить key на сайте https://developer.forecast.io
22
 *
23
 * PHP version 5.5
24
 *
25
 * @package Forecast
26
 * @author  Sergey V.Kuzin <[email protected]>
27
 * @license http://opensource.org/licenses/MIT The MIT License (MIT)
28
 *
29
 */
30
class ForecastIO extends WeatherAbstract
31
{
32
    /**
33
     * @var string
34
     */
35
    protected $apiKey = null;
36
    protected $pint = null;
37
38
    /**
39
     * Полу
40
     *
41
     * @param string $apiKey Ключ получченный на https://developer.forecast.io/
42
     *       Получить ключь можно бесплатно. Каждому дано 100 бесплатных запров в день к серверу.
43
     * @param CacheItemPoolInterface|null $cache Экземпляра класса кэширования по стандарту PSR-6
44
     * @param LoggerInterface|null $logger Экземляр класса логера сандарта PSR-3
45
     *
46
     * @api
47
     */
48
    public function __construct($apiKey, CacheItemPoolInterface $cache = null, LoggerInterface $logger = null)
49
    {
50
        $this->apiKey = $apiKey;
51
        parent::__construct($cache, $logger);
52
    }
53
54
    protected function doFetchAll(Point $point)
55
    {
56
        if ($point->getType() == Point::ADDRESS) {
57
            throw new \InvalidArgumentException();
58
        }
59
60
        $key = 'weather.fc.io-all-' . md5(serialize([$this->getLang(), $this->getUnits(), $point->getKey()]));
61
        $item = $this->cache->getItem($key);
62
        if (!$item->isHit()) {
63
            $params = [
64
                'units' => $this->getUnits(),
65
                'lang' => $this->getLang(),
66
                'exclude' => 'flags'
67
            ];
68
            $url = 'https://api.forecast.io/forecast/' . $this->apiKey . '/' . $point->getLatitude() . ',' . $point->getLongitude();
69
70
            $client = new \GuzzleHttp\Client();
71
72
            $response = $client->get($url, ['debug' => false, 'query' => $params]);
73
74
            $result = json_decode($response->getBody()->getContents(), true);
75
76
            if ($result !== null) {
77
                list($n, $exp) = explode('=', $response->getHeader('Cache-Control'));
0 ignored issues
show
Unused Code introduced by
The assignment to $n is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
78
                $exp = (int)$exp;
0 ignored issues
show
Unused Code introduced by
$exp 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...
79
                $exp  = 60*15;
80
                $this->expiration = \DateTime::createFromFormat(
0 ignored issues
show
Documentation Bug introduced by
It seems like \DateTime::createFromFormat('U', time() + $exp) can also be of type false. However, the property $expiration is declared as type object<DateTime>. 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...
81
                    'U',
82
                    time() + $exp
83
                );
84
                $item->set($result)
85
                    ->expiresAfter($exp)
86
                    ->addTag('weather');
87
                $this->cache->save($item);
88
            }
89
        }
90
91
        return $item->get();
92
    }
93
94
    /**
95
     * @internal
96
     * @return \Forecast\Current
97
     */
98
    protected function doFetchCurrent(Point $point)
99
    {
100
        if ($point->getType() == Point::ADDRESS) {
101
            throw new \InvalidArgumentException();
102
        }
103
        $result = $this->doFetchAll($point);
104
        $result = $result['currently'];
105
106
        $cur = new Current();
107
108
        $precipType = self::PRECIP_TYPE_NONE;
109 View Code Duplication
        if ($result['precipProbability'] > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
            switch ($result['precipType']) {
111
                case 'rain':
112
                    $precipType = self::PRECIP_TYPE_RAIN;
113
                    break;
114
                case 'snow':
115
                    $precipType = self::PRECIP_TYPE_SNOW;
116
                    break;
117
                case 'sleet':
118
                    $precipType = self::PRECIP_TYPE_SLEET;
119
                    break;
120
                case 'hail':
121
                    $precipType = self::PRECIP_TYPE_HAIL;
122
                    break;
123
                default:
124
                    throw new \Exception('Не известный тип precipType: ' . $result['precipType']);
125
            }
126
        }
127
        $cur->setData([
128
            'summary' => $result['summary'],
129
            'temperature' => [
130
                'current' => $result['temperature'],
131
                'apparent' => $result['apparentTemperature']
132
            ],
133
            'wind' => [
134
                'speed' => $result['windSpeed'],
135
                'degree' => $result['windBearing'],
136
            ],
137
            'precipitation' => [
138
                'intensity' => $result['precipIntensity'],
139
                'probability' => $result['precipProbability'] * 100,
140
                'type' => $precipType,
141
            ],
142
            'humidity' => [
143
                'humidity' => $result['humidity']
144
            ]
145
        ]);
146
147
        return $cur;
148
    }
149
150
    /**
151
     * @param Point $point Класс с коорденатами места для которой запрашивается погода
152
     * @internal
153
     * @return string
154
     */
155
    protected function getCacheKeyCurrent(Point $point)
156
    {
157
        return 'weather.fc.io-current-' . md5(serialize([$this->getLang(), $this->getUnits(), $point->getKey()]));
158
    }
159
160
    /**
161
     * @internal
162
     * @return \DateTime
163
     */
164
    protected function getCacheExpirationCurrent()
165
    {
166
        return $this->expiration;
167
    }
168
169
    /**
170
     * @param Point $point
171
     * @return Hourly
172
     */
173
    protected function doFetchHourly(Point $point)
174
    {
175
        if ($point->getType() == Point::ADDRESS) {
176
            throw new \InvalidArgumentException();
177
        }
178
179
        $result = $this->doFetchAll($point);
180
        $result = $result['hourly'];
181
182
        $hours = [];
183
        foreach ($result['data'] as $item) {
184
            $precipType = self::PRECIP_TYPE_NONE;
185 View Code Duplication
            if ($item['precipProbability'] > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
186
                switch ($item['precipType']) {
187
                    case 'rain':
188
                        $precipType = self::PRECIP_TYPE_RAIN;
189
                        break;
190
                    case 'snow':
191
                        $precipType = self::PRECIP_TYPE_SNOW;
192
                        break;
193
                    case 'sleet':
194
                        $precipType = self::PRECIP_TYPE_SLEET;
195
                        break;
196
                    case 'hail':
197
                        $precipType = self::PRECIP_TYPE_HAIL;
198
                        break;
199
                    default:
200
                        throw new \Exception('Не известный тип precipType: ' . $item['precipType']);
201
                }
202
            }
203
204
            $hours[] = [
205
                'summary' => $item['summary'],
206
                'date' => new \DateTime(date(\DateTime::RFC3339, $item['time'])),
207
                'temperature' => [
208
                    'current' => $item['temperature'],
209
                    'apparent' => $item['apparentTemperature']
210
                ],
211
                'wind' => [
212
                    'speed' => $item['windSpeed'],
213
                    'degree' => $item['windBearing'],
214
                ],
215
                'precipitation' => [
216
                    'intensity' => $item['precipIntensity'],
217
                    'probability' => $item['precipProbability'] * 100,
218
                    'type' => $precipType,
219
                ],
220
                'humidity' => [
221
                    'humidity' => $item['humidity']
222
                ],
223
                'icon' => $item['icon']
224
            ];
225
        }
226
227
        $hourly = new Hourly();
228
        $hourly->setData([
229
            'summary' => $result['summary'],
230
            'hours' => $hours
231
        ]);
232
233
        return $hourly;
234
    }
235
236
    /**
237
     * @param Point $point
238
     *
239
     * @internal
240
     * @return string
241
     */
242
    protected function getCacheKeyHourly(Point $point)
243
    {
244
        return 'weather.fc.io-hourly-' . md5(serialize([$this->getLang(), $this->getUnits(), $point->getKey()]));
245
    }
246
247
    /**
248
     *
249
     * @internal
250
     * @return \DateTime
251
     */
252
    protected function getCacheExpirationHourly()
253
    {
254
        return $this->expiration;
255
    }
256
}
257