|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Wordlift\Jsonld; |
|
4
|
|
|
|
|
5
|
|
|
use DateInterval; |
|
6
|
|
|
use DateTime; |
|
7
|
|
|
use DateTimeZone; |
|
8
|
|
|
use WP_REST_Response; |
|
9
|
|
|
|
|
10
|
|
|
class Jsonld_Endpoint { |
|
11
|
|
|
/** |
|
12
|
|
|
* @var Wordlift_Jsonld_Service |
|
13
|
|
|
*/ |
|
14
|
|
|
private $jsonld_service; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Jsonld_Endpoint constructor. |
|
18
|
|
|
* |
|
19
|
|
|
* @param \Wordlift_Jsonld_Service $jsonld_service |
|
20
|
|
|
*/ |
|
21
|
|
|
public function __construct( $jsonld_service ) { |
|
22
|
|
|
|
|
23
|
|
|
// PHP 5.3 compatibility. |
|
24
|
|
|
$that = $this; |
|
25
|
|
|
add_action( 'rest_api_init', function () use ( $that ) { |
|
26
|
|
|
register_rest_route( WL_REST_ROUTE_DEFAULT_NAMESPACE, '/jsonld/(?P<id>\d+)', array( |
|
27
|
|
|
'methods' => 'GET', |
|
28
|
|
|
'callback' => array( $that, 'callback' ), |
|
29
|
|
|
'args' => array( |
|
30
|
|
|
'id' => array( |
|
31
|
|
|
'validate_callback' => function ( $param, $request, $key ) { |
|
|
|
|
|
|
32
|
|
|
return is_numeric( $param ); |
|
33
|
|
|
}, |
|
34
|
|
|
'sanitize_callback' => 'absint', |
|
35
|
|
|
), |
|
36
|
|
|
) |
|
37
|
|
|
) ); |
|
38
|
|
|
} ); |
|
39
|
|
|
|
|
40
|
|
|
$this->jsonld_service = $jsonld_service; |
|
|
|
|
|
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public function callback( $request ) { |
|
44
|
|
|
|
|
45
|
|
|
$post_id = $request['id']; |
|
46
|
|
|
$is_homepage = ( 0 === $post_id ); |
|
47
|
|
|
|
|
48
|
|
|
// Send the generated JSON-LD. |
|
49
|
|
|
$data = $this->jsonld_service->get_jsonld( $is_homepage, $post_id ); |
|
50
|
|
|
$response = new WP_REST_Response( $data ); |
|
51
|
|
|
|
|
52
|
|
|
$cache_in_seconds = 86400; |
|
53
|
|
|
$date_timezone = new DateTimeZone( 'GMT' ); |
|
54
|
|
|
$date_now = new DateTime( 'now', $date_timezone ); |
|
55
|
|
|
$date_interval = new DateInterval( "PT{$cache_in_seconds}S" ); |
|
56
|
|
|
$expires = $date_now->add( $date_interval )->format( 'D, j M Y H:i:s T' ); |
|
57
|
|
|
|
|
58
|
|
|
$response->set_headers( array( |
|
59
|
|
|
'Content-Type' => 'application/ld+json; charset=' . get_option( 'blog_charset' ), |
|
60
|
|
|
'Cache-Control' => "max-age=$cache_in_seconds", |
|
61
|
|
|
'Expires' => $expires |
|
62
|
|
|
) ); |
|
63
|
|
|
|
|
64
|
|
|
return $response; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
} |
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.