UrlRewrite.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\UrlRewrite\Helper;
  7. class UrlRewrite extends \Magento\Framework\App\Helper\AbstractHelper
  8. {
  9. /**
  10. * Validation error constants
  11. */
  12. const VERR_MANYSLASHES = 1;
  13. // Too many slashes in a row of request path, e.g. '///foo//'
  14. const VERR_ANCHOR = 2;
  15. // Anchor is not supported in request path, e.g. 'foo#bar'
  16. /**
  17. * Core func to validate request path
  18. * If something is wrong with a path it throws localized error message and error code,
  19. * that can be checked to by wrapper func to alternate error message
  20. *
  21. * @param string $requestPath
  22. * @return bool
  23. * @throws \Exception
  24. */
  25. protected function _validateRequestPath($requestPath)
  26. {
  27. if (strpos($requestPath, '//') !== false) {
  28. throw new \Exception(
  29. __('Do not use two or more consecutive slashes in the request path.'),
  30. self::VERR_MANYSLASHES
  31. );
  32. }
  33. if (strpos($requestPath, '#') !== false) {
  34. throw new \Exception(__('Anchor symbol (#) is not supported in request path.'), self::VERR_ANCHOR);
  35. }
  36. return true;
  37. }
  38. /**
  39. * Validates request path
  40. * Either returns TRUE (success) or throws error (validation failed)
  41. *
  42. * @param string $requestPath
  43. * @throws \Magento\Framework\Exception\LocalizedException
  44. * @return bool
  45. */
  46. public function validateRequestPath($requestPath)
  47. {
  48. try {
  49. $this->_validateRequestPath($requestPath);
  50. } catch (\Exception $e) {
  51. throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()));
  52. }
  53. return true;
  54. }
  55. /**
  56. * Validates suffix for url rewrites to inform user about errors in it
  57. * Either returns TRUE (success) or throws error (validation failed)
  58. *
  59. * @param string $suffix
  60. * @throws \Magento\Framework\Exception\LocalizedException
  61. * @return bool
  62. */
  63. public function validateSuffix($suffix)
  64. {
  65. try {
  66. // Suffix itself must be a valid request path
  67. $this->_validateRequestPath($suffix);
  68. } catch (\Exception $e) {
  69. // Make message saying about suffix, not request path
  70. switch ($e->getCode()) {
  71. case self::VERR_MANYSLASHES:
  72. throw new \Magento\Framework\Exception\LocalizedException(
  73. __('Do not use two or more consecutive slashes in the url rewrite suffix.')
  74. );
  75. case self::VERR_ANCHOR:
  76. throw new \Magento\Framework\Exception\LocalizedException(
  77. __('Anchor symbol (#) is not supported in url rewrite suffix.')
  78. );
  79. }
  80. }
  81. return true;
  82. }
  83. }