CURIE.php
58 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\API\REST\V3\Support; |
| 4 | |
| 5 | use Give\Framework\Exceptions\Primitives\Exception; |
| 6 | |
| 7 | /** |
| 8 | * @since 4.4.0 |
| 9 | * |
| 10 | * WordPress version 4.5 introduced support for Compact URIs, or CURIEs. This makes it possible to |
| 11 | * reference links by a much simpler identifier than the full URL which could easily be quite lengthy. |
| 12 | * |
| 13 | * This will convert link URLs from https://api.mypluginurl.com/my_link` to my_plugin:my_linkin the API response. |
| 14 | * The full URL must still be used when adding links using WP_REST_Response::add_link() `. |
| 15 | */ |
| 16 | class CURIE |
| 17 | { |
| 18 | /** |
| 19 | * @var string |
| 20 | */ |
| 21 | private static $baseUrl = 'https://relations.givewp.com/'; |
| 22 | |
| 23 | /** |
| 24 | * @since 4.4.0 |
| 25 | * |
| 26 | * @see https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/#registering-a-curie |
| 27 | */ |
| 28 | public function registerCURIE($curies): array |
| 29 | { |
| 30 | $curies[] = [ |
| 31 | 'name' => 'givewp', |
| 32 | 'href' => trailingslashit(self::$baseUrl) . '{rel}', |
| 33 | 'templated' => true, |
| 34 | ]; |
| 35 | |
| 36 | return $curies; |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * @since 4.4.0 |
| 41 | * |
| 42 | * To use the $response->add_link() with a custom link, you need to use a URI that is under your control, so GiveWP |
| 43 | * uses it to generate the URL, which is transformed into givewp:$rel when generating the response by using a CURIE. |
| 44 | * |
| 45 | * @see https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/#adding-links-to-the-api-response |
| 46 | * |
| 47 | * @throws Exception |
| 48 | */ |
| 49 | public static function relationUrl(string $rel): string |
| 50 | { |
| 51 | if (wp_http_validate_url($rel)) { |
| 52 | throw new Exception(__('The $rel value should be a unique identifier, not a full URL.', 'give')); |
| 53 | } |
| 54 | |
| 55 | return trailingslashit(self::$baseUrl) . $rel; |
| 56 | } |
| 57 | } |
| 58 |