Rest.php
78 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WPStaging\Framework\Rest; |
| 4 | |
| 5 | use WPStaging\Framework\Utils\Sanitize; |
| 6 | |
| 7 | /** |
| 8 | * Class Rest |
| 9 | * |
| 10 | * @package WPStaging\Framework\Rest |
| 11 | * |
| 12 | * @todo merge into WPAdapter class? |
| 13 | */ |
| 14 | class Rest |
| 15 | { |
| 16 | /** @var Sanitize */ |
| 17 | private $sanitize; |
| 18 | |
| 19 | public function __construct(Sanitize $sanitize) |
| 20 | { |
| 21 | $this->sanitize = $sanitize; |
| 22 | } |
| 23 | |
| 24 | // Is Rest URL |
| 25 | public function isRestUrl() |
| 26 | { |
| 27 | // Early bail if uri is empty |
| 28 | if (empty($_SERVER['REQUEST_URI'])) { |
| 29 | return false; |
| 30 | } |
| 31 | |
| 32 | $requestPath = trim($this->sanitize->sanitizeUrl($_SERVER['REQUEST_URI']), '/'); |
| 33 | |
| 34 | $url = trailingslashit(get_home_url(get_current_blog_id(), '')); |
| 35 | // nginx only allows HTTP/1.0 methods when redirecting from / to /index.php. |
| 36 | // To work around this, we manually add index.php to the URL, avoiding the redirect. |
| 37 | if ('index.php/' !== substr($url, -10)) { |
| 38 | $url .= 'index.php'; |
| 39 | } |
| 40 | |
| 41 | $url = add_query_arg('rest_route', '/', $url); |
| 42 | $restPath = $this->getApiRequestURI($url); |
| 43 | if (!empty($restPath) && strpos($requestPath, $restPath) === 0) { |
| 44 | return true; |
| 45 | } |
| 46 | |
| 47 | // Early bail rest url function not exists |
| 48 | if (!function_exists('rest_url')) { |
| 49 | return false; |
| 50 | } |
| 51 | |
| 52 | $baseRestURL = get_rest_url(get_current_blog_id(), '/'); |
| 53 | $restPath = $this->getApiRequestURI($baseRestURL); |
| 54 | |
| 55 | // Early bail if rest path is empty |
| 56 | if (empty($restPath)) { |
| 57 | return false; |
| 58 | } |
| 59 | |
| 60 | return strpos($requestPath, $restPath) === 0; |
| 61 | } |
| 62 | |
| 63 | private function getApiRequestURI($url) |
| 64 | { |
| 65 | if (empty($url)) { |
| 66 | return ''; |
| 67 | } |
| 68 | |
| 69 | $path = parse_url($url, PHP_URL_PATH); |
| 70 | $path = empty($path) ? '' : trim($path, '/'); |
| 71 | |
| 72 | $query = parse_url($url, PHP_URL_QUERY); |
| 73 | $query = empty($query) ? '' : trim($query, '/'); |
| 74 | |
| 75 | return $query === '' ? $path : $path . '?' . $query; |
| 76 | } |
| 77 | } |
| 78 |