PathInfo.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\Framework\App\Request;
  8. /**
  9. * Computes path info and query string from request
  10. */
  11. class PathInfo
  12. {
  13. /**
  14. * Get path info using from the request URI and base URL
  15. *
  16. * @param string $requestUri
  17. * @param string $baseUrl
  18. * @return string
  19. */
  20. public function getPathInfo(string $requestUri, string $baseUrl) : string
  21. {
  22. if ($requestUri === '/') {
  23. return '';
  24. }
  25. $requestUri = $this->removeRepeatedSlashes($requestUri);
  26. $parsedRequestUri = explode('?', $requestUri, 2);
  27. $pathInfo = (string)substr(current($parsedRequestUri), (int)strlen($baseUrl));
  28. if ($this->isNoRouteUri($baseUrl, $pathInfo)) {
  29. $pathInfo = \Magento\Framework\App\Router\Base::NO_ROUTE;
  30. }
  31. return $pathInfo;
  32. }
  33. /**
  34. * Get query string using from the request URI
  35. *
  36. * @param string $requestUri
  37. * @return string
  38. */
  39. public function getQueryString(string $requestUri) : string
  40. {
  41. $requestUri = $this->removeRepeatedSlashes($requestUri);
  42. $parsedRequestUri = explode('?', $requestUri, 2);
  43. $queryString = !isset($parsedRequestUri[1]) ? '' : '?' . $parsedRequestUri[1];
  44. return $queryString;
  45. }
  46. /**
  47. * Remove repeated slashes from the start of the path.
  48. *
  49. * @param string $pathInfo
  50. * @return string
  51. */
  52. private function removeRepeatedSlashes($pathInfo) : string
  53. {
  54. $firstChar = (string)substr($pathInfo, 0, 1);
  55. if ($firstChar == '/') {
  56. $pathInfo = '/' . ltrim($pathInfo, '/');
  57. }
  58. return $pathInfo;
  59. }
  60. /**
  61. * Check is URI should be marked as no route, helps route to 404 URI like `index.phpadmin`.
  62. *
  63. * @param string $baseUrl
  64. * @param string $pathInfo
  65. * @return bool
  66. */
  67. private function isNoRouteUri($baseUrl, $pathInfo) : bool
  68. {
  69. $firstChar = (string)substr($pathInfo, 0, 1);
  70. return $baseUrl !== '' && !in_array($firstChar, ['/', '']);
  71. }
  72. }