Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- const WORLD_URL_REGEX = '/(?P<country>[A-Za-z]+)(?P<worldId>\d+)/';
- const STOCKS_REGEX = '/(?P<id>\d+)\s+(?P<name>.+?)\s+(?P<value>\d+)/';
- const SECOND_REFRESH = 3600;
- require_once('Option.php');
- function arrayGet($array, $key)
- {
- return COption::of(isset($array[$key]) ? $array[$key] : null);
- }
- function getWorldInfo($worldUrl)
- {
- return (preg_match_all(WORLD_URL_REGEX, $worldUrl, $matches, PREG_SET_ORDER, 0) == true ? COption::of([ 'country' => $matches[0]['country'], 'id' => intval($matches[0]['worldId']) ]) : COption::of(null));
- }
- function validateWorldInfo($worldInfo)
- {
- $id = $worldInfo['id'];
- switch($worldInfo['country'])
- {
- case 'de': return (1 <= $id && $id <= 14);
- case 'uk': return (1 <= $id && $id <= 1);
- default: return False;
- }
- }
- function getUrl($worldInfo)
- {
- function getUrlForCountry($country)
- {
- switch($country)
- {
- case 'uk': return 'http://world%d.freewar.com/freewar/';
- case 'de': return 'http://welt%d.freewar.de/freewar/';
- }
- }
- function getUrl_($country, $id)
- {
- return sprintf(getUrlForCountry($country), $id);
- }
- return getUrl_($worldInfo['country'], $worldInfo['id']);
- }
- function parseStocksFile($content)
- {
- preg_match_all(STOCKS_REGEX, $content, $matches, PREG_SET_ORDER, 0);
- $stocks = array();
- foreach($matches as $match)
- {
- $id = intval($match['id']);
- $name = $match['name'];
- $value = intval($match['value']);
- $stocks[$id] = array('name' => $name, 'value' => $value);
- }
- return $stocks;
- }
- $res = arrayGet($_GET, 'world')->flatMap(getWorldInfo)->filter(validateWorldInfo)->flatMap(function($info)
- {
- $file = sprintf('freewar/sotcks_%s%d.json', $info['country'], $info['id']);
- if(!file_exists($file) || time() - filemtime($file) >= SECOND_REFRESH) // print out old file
- {
- $url = getUrl($info);
- if(($urlContent = @file_get_contents($url . 'list_stocks.php')) != false)
- {
- $stocks = parseStocksFile($urlContent);
- file_put_contents($file, json_encode([ 'status' => 'success', 'data' => $stocks ], JSON_PRETTY_PRINT));
- }
- else
- {
- return COption::of(NULL);
- }
- }
- return COption::of(file_get_contents($file));
- })->getOrElse(json_encode([ 'status' => 'error', 'message' => 'an error occured' ], JSON_PRETTY_PRINT));
- header('Content-Type: application/json');
- echo $res;
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement