This repository was archived by the owner on Dec 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAPI.php
67 lines (54 loc) · 2.67 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
<?php
class API {
private static $endpoints = array();
public static function add_endpoint($endpoint) {
self::$endpoints[] = $endpoint;
}
public static function construct_endpoints() {
add_filter('query_vars', function ($query_vars) {
$query_vars[] = 'api';
return $query_vars;
});
foreach (self::$endpoints as $key => $endpoint) {
add_action('init', function () use ($endpoint) {
add_rewrite_rule('api' . $endpoint->get_url_regex(), 'index.php?api=' . $endpoint->get_name(), 'top');
});
add_filter('template_include', function ($template) use ($endpoint) {
global $wp_query;
if (isset( $wp_query->query_vars['api'] ) && !is_page() && !is_single()) {
$wp_query->is_404 = false;
$wp_query->is_archive = true;
$wp_query->is_category = true;
$base_name = str_replace('$matches[1]', '', $endpoint->get_name());
if (strpos($wp_query->query_vars['api'], $base_name) !== false) {
$match = str_replace($base_name, '', $wp_query->query_vars['api']);
header('Content-Type: application/json');
header('Access-Control-Request-Headers: X-Requested-With, accept, content-type');
header('Access-Control-Allow-Methods: GET, POST');
// Disable caching in debug mode
if (WP_DEBUG) {
die($output = json_encode($endpoint->get_output($match)));
}
// If it's a POST request, don't cache anything
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
die(json_encode($endpoint->get_output($match)));
}
$filename = dirname(__FILE__) . '/cache/' . $wp_query->query_vars['api'] . '.json';
// How long the cache for endpoints lasts for in seconds
$cache_ttl = 15;
if (file_exists($filename) && time() - filemtime($filename) < $cache_ttl) {
$output = file_get_contents($filename);
}
else {
$output = json_encode($endpoint->get_output($match));
file_put_contents($filename, $output);
}
die($output);
}
} else {
return $template;
}
});
}
}
}