|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Component\HttpKernel\CacheWarmer; |
| 13 | + |
| 14 | +/** |
| 15 | + * Default implementation of the ClassMatcherInterface. |
| 16 | + * |
| 17 | + * This implementation uses single wildcards for any character other than backslashes |
| 18 | + * and double wildcards for any character. |
| 19 | + * |
| 20 | + * @author Titouan Galopin <galopintitouan@gmail.com> |
| 21 | + */ |
| 22 | +class ClassMatcher implements ClassMatcherInterface |
| 23 | +{ |
| 24 | + /** |
| 25 | + * {@inheritdoc} |
| 26 | + */ |
| 27 | + public function match(array $classes, array $patterns) |
| 28 | + { |
| 29 | + $matched = array(); |
| 30 | + |
| 31 | + // Explicit classes declared in the patterns are returned directly |
| 32 | + foreach ($patterns as $key => $pattern) { |
| 33 | + if (substr($pattern, -1) !== '\\' && false === strpos($pattern, '*')) { |
| 34 | + unset($patterns[$key]); |
| 35 | + $matched[] = ltrim($pattern, '\\'); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + // Match patterns with the classes list |
| 40 | + $regexps = $this->patternsToRegexps($patterns); |
| 41 | + |
| 42 | + foreach ($classes as $class) { |
| 43 | + $class = ltrim($class, '\\'); |
| 44 | + |
| 45 | + if ($this->matchAnyRegexp($class, $regexps)) { |
| 46 | + $matched[] = $class; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return $matched; |
| 51 | + } |
| 52 | + |
| 53 | + private function patternsToRegexps($patterns) |
| 54 | + { |
| 55 | + $regexps = array(); |
| 56 | + |
| 57 | + foreach ($patterns as $pattern) { |
| 58 | + // Escape user input |
| 59 | + $regex = preg_quote(ltrim($pattern, '\\')); |
| 60 | + |
| 61 | + // Wildcards * and ** |
| 62 | + $regex = strtr($regex, array('\\*\\*' => '.*?', '\\*' => '[^\\\\]*?')); |
| 63 | + |
| 64 | + // If this class does not end by a slash, anchor the end |
| 65 | + if (substr($regex, -1) !== '\\') { |
| 66 | + $regex .= '$'; |
| 67 | + } |
| 68 | + |
| 69 | + $regexps[] = '{^\\\\'.$regex.'}'; |
| 70 | + } |
| 71 | + |
| 72 | + return $regexps; |
| 73 | + } |
| 74 | + |
| 75 | + private function matchAnyRegexp($class, $regexps) |
| 76 | + { |
| 77 | + $blacklisted = false !== strpos($class, 'Test'); |
| 78 | + |
| 79 | + foreach ($regexps as $regex) { |
| 80 | + if ($blacklisted && false === strpos($regex, 'Test')) { |
| 81 | + continue; |
| 82 | + } |
| 83 | + |
| 84 | + if (preg_match($regex, '\\'.$class)) { |
| 85 | + return true; |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + return false; |
| 90 | + } |
| 91 | +} |
0 commit comments