This repository has been archived by the owner on Nov 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.php
75 lines (63 loc) · 1.53 KB
/
api.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
66
67
68
69
70
71
72
73
74
75
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
/**
* Declarations
*/
$validCommands = [
'search',
'location'
];
$command = isset($_GET['command']) ? $_GET['command'] : null;
$baseUrl = 'https://www.metaweather.com/api/location/';
/**
* Functions
*/
function quitWithResponse($output, $code = 200) {
header('Content-Type: text/json');
http_response_code($code);
echo $output;
exit;
}
function quitWithJsonResponse($output, $code = 200) {
return quitWithResponse(
json_encode($output),
$code
);
}
function mirrorToEndpoint($uri) {
global $baseUrl;
$response = @file_get_contents($baseUrl . $uri);
if ( $response ) {
return quitWithResponse($response);
}
quitWithJsonResponse(['error' => 'Not found'], 404);
}
function requireParameters($params) {
foreach ($params as $param) {
if (!isset($_GET[$param])) {
quitWithJsonResponse(['error' => $param . ' is missing']);
}
}
}
/**
* Commands
*/
function search() {
requireParameters(['keyword']);
return mirrorToEndpoint('search/?query=' . $_GET['keyword']);
}
function location() {
requireParameters(['woeid']);
return mirrorToEndpoint($_GET['woeid']);
}
/**
* Execution
*/
if (is_null($command) or !in_array($command, $validCommands)) {
quitWithJsonResponse(['error' => 'Invalid command'], 422);
}
$command();