Completed
Push — master ( fedfa0...4d6eb0 )
by Yannick
05:25
created

METAR::addMETARCycle()   F

Complexity

Conditions 15
Paths 304

Size

Total Lines 33
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 23
nc 304
nop 0
dl 0
loc 33
rs 3.7313
c 0
b 0
f 0

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
require_once(dirname(__FILE__).'/settings.php');
3
require_once(dirname(__FILE__).'/class.Connection.php');
4
require_once(dirname(__FILE__).'/class.Common.php');
5
6
class METAR {
7
	public $db;
8
	
9
	protected $texts = Array(
10
	    'MI' => 'Shallow',
11
	    'PR' => 'Partial',
12
	    'BC' => 'Low drifting',
13
	    'BL' => 'Blowing',
14
	    'SH' => 'Showers',
15
	    'TS' => 'Thunderstorm',
16
	    'FZ' => 'Freezing',
17
	    'DZ' => 'Drizzle',
18
	    'RA' => 'Rain',
19
	    'SN' => 'Snow',
20
	    'SG' => 'Snow Grains',
21
	    'IC' => 'Ice crystals',
22
	    'PL' => 'Ice pellets',
23
	    'GR' => 'Hail',
24
	    'GS' => 'Small hail',
25
	    'UP' => 'Unknown',
26
	    'BR' => 'Mist',
27
	    'FG' => 'Fog',
28
	    'FU' => 'Smoke',
29
	    'VA' => 'Volcanic ash',
30
	    'DU' => 'Widespread dust',
31
	    'SA' => 'Sand',
32
	    'HZ' => 'Haze',
33
	    'PY' => 'Spray',
34
	    'PO' => 'Well developed dust / sand whirls',
35
	    'SQ' => 'Squalls',
36
	    'FC' => 'Funnel clouds inc tornadoes or waterspouts',
37
	    'SS' => 'Sandstorm',
38
	    'DS' => 'Duststorm'
39
	);
40
	
41
	public function __construct($dbc = null) {
42
                $Connection = new Connection($dbc);
43
                $this->db = $Connection->db;
44
        }
45
46
       public static function check_last_update() {
47
    		global $globalDBdriver;
48
    		if ($globalDBdriver == 'mysql') {
49
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_metar' AND value > DATE_SUB(DATE(NOW()), INTERVAL 1 HOUR)";
50
		} else {
51
			$query = "SELECT COUNT(*) as nb FROM config WHERE name = 'last_update_metar' AND value::timestamp > CURRENT_TIMESTAMP - INTERVAL '1 HOURS'";
52
		}
53
                try {
54
                        $Connection = new Connection();
55
                        $sth = $Connection->db->prepare($query);
56
                        $sth->execute();
57
                } catch(PDOException $e) {
58
                        return "error : ".$e->getMessage();
59
                }
60
                $row = $sth->fetch(PDO::FETCH_ASSOC);
61
                if ($row['nb'] > 0) return false;
62
                else return true;
63
        }
64
65
        public static function insert_last_update() {
66
                $query = "DELETE FROM config WHERE name = 'last_update_metar';
67
                        INSERT INTO config (name,value) VALUES ('last_update_metar',NOW());";
68
                try {
69
                        $Connection = new Connection();
70
                        $sth = $Connection->db->prepare($query);
71
                        $sth->execute();
72
                } catch(PDOException $e) {
73
                        return "error : ".$e->getMessage();
74
                }
75
        }
76
77
78
        
79
        public function parse($data) {
80
    		//$data = str_replace(array('\n','\r','\r','\n'),'',$data);
81
    		$codes = implode('|', array_keys($this->texts));
82
    		$regWeather = '#^(\+|\-|VC)?(' . $codes . ')(' . $codes . ')?$#';
83
    		//$pieces = explode(' ',$data);
84
    		$pieces = preg_split('/\s/',$data);
85
    		$pos = 0;
86
    		if ($pieces[0] == 'METAR') $pos++;
87
    		elseif ($pieces[0] == 'SPECI') $pos++;
88
    		if (strlen($pieces[$pos]) != 4) $pos++;
89
    		$result = array();
90
    		$result['location'] = $pieces[$pos];
91
    		$pos++;
92
    		$result['dayofmonth'] = substr($pieces[$pos],0,2);
93
    		$result['time'] = substr($pieces[$pos],2,4);
94
    		$c = count($pieces);
95
    		for($pos++; $pos < $c; $pos++) {
96
    			$piece = $pieces[$pos];
97
    			if ($piece == 'RMK') break;
98
    			if ($piece == 'AUTO') $result['auto'] = true;
99
    			if ($piece == 'COR') $result['correction'] = true;
100
    			// Wind Speed
101
    			if (preg_match('#(VRB|\d\d\d)(\d\d)(?:G(\d\d))?(KT|MPS|KPH)(?: (\d{1,3})V(\d{1,3}))?$#', $piece, $matches)) {
102
    				$result['wind']['direction'] = (float)$matches[1];
103
				$result['wind']['unit'] = $matches[4];
104
    				if ($result['wind']['unit'] == 'KT') $result['wind']['speed'] = round(((float)$matches[2])*0.51444444444,2);
105
    				elseif ($result['wind']['unit'] == 'KPH') $result['wind']['speed'] = round(((float)$matches[2])*1000,2);
106
    				elseif ($result['wind']['unit'] == 'MPS') $result['wind']['speed'] = round(((float)$matches[2]),2);
107
				$result['wind']['gust'] = (float)$matches[3];
108
				$result['wind']['unit'] = $matches[4];
109
				$result['wind']['min_variation'] = array_key_exists(5,$matches) ? $matches[5] : 0;
110
				$result['wind']['max_variation'] = array_key_exists(6,$matches) ? $matches[6] : 0;
111
    			}
112
113
/*    			if (preg_match('#^([0-9]{3})([0-9]{2})(G([0-9]{2}))?(KT|MPS)$#', $piece, $matches)) {
114
    				$result['wind_direction'] = (float)$matches[1];
115
    				if ($matches[5] == 'KT') {
116
    					$result['speed'] = round(((float)$matches[2])*0.51444444444,2);
117
    				} elseif ($matches[5] == 'KPH') {
118
    					$result['speed'] = round(((float)$matches[2])*1000,2);
119
    				} elseif ($matches[5] == 'MPS') {
120
    					$result['speed'] = round(((float)$matches[2]),2);
121
    				}
122
    				if ($matches[3]) {
123
    				    $result['gust'] = $matches[4];
124
    				    $result['gust_format'] = $matches[5];
125
    				}
126
    			}
127
    			*/
128
    			// Temperature
129
    			if (preg_match('#^(M?[0-9]{2,})/(M?[0-9]{2,})$#', $piece, $matches)) {
130
    				$temp = (float)$matches[1];
131
				if ($matches[1]{0} == 'M') {
132
					$temp = ((float)substr($matches[1], 1)) * -1;
133
				}
134
    				$result['temperature'] = $temp;
135
    				$dew = (float)$matches[2];
136
				if ($matches[2]{0} == 'M') {
137
					$dew = ((float)substr($matches[2], 1)) * -1;
138
				}
139
				$result['dew'] = $dew;
140
    			}
141
    			// QNH
142
    			if (preg_match('#^(A|Q)([0-9]{4})$#', $piece, $matches)) {
143
    			// #^(Q|A)(////|[0-9]{4})( )#
144
    				if ($matches[1] == 'Q') {
145
    					// hPa
146
    					$result['QNH'] = $matches[2];
147
    				} else {
148
    					// inHg
149
    					$result['QNH'] = round(($matches[2] / 100)*33.86389,2);
150
				}
151
    				/*
152
    				$result['QNH'] = $matches[1] == 'Q' ? $matches[2] : ($matches[2] / 100);
153
    				$result['QNH_format'] = $matches[1] == 'Q' ? 'hPa' : 'inHg';
154
    				*/
155
    			}
156
                     /*
157
    			// Wind Direction
158
    			if (preg_match('#^([0-9]{3})V([0-9]{3})$#', $piece, $matches)) {
159
    				$result['wind_direction'] = $matches[1];
160
    				$result['wind_direction_other'] = $matches[2];
161
    			}
162
    			// Wind Speed Variable
163
    			if (preg_match('#^VRB([0-9]{2})KT$#', $piece, $matches)) {
164
    				$result['speed_variable'] = $matches[1];
165
    			}
166
    			*/
167
    			// Visibility
168
    			if (preg_match('#^([0-9]{4})|(([0-9]{1,4})SM)$#', $piece, $matches)) {
169
    				if (isset($matches[3]) && strlen($matches[3]) > 0) {
170
					$result['visibility'] = (float)$matches[3] * 1609.34;
171
				} else {
172
					if ($matches[1] == '9999') {
173
						$result['visibility'] = '> 10000';
174
					} else {
175
						$result['visibility'] = (float)$matches[1];
176
					}
177
				}
178
				if (preg_match('#^CAVOK$#', $piece, $matches)) {
179
					$result['visibility'] = '> 10000';
180
					$result['weather'] = "CAVOK";
181
				}
182
    			}
183
    			// Cloud Coverage
184
    			if (preg_match('#^(SKC|CLR|FEW|SCT|BKN|OVC|VV)([0-9]{3})(CB|TCU|CU|CI)?$#', $piece, $matches)) {
185
    				//$this->addCloudCover($matches[1], ((float)$matches[2]) * 100, isset($matches[3]) ? $matches[3] : '');
186
    				$type = $matches[1];
187
    				$cloud = array();
188
    				if ($type == 'SKC') $cloud['type'] = 'No cloud/Sky clear';
189
    				elseif ($type == 'CLR') $cloud['type'] = 'No cloud below 12,000ft (3700m)';
190
    				elseif ($type == 'NSC') $cloud['type'] = 'No significant cloud';
191
    				elseif ($type == 'FEW') $cloud['type'] = 'Few';
192
    				elseif ($type == 'SCT') $cloud['type'] = 'Scattered';
193
    				elseif ($type == 'BKN') $cloud['type'] = 'Broken';
194
    				elseif ($type == 'OVC') $cloud['type'] = 'Overcast/Full cloud coverage';
195
    				elseif ($type == 'VV') $cloud['type'] = 'Vertical visibility';
196
    				$cloud['type_code'] = $type;
197
    				$cloud['level'] = round(((float)$matches[2]) * 100 * 0.3048);
198
    				$cloud['significant'] = isset($matches[3]) ? $matches[3] : '';
199
    				$result['cloud'][] = $cloud;
200
    			}
201
    			// RVR
202
    			 if (preg_match('#^(R.+)/([M|P])?(\d{4})(?:V(\d+)|[UDN])?(FT)?$#', $piece, $matches)) {
203
    				$rvr = array();
204
				$rvr['runway'] = $matches[1];
205
				$rvr['assessment'] = $matches[2];
206
				$rvr['rvr'] = $matches[3];
207
				$rvr['rvr_max'] = array_key_exists(4,$matches) ? $matches[4] : 0;
208
				$rvr['unit'] = array_key_exists(5,$matches) ? $matches[5] : '';
209
				$result['RVR'] = $rvr;
210
			}
211
    			
212
    			//if (preg_match('#^(R[A-Z0-9]{2,3})/([0-9]{4})(V([0-9]{4}))?(FT)?$#', $piece, $matches)) {
213
    			if (preg_match('#^R(\d{2}[LRC]?)/([\d/])([\d/])([\d/]{2})([\d/]{2})$#', $piece, $matches)) {
214
    				//print_r($matches);
215
    				// https://github.com/davidmegginson/metar-taf/blob/master/Metar.php
216
    				$result['RVR']['runway'] = $matches[1];
217
        			$result['RVR']['deposits'] = $matches[2];
218
        			$result['RVR']['extent'] = $matches[3];
219
        			$result['RVR']['depth'] = $matches[4];
220
        			$result['RVR']['friction'] = $matches[5];
221
    			}
222
    			if (preg_match('#^(R[A-Z0-9]{2,3})/([0-9]{4})(V([0-9]{4}))?(FT)?$#', $piece, $matches)) {
223
    				//echo $piece;
224
    				//print_r($matches);
225
    				if (isset($matches[5])) $range = array('exact' => (float)$matches[2], 'unit' => $matches[5] ? 'FT' : 'M');
226
    				else $range = array('exact' => (float)$matches[2], 'unit' => 'M');
227
				if (isset($matches[3])) {
228
					$range = Array(
229
					    'from' => (float)$matches[2],
230
					    'to'   => (float)$matches[4],
231
					    'unit' => $matches[5] ? 'FT' : 'M'
232
					);
233
				}
234
				$result['RVR'] = $matches[1];
235
				$result['RVR_range'] = $range;
236
    			}
237
    			// Weather
238
    			if (preg_match($regWeather, $piece, $matches)) {
239
				$text = Array();
240
				switch ($matches[1]) {
241
					case '+':
242
						$text[] = 'Heavy';
243
						break;
244
					case '-':
245
						$text[] = 'Light';
246
						break;
247
					case 'VC':
248
						$text[] = 'Vicinity';
249
						break;
250
					default:
251
						break;
252
				}
253
				if (isset($matches[2])) {
254
					$text[] = $this->texts[$matches[2]];
255
				}
256
				if (isset($matches[3])) {
257
					$text[] = $this->texts[$matches[3]];
258
				}
259
				if (!isset($result['weather'])) $result['weather'] = implode(' ', $text);
260
				else $result['weather'] = $result['weather'].' / '.implode(' ', $text);
261
    			}
262
    		}
263
    		return $result;
264
        
265
        }
266
        
267
	public function getMETAR($icao) {
268
    		global $globalMETARcycle, $globalDBdriver;
269
    		if (isset($globalMETARcycle) && $globalMETARcycle) {
270
            		$query = "SELECT * FROM metar WHERE metar_location = :icao";
271
                } else {
272
            		if ($globalDBdriver == 'mysql') $query = "SELECT * FROM metar WHERE metar_location = :icao AND metar_date >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 10 HOUR) LIMIT 1";
273
            		else $query = "SELECT * FROM metar WHERE metar_location = :icao AND metar_date >= now() AT TIMEZONE 'UTC' - '10 HOUR'->INTERVAL LIMIT 0,1";
274
                }
275
                $query_values = array(':icao' => $icao);
276
                 try {
277
                        $sth = $this->db->prepare($query);
278
                        $sth->execute($query_values);
279
                } catch(PDOException $e) {
280
                        return "error : ".$e->getMessage();
281
                }
282
                $all = $sth->fetchAll(PDO::FETCH_ASSOC);
283
                if ((!isset($globalMETARcycle) || $globalMETARcycle === false) && count($all) == 0) {
284
            		$all = $this->downloadMETAR($icao);
285
                }
286
                return $all;
287
        }
288
289
       public function addMETAR($location,$metar,$date) {
290
		global $globalDBdriver;
291
		$date = date('Y-m-d H:i:s',strtotime($date));
292
		if ($globalDBdriver == 'mysql') {
293
			$query = "INSERT INTO metar (metar_location,metar_date,metar) VALUES (:location,:date,:metar) ON DUPLICATE KEY UPDATE metar_date = :date, metar = :metar";
294
		} else {
295
			$query = "UPDATE metar SET metar_date = :date, metar = metar WHERE metar_location = :location;INSERT INTO metar (metar_location,metar_date,metar) SELECT :location,:date,:metar WHERE NOT EXISTS (SELECT 1 FROM metar WHERE metar_location = :location);";
296
		}
297
                $query_values = array(':location' => $location,':date' => $date,':metar' => $metar);
298
                 try {
299
                        $sth = $this->db->prepare($query);
300
                        $sth->execute($query_values);
301
                } catch(PDOException $e) {
302
                        return "error : ".$e->getMessage();
303
                }
304
        }
305
306
       public function deleteMETAR($id) {
307
                $query = "DELETE FROM metar WHERE id = :id";
308
                $query_values = array(':id' => $id);
309
                 try {
310
                        $sth = $this->db->prepare($query);
311
                        $sth->execute($query_values);
312
                } catch(PDOException $e) {
313
                        return "error : ".$e->getMessage();
314
                }
315
        }
316
       public function deleteAllMETARLocation() {
317
                $query = "DELETE FROM metar";
318
                 try {
319
                        $sth = $this->db->prepare($query);
320
                        $sth->execute();
321
                } catch(PDOException $e) {
322
                        return "error : ".$e->getMessage();
323
                }
324
        }
325
        
326
        public function addMETARCycle() {
327
    		global $globalDebug, $globalIVAO;
328
    		if (isset($globalDebug) && $globalDebug) echo "Downloading METAR cycle...";
329
    		date_default_timezone_set("UTC");
330
    		$Common = new Common();
331
    		if (isset($globalIVAO) && $globalIVAO) {
332
        		$cycle = $Common->getData('http://wx.ivao.aero/metar.php');
333
    		} else {
334
			$cycle = $Common->getData('http://tgftp.nws.noaa.gov/data/observations/metar/cycles/'.date('H').'Z.TXT');
335
    		}
336
    		if (isset($globalDebug) && $globalDebug) echo "Done - Updating DB...";
337
    		$date = '';
338
    		foreach(explode("\n",$cycle) as $line) {
339
    			if (preg_match('#^([0-9]{4})/([0-9]{2})/([0-9]{2}) ([0-9]{2}):([0-9]{2})$#',$line)) {
340
    				//echo "date : ".$line."\n";
341
    				$date = $line;
342
    			} 
343
    			if ($line != '') {
344
    			    //$this->parse($line);
345
    			    //echo $line;
346
    			    if ($date == '') $date = date('Y/m/d H:m');
347
    			    $pos = 0;
348
    			    $pieces = preg_split('/\s/',$line);
349
    			    if ($pieces[0] == 'METAR') $pos++;
350
    			    if (strlen($pieces[$pos]) != 4) $pos++;
351
	        	    $location = $pieces[$pos];
352
	        	    echo $this->addMETAR($location,$line,$date);
353
    			}
354
    			//echo $line."\n";
355
    		}
356
    		if (isset($globalDebug) && $globalDebug) echo "Done\n";
357
        
358
        }
359
        public function downloadMETAR($icao) {
360
    		global $globalMETARurl;
361
    		if ($globalMETARurl == '') return array();
362
    		date_default_timezone_set("UTC");
363
    		$Common = new Common();
364
    		$url = str_replace('{icao}',$icao,$globalMETARurl);
365
    		$cycle = $Common->getData($url);
366
    		$date = '';
367
    		foreach(explode("\n",$cycle) as $line) {
368
    			if (preg_match('#^([0-9]{4})/([0-9]{2})/([0-9]{2}) ([0-9]{2}):([0-9]{2})$#',$line)) {
369
    				//echo "date : ".$line."\n";
370
    				$date = $line;
371
    			} 
372
    			if ($line != '') {
373
    			    //$this->parse($line);
374
    			    //echo $line;
375
    			    if ($date == '') $date = date('Y/m/d H:m');
376
    			    $pos = 0;
377
    			    $pieces = preg_split('/\s/',$line);
378
    			    if ($pieces[0] == 'METAR') $pos++;
379
    			    if (strlen($pieces[$pos]) != 4) $pos++;
380
	        	    $location = $pieces[$pos];
381
	        	    if (strlen($location == 4)) {
382
	        		$this->addMETAR($location,$line,$date);
383
	        		return array('0' => array('metar_date' => $date, 'metar_location' => $location, 'metar' => $line));
384
	        	    } else return array();
385
    			}
386
    			//echo $line."\n";
387
    		}
388
    		return array();
389
        
390
        }
391
}
392
/*
393
$METAR = new METAR();
394
echo $METAR->parse('CYZR 070646Z AUTO VRB02KT 1SM R33/3500VP6000FT/ BR OVC001 M03/M03 A3020 RMK ICG PAST HR SLP233');
395
echo $METAR->parse('CYVQ 070647Z 00000KT 10SM -SN OVC030 M24/M26 A2981 RMK SC8 SLP105');
396
echo $METAR->parse('CYFC 070645Z AUTO 23003KT 5/8SM R09/3500VP6000FT BR FEW180 M01/M01 A3004 RMK SLP173');
397
echo $METAR->parse('ZMUB 070700Z VRB01MPS 6000NW SCT100 M11/M15 Q1013 NOSIG RMK QFE652.8 71 NW MO');
398
echo $METAR->parse('LFLY 070700Z AUTO 00000KT 2800 0500 R34/0600D BCFG NSC 04/03 Q1033');
399
echo $METAR->parse('LFLY 071100Z 0712/0812 15007KT CAVOK PROB30 0800/0806 4000 BR');
400
echo $METAR->parse('LFMU 070700Z AUTO 02005KT 5000 BR BKN012/// BKN018/// BKN030/// ///CB 11/11 Q1032');
401
echo $METAR->parse('METAR LFPO 231027Z AUTO 24004G09MPS 2500 1000NW R32/0400 R08C/0004D +FZRA VCSN //FEW015 17/10 Q1009 REFZRA WS R03');
402
*/
403
404
$METAR = new METAR();
405
$METAR->addMETARCycle();
406
407
/*
408
2015/12/07 12:21
409
TAF LFLY 071100Z 0712/0812 15007KT CAVOK PROB30 0800/0806 4000 BR 
410
      BECMG 0805/0807 0400 FG VV/// 
411
     FM081002 18010KT CAVOK
412
     */
413
414
?>