-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmod_rate.php
65 lines (54 loc) · 2.09 KB
/
mod_rate.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
/**
* Class modRate
* Convert currency rates
*
* TODO merge with mod_coin.php or better, find an API that also supports digital currencies
*
* @Version: 0.1
* @Author: rab1t
* @Since: 30-5-2017
*/
class modRate {
const DEFAULT_FROM = 'EUR';
const SECOND_FROM = 'USD';
private static function getCurrencies() {
$jsonResponse = file_get_contents('http://api.fixer.io/latest');
if(!$result = json_decode($jsonResponse, true)) {
return 'Er ging iets fout.';
}
// assuming 'rates' is set
return implode(', ', array_keys($result['rates']));
}
public static function rate($args = '') {
// get params as array and remove empty ones
$params = array_filter(explode(' ', trim(strtoupper($args))));
$times = 1;
// no params
if(count($params) < 1) {
return '[RATE] !rate [aantal] [van] naar'. PHP_EOL .
'[RATE] Beschikbare valuta: '. self::getCurrencies();
} // 1 param
elseif(count($params) === 1) {
$fromCurrency = $params[0] === self::DEFAULT_FROM ? self::SECOND_FROM : self::DEFAULT_FROM;
} // first param is numeric
elseif(is_numeric($params[0])) {
$times = (int) array_shift($params);
$fromCurrency = array_shift($params);
} // multiple string params
else {
$fromCurrency = array_shift($params);
}
$jsonResponse = file_get_contents('http://api.fixer.io/latest?base=' . $fromCurrency . '&symbols=' . urlencode(implode(',', $params)));
if(!$result = json_decode($jsonResponse, true)) {
return '[RATE] Er ging iets fout.';
}
$return = [];
//assuming 'rates' is set
foreach($result['rates'] as $curr => $rate) {
// format the currency/rate and add it to an array so we can return it
$return[] = $times . ' ' . $fromCurrency . ' = ' . number_format($times * $rate, 2, ',', '.') . ' ' . $curr;
}
return '[RATE] ' . (implode(', ', $return) ?: 'Valuta niet gevonden');
}
}