4 * This file is part of the Behat.
5 * (c) Konstantin Kudryashov <ever.zet@gmail.com>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
11 namespace Behat\Behat\Definition\Pattern\Policy;
13 use Behat\Behat\Definition\Exception\InvalidPatternException;
14 use Behat\Behat\Definition\Pattern\Pattern;
15 use Behat\Transliterator\Transliterator;
18 * Defines a way to handle regex patterns.
20 * @author Konstantin Kudryashov <ever.zet@gmail.com>
22 final class RegexPatternPolicy implements PatternPolicy
27 private static $replacePatterns = array(
28 "/(?<=\W|^)\\\'(?:((?!\\').)*)\\\'(?=\W|$)/" => "'([^']*)'", // Single quoted strings
29 '/(?<=\W|^)\"(?:[^\"]*)\"(?=\W|$)/' => "\"([^\"]*)\"", // Double quoted strings
30 '/(?<=\W|^)(\d+)(?=\W|$)/' => "(\\d+)", // Numbers
36 public function supportsPatternType($type)
38 return 'regex' === $type;
44 public function generatePattern($stepText)
46 $canonicalText = $this->generateCanonicalText($stepText);
47 $stepRegex = $this->generateRegex($stepText);
48 $placeholderCount = $this->countPlaceholders($stepText, $stepRegex);
50 return new Pattern($canonicalText, '/^' . $stepRegex . '$/', $placeholderCount);
56 public function supportsPattern($pattern)
58 return (bool) preg_match('/^(?:\\{.*\\}|([~\\/#`]).*\1)[imsxADSUXJu]*$/s', $pattern);
64 public function transformPatternToRegex($pattern)
66 if (false === @preg_match($pattern, 'anything')) {
67 $error = error_get_last();
68 $errorMessage = isset($error['message']) ? $error['message'] : '';
70 throw new InvalidPatternException(sprintf('The regex `%s` is invalid: %s', $pattern, $errorMessage));
77 * Generates regex from step text.
79 * @param string $stepText
83 private function generateRegex($stepText)
86 array_keys(self::$replacePatterns),
87 array_values(self::$replacePatterns),
88 $this->escapeStepText($stepText)
93 * Generates canonical text for step text.
95 * @param string $stepText
99 private function generateCanonicalText($stepText)
101 $canonicalText = preg_replace(array_keys(self::$replacePatterns), '', $stepText);
102 $canonicalText = Transliterator::transliterate($canonicalText, ' ');
103 $canonicalText = preg_replace('/[^a-zA-Z\_\ ]/', '', $canonicalText);
104 $canonicalText = str_replace(' ', '', ucwords($canonicalText));
106 return $canonicalText;
110 * Counts regex placeholders using provided text.
112 * @param string $stepText
113 * @param string $stepRegex
117 private function countPlaceholders($stepText, $stepRegex)
119 preg_match('/^' . $stepRegex . '$/', $stepText, $matches);
121 return count($matches) ? count($matches) - 1 : 0;
125 * Returns escaped step text.
127 * @param string $stepText
131 private function escapeStepText($stepText)
133 return preg_replace('/([\/\[\]\(\)\\\^\$\.\|\?\*\+\'])/', '\\\\$1', $stepText);