-
Notifications
You must be signed in to change notification settings - Fork 611
/
TurnipPatternPolicy.php
212 lines (186 loc) · 5.76 KB
/
TurnipPatternPolicy.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
<?php
/*
* This file is part of the Behat.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Behat\Behat\Definition\Pattern\Policy;
use Behat\Behat\Definition\Pattern\Pattern;
use Behat\Behat\Definition\Exception\InvalidPatternException;
use Behat\Transliterator\Transliterator;
/**
* Defines a way to handle turnip patterns.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
final class TurnipPatternPolicy implements PatternPolicy
{
public const TOKEN_REGEX = "[\"']?(?P<%s>(?<=\")[^\"]*(?=\")|(?<=')[^']*(?=')|\-?[\w\.\,]+)['\"]?";
public const PLACEHOLDER_REGEXP = "/\\\:(\w+)/";
public const OPTIONAL_WORD_REGEXP = '/(\s)?\\\\\(([^\\\]+)\\\\\)(\s)?/';
public const ALTERNATIVE_WORD_REGEXP = '/(\w+)\\\\\/(\w+)/';
/**
* @var string[]
*/
private $regexCache = array();
/**
* @var string[]
*/
private static $placeholderPatterns = array(
"/(?<!\w)\"[^\"]+\"(?!\w)/",
"/(?<!\w)'[^']+'(?!\w)/",
"/(?<!\w|\.|\,)\-?\d+(?:[\.\,]\d+)?(?!\w|\.|\,)/"
);
/**
* {@inheritdoc}
*/
public function supportsPatternType($type)
{
return null === $type || 'turnip' === $type;
}
/**
* {@inheritdoc}
*/
public function generatePattern($stepText)
{
$count = 0;
$pattern = $stepText;
foreach (self::$placeholderPatterns as $replacePattern) {
$pattern = preg_replace_callback(
$replacePattern,
function () use (&$count) { return ':arg' . ++$count; },
$pattern
);
}
$pattern = $this->escapeAlternationSyntax($pattern);
$canonicalText = $this->generateCanonicalText($stepText);
return new Pattern($canonicalText, $pattern, $count);
}
/**
* {@inheritdoc}
*/
public function supportsPattern($pattern)
{
return true;
}
/**
* {@inheritdoc}
*/
public function transformPatternToRegex($pattern)
{
if (!isset($this->regexCache[$pattern])) {
$this->regexCache[$pattern] = $this->createTransformedRegex($pattern);
}
return $this->regexCache[$pattern];
}
/**
* @param string $pattern
* @return string
*/
private function createTransformedRegex($pattern)
{
$regex = preg_quote($pattern, '/');
$regex = $this->replaceTokensWithRegexCaptureGroups($regex);
$regex = $this->replaceTurnipOptionalEndingWithRegex($regex);
$regex = $this->replaceTurnipAlternativeWordsWithRegex($regex);
return '/^' . $regex . '$/iu';
}
/**
* Generates canonical text for step text.
*
* @param string $stepText
*
* @return string
*/
private function generateCanonicalText($stepText)
{
$canonicalText = preg_replace(self::$placeholderPatterns, '', $stepText);
$canonicalText = Transliterator::transliterate($canonicalText, ' ');
$canonicalText = preg_replace('/[^a-zA-Z\_\ ]/', '', $canonicalText);
$canonicalText = str_replace(' ', '', ucwords($canonicalText));
return $canonicalText;
}
/**
* Replaces turnip tokens with regex capture groups.
*
* @param string $regex
*
* @return string
*/
private function replaceTokensWithRegexCaptureGroups($regex)
{
$tokenRegex = self::TOKEN_REGEX;
return preg_replace_callback(
self::PLACEHOLDER_REGEXP,
array($this, 'replaceTokenWithRegexCaptureGroup'),
$regex
);
}
private function replaceTokenWithRegexCaptureGroup($tokenMatch)
{
if (strlen($tokenMatch[1]) >= 32) {
throw new InvalidPatternException(
"Token name should not exceed 32 characters, but `{$tokenMatch[1]}` was used."
);
}
return sprintf(self::TOKEN_REGEX, $tokenMatch[1]);
}
/**
* Replaces turnip optional ending with regex non-capturing optional group.
*
* @param string $regex
*
* @return string
*/
private function replaceTurnipOptionalEndingWithRegex($regex)
{
return preg_replace(self::OPTIONAL_WORD_REGEXP, '(?:\1)?(?:\2)?(?:\3)?', $regex);
}
/**
* Replaces turnip alternative words with regex non-capturing alternating group.
*
* @param string $regex
*
* @return string
*/
private function replaceTurnipAlternativeWordsWithRegex($regex)
{
$regex = preg_replace(self::ALTERNATIVE_WORD_REGEXP, '(?:\1|\2)', $regex);
$regex = $this->removeEscapingOfAlternationSyntax($regex);
return $regex;
}
/**
* Adds escaping to alternation syntax in pattern.
*
* By default, Turnip treats `/` as alternation syntax. Meaning `one/two` for Turnip
* means either `one` or `two`. Sometimes though you'll want to use slash character
* with different purpose (URL, UNIX paths). In this case, you would escape slashes
* with backslash.
*
* This method adds escaping to all slashes in generated snippets.
*
* @param string $pattern
*
* @return string
*/
private function escapeAlternationSyntax($pattern)
{
return str_replace('/', '\/', $pattern);
}
/**
* Removes escaping of alternation syntax from regex.
*
* This method removes those escaping backslashes from your slashes, so your steps
* could be matched against your escaped definitions.
*
* @param string $regex
*
* @return string
*/
private function removeEscapingOfAlternationSyntax($regex)
{
return str_replace('\\\/', '/', $regex);
}
}