Rest.php
98 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WPStaging\Framework\Rest; |
| 4 | |
| 5 | use WPStaging\Framework\Utils\Sanitize; |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | class Rest |
| 15 | { |
| 16 | |
| 17 | const WPSTG_ROUTE_NAMESPACE_V1 = 'wpstg/v1'; |
| 18 | |
| 19 | |
| 20 | const REQUEST_TIMEOUT = 30; |
| 21 | |
| 22 | |
| 23 | private $sanitize; |
| 24 | |
| 25 | public function __construct(Sanitize $sanitize) |
| 26 | { |
| 27 | $this->sanitize = $sanitize; |
| 28 | } |
| 29 | |
| 30 | |
| 31 | public function isRestUrl() |
| 32 | { |
| 33 | |
| 34 | if (empty($_SERVER['REQUEST_URI'])) { |
| 35 | return false; |
| 36 | } |
| 37 | |
| 38 | if ($this->hasRestRouteQueryParam()) { |
| 39 | return true; |
| 40 | } |
| 41 | |
| 42 | $requestUri = $this->sanitize->sanitizeUrl($_SERVER['REQUEST_URI']); |
| 43 | |
| 44 | |
| 45 | if (!function_exists('rest_url')) { |
| 46 | return false; |
| 47 | } |
| 48 | |
| 49 | $requestPath = trim($requestUri, '/'); |
| 50 | |
| 51 | $baseRestURL = get_rest_url(get_current_blog_id(), '/'); |
| 52 | $restPath = $this->getApiRequestURI($baseRestURL); |
| 53 | |
| 54 | |
| 55 | if (empty($restPath)) { |
| 56 | return false; |
| 57 | } |
| 58 | |
| 59 | return strpos($requestPath, $restPath) === 0; |
| 60 | } |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | private function hasRestRouteQueryParam(): bool |
| 75 | { |
| 76 | if (!array_key_exists('rest_route', $_GET) || !is_string($_GET['rest_route'])) { |
| 77 | return false; |
| 78 | } |
| 79 | |
| 80 | return $_GET['rest_route'] !== '' && $_GET['rest_route'] !== '0'; |
| 81 | } |
| 82 | |
| 83 | private function getApiRequestURI($url) |
| 84 | { |
| 85 | if (empty($url)) { |
| 86 | return ''; |
| 87 | } |
| 88 | |
| 89 | $path = parse_url($url, PHP_URL_PATH); |
| 90 | $path = empty($path) ? '' : trim($path, '/'); |
| 91 | |
| 92 | $query = parse_url($url, PHP_URL_QUERY); |
| 93 | $query = empty($query) ? '' : trim($query, '/'); |
| 94 | |
| 95 | return $query === '' ? $path : $path . '?' . $query; |
| 96 | } |
| 97 | } |
| 98 |