3 namespace Drupal\Core\Path;
5 use Drupal\Core\Config\ConfigFactoryInterface;
6 use Drupal\Core\Routing\RouteMatchInterface;
10 * Provides a path matcher.
12 class PathMatcher implements PathMatcherInterface {
15 * Whether the current page is the front page.
19 protected $isCurrentFrontPage;
22 * The default front page.
29 * The cache of regular expressions.
36 * The config factory service.
38 * @var \Drupal\Core\Config\ConfigFactoryInterface
40 protected $configFactory;
43 * The current route match.
45 * @var \Drupal\Core\Routing\RouteMatchInterface
47 protected $routeMatch;
50 * Creates a new PathMatcher.
52 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
54 * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
55 * The current route match.
57 public function __construct(ConfigFactoryInterface $config_factory, RouteMatchInterface $route_match) {
58 $this->configFactory = $config_factory;
59 $this->routeMatch = $route_match;
65 public function matchPath($path, $patterns) {
67 if (!isset($this->regexes[$patterns])) {
68 // Convert path settings to a regular expression.
70 // Replace newlines with a logical 'or'.
74 // Quote <front> keyword.
75 '/(^|\|)\\\\<front\\\\>($|\|)/',
80 '\1' . preg_quote($this->getFrontPagePath(), '/') . '\2',
82 $patterns_quoted = preg_quote($patterns, '/');
83 $this->regexes[$patterns] = '/^(' . preg_replace($to_replace, $replacements, $patterns_quoted) . ')$/';
85 return (bool) preg_match($this->regexes[$patterns], $path);
91 public function isFrontPage() {
92 // Cache the result as this is called often.
93 if (!isset($this->isCurrentFrontPage)) {
94 $this->isCurrentFrontPage = FALSE;
95 // Ensure that the code can also be executed when there is no active
96 // route match, like on exception responses.
97 if ($this->routeMatch->getRouteName()) {
98 $url = Url::fromRouteMatch($this->routeMatch);
99 $this->isCurrentFrontPage = ($url->getRouteName() && '/' . $url->getInternalPath() === $this->getFrontPagePath());
102 return $this->isCurrentFrontPage;
106 * Gets the current front page path.
109 * The front page path.
111 protected function getFrontPagePath() {
112 // Lazy-load front page config.
113 if (!isset($this->frontPage)) {
114 $this->frontPage = $this->configFactory->get('system.site')
117 return $this->frontPage;