PathPattern.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\View\Helper;
  7. /**
  8. * Path pattern creation helper
  9. */
  10. class PathPattern
  11. {
  12. /**
  13. * Translate pattern with glob syntax into regular expression
  14. *
  15. * @param string $path
  16. * @return string
  17. */
  18. public function translatePatternFromGlob($path)
  19. {
  20. $pattern = str_replace(['\\?', '\\*'], ['[^/]', '[^/]*'], preg_quote($path));
  21. $pattern = $this->translateGroupsFromGlob($pattern);
  22. $pattern = $this->translateCharacterGroupsFromGlob($pattern);
  23. return $pattern;
  24. }
  25. /**
  26. * Translate groups from escaped glob syntax into regular expression
  27. *
  28. * Example: filename\.\{php,css,js\} -> filename\.(?:php|css|js)
  29. * Transformations:
  30. * 1. \{ -> (?:
  31. * 2. , -> |
  32. * 3. \} -> )
  33. *
  34. * @param string $pattern
  35. * @return string
  36. */
  37. protected function translateGroupsFromGlob($pattern)
  38. {
  39. preg_match_all('~\\\\\\{[^,\\}]+(?:,[^,\\}]*)*\\\\\\}~', $pattern, $matches, PREG_OFFSET_CAPTURE);
  40. for ($index = count($matches[0]) - 1; $index >= 0; $index -= 1) {
  41. list($match, $offset) = $matches[0][$index];
  42. $replacement = substr_replace($match, '(?:', 0, 2);
  43. $replacement = substr_replace($replacement, ')', -2);
  44. $replacement = str_replace(',', '|', $replacement);
  45. $pattern = substr_replace($pattern, $replacement, $offset, strlen($match));
  46. }
  47. return $pattern;
  48. }
  49. /**
  50. * Translate character groups from escaped glob syntax into regular expression
  51. *
  52. * Example: \[\!a\-f\]\.php -> [^a-f]\.php
  53. * Transformations:
  54. * 1. \[ -> [
  55. * 2. \! -> ^
  56. * 3. \- -> -
  57. * 4. \] -> ]
  58. *
  59. * @param string $pattern
  60. * @return string
  61. */
  62. protected function translateCharacterGroupsFromGlob($pattern)
  63. {
  64. preg_match_all('~\\\\\\[(\\\\\\!)?[^\\]]+\\\\\\]~i', $pattern, $matches, PREG_OFFSET_CAPTURE);
  65. for ($index = count($matches[0]) - 1; $index >= 0; $index -= 1) {
  66. list($match, $offset) = $matches[0][$index];
  67. $exclude = !empty($matches[1][$index]);
  68. $replacement = substr_replace($match, '[' . ($exclude ? '^' : ''), 0, $exclude ? 4 : 2);
  69. $replacement = substr_replace($replacement, ']', -2);
  70. $replacement = str_replace('\\-', '-', $replacement);
  71. $pattern = substr_replace($pattern, $replacement, $offset, strlen($match));
  72. }
  73. return $pattern;
  74. }
  75. }