sfValidatorFromDescription.class.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * sfValidatorFromDescription converts a string to a validator.
  11. *
  12. * @package symfony
  13. * @subpackage validator
  14. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  15. * @version SVN: $Id: sfValidatorFromDescription.class.php 9048 2008-05-19 09:11:23Z FabianLange $
  16. */
  17. class sfValidatorFromDescription extends sfValidatorDecorator
  18. {
  19. protected
  20. $tokens = array(),
  21. $string = '';
  22. /**
  23. * @see sfValidatorBase
  24. */
  25. public function __construct($string, $options = array(), $messages = array())
  26. {
  27. $this->string = $string;
  28. $this->tokens = $this->tokenize($string);
  29. parent::__construct($options, $messages);
  30. }
  31. /**
  32. * Returns a PHP representation for the validator.
  33. *
  34. * This PHP representation can be evaled to return the object validator.
  35. *
  36. * This is mainly useful to cache the result of the validator string parsing.
  37. *
  38. * @return string The PHP representation for the validator
  39. */
  40. public function asPhp()
  41. {
  42. return $this->reduceTokens($this->tokens, 'asPhp');
  43. }
  44. /**
  45. * @see sfValidatorDecorator
  46. */
  47. public function getValidator()
  48. {
  49. if (is_null($this->validator))
  50. {
  51. $this->validator = $this->reduceTokens($this->tokens, 'getValidator');
  52. }
  53. return $this->validator;
  54. }
  55. /**
  56. * Tokenizes a validator string to a list of tokens in RPN.
  57. *
  58. * @param string $string A validator string
  59. *
  60. * @return array An array of tokens
  61. */
  62. protected function tokenize($string)
  63. {
  64. $tokens = array();
  65. $len = strlen($string);
  66. $i = 0;
  67. while ($i < $len)
  68. {
  69. if (preg_match('/^([a-z0-9_\-]+)\s*(<=|>=|<|>|==|!=)/i', substr($string, $i), $match))
  70. {
  71. // schema compare validator
  72. $i += strlen($match[0]);
  73. $leftField = $match[1];
  74. $operator = $match[2];
  75. // arguments (optional)
  76. $arguments = $this->parseArguments($string, $i);
  77. // rightField
  78. if (!preg_match('/\s*([a-z0-9_\-]+)/', substr($string, $i), $match))
  79. {
  80. throw new DomainException('Parsing problem.');
  81. }
  82. $i += strlen($match[0]);
  83. $rightField = $match[1];
  84. $tokens[] = new sfValidatorFDToken('sfValidatorSchemaCompare', array($leftField, $operator, $rightField, $arguments[0], isset($arguments[1]) ? $arguments[1] : array()));
  85. }
  86. else if (preg_match('/^(and|or)/i', substr($string, $i), $match))
  87. {
  88. // all, any validador
  89. $i += strlen($match[0]);
  90. // arguments (optional)
  91. $arguments = $this->parseArguments($string, $i);
  92. $tokens[] = new sfValidatorFDTokenOperator(strtolower($match[1]), $arguments);
  93. }
  94. else if (preg_match('/^(?:([a-z0-9_\-]+)\:)?([a-z0-9_\-]+)/i', substr($string, $i), $match))
  95. {
  96. // single validator (optionally filtered)
  97. $i += strlen($match[0]);
  98. $class = 'sfValidator'.$match[2];
  99. $arguments = $this->parseArguments($string, $i);
  100. $token = new sfValidatorFDToken($class, array($arguments[0], isset($arguments[1]) ? $arguments[1] : array()));
  101. if ($match[1])
  102. {
  103. $token = new sfValidatorFDTokenFilter($match[1], $token);
  104. }
  105. $tokens[] = $token;
  106. }
  107. else if ('(' == $string[$i])
  108. {
  109. $tokens[] = new sfValidatorFDTokenLeftBracket();
  110. ++$i;
  111. }
  112. else if (')' == $string[$i])
  113. {
  114. $tokens[] = new sfValidatorFDTokenRightBracket();
  115. ++$i;
  116. }
  117. else if (in_array($string[$i], array(' ', "\t", "\r", "\n")))
  118. {
  119. ++$i;
  120. }
  121. else
  122. {
  123. throw new DomainException(sprintf('Unable to parse string (%s).', $string));
  124. }
  125. }
  126. return $this->convertInfixToRpn($tokens);
  127. }
  128. /**
  129. * Parses validator arguments.
  130. *
  131. * @param string $string The string to parse
  132. * @param integer $i The indice to start the parsing
  133. *
  134. * @return array An array of parameters
  135. */
  136. protected function parseArguments($string, &$i)
  137. {
  138. $len = strlen($string);
  139. if ($i + 1 > $len || '(' != $string[$i])
  140. {
  141. return array(array(), array());
  142. }
  143. ++$i;
  144. $args = '';
  145. $opened = 0;
  146. while ($i < $len)
  147. {
  148. if ('(' == $string[$i])
  149. {
  150. ++$opened;
  151. }
  152. else if (')' == $string[$i])
  153. {
  154. if (!$opened)
  155. {
  156. break;
  157. }
  158. --$opened;
  159. }
  160. $args .= $string[$i++];
  161. }
  162. ++$i;
  163. return sfYamlInline::load('['.(!$args ? '{}' : $args).']');
  164. }
  165. /**
  166. * Converts a token array from an infix notation to a RPN.
  167. *
  168. * @param array $tokens An array of tokens in infix notation
  169. *
  170. * @return array An array of token in RPN
  171. */
  172. protected function convertInfixToRpn($tokens)
  173. {
  174. $outputStack = array();
  175. $operatorStack = array();
  176. $precedences = array('and' => 2, 'or' => 1, '(' => 0);
  177. // based on the shunting yard algorithm
  178. foreach ($tokens as $token)
  179. {
  180. switch (get_class($token))
  181. {
  182. case 'sfValidatorFDToken':
  183. $outputStack[] = $token;
  184. break;
  185. case 'sfValidatorFDTokenLeftBracket':
  186. $operatorStack[] = $token;
  187. break;
  188. case 'sfValidatorFDTokenRightBracket':
  189. while (!$operatorStack[count($operatorStack) - 1] instanceof sfValidatorFDTokenLeftBracket)
  190. {
  191. $outputStack[] = array_pop($operatorStack);
  192. }
  193. array_pop($operatorStack);
  194. break;
  195. case 'sfValidatorFDTokenOperator':
  196. while (count($operatorStack) && $precedences[$token->__toString()] <= $precedences[$operatorStack[count($operatorStack) - 1]->__toString()])
  197. {
  198. $outputStack[] = array_pop($operatorStack);
  199. }
  200. $operatorStack[] = $token;
  201. break;
  202. default:
  203. $outputStack[] = $token;
  204. }
  205. }
  206. while (count($operatorStack))
  207. {
  208. $token = array_pop($operatorStack);
  209. if ($token instanceof sfValidatorFDTokenLeftBracket || $token instanceof sfValidatorFDTokenRightBracket)
  210. {
  211. throw new DomainException(sprintf('Uneven parenthesis in string (%s).', $this->string));
  212. }
  213. $outputStack[] = $token;
  214. }
  215. return $outputStack;
  216. }
  217. /**
  218. * Reduces tokens to a single token and convert it with the given method.
  219. *
  220. * @param array $tokens An array of tokens
  221. * @param string $method The method name to execute on each token
  222. *
  223. * @return mixed A single validator representation
  224. */
  225. protected function reduceTokens($tokens, $method)
  226. {
  227. if (1 == count($tokens))
  228. {
  229. return $tokens[0]->$method();
  230. }
  231. // reduce to a single validator
  232. while (count($tokens) > 1)
  233. {
  234. $i = 0;
  235. while (isset($tokens[$i]) && !$tokens[$i] instanceof sfValidatorFDTokenOperator)
  236. {
  237. $i++;
  238. }
  239. $tokens[$i] = $tokens[$i]->$method($tokens[$i - 2], $tokens[$i - 1]);
  240. unset($tokens[$i - 1], $tokens[$i - 2]);
  241. $tokens = array_values($tokens);
  242. }
  243. return $tokens[0];
  244. }
  245. }
  246. class sfValidatorFDToken
  247. {
  248. protected
  249. $class,
  250. $arguments;
  251. public function __construct($class, $arguments = array())
  252. {
  253. $this->class = $class;
  254. $this->arguments = $arguments;
  255. }
  256. public function asPhp()
  257. {
  258. return sprintf('new %s(%s)', $this->class, implode(', ', array_map(create_function('$a', 'return var_export($a, true);'), $this->arguments)));
  259. }
  260. public function getValidator()
  261. {
  262. $reflection = new ReflectionClass($this->class);
  263. return $reflection->newInstanceArgs($this->arguments);
  264. }
  265. }
  266. class sfValidatorFDTokenFilter
  267. {
  268. protected
  269. $field,
  270. $token;
  271. public function __construct($field, sfValidatorFDToken $token)
  272. {
  273. $this->field = $field;
  274. $this->token = $token;
  275. }
  276. public function asPhp()
  277. {
  278. return sprintf('new sfValidatorSchemaFilter(\'%s\', %s)', $this->field, $this->token->asPhp());
  279. }
  280. public function getValidator()
  281. {
  282. return new sfValidatorSchemaFilter($this->field, $this->token->getValidator());
  283. }
  284. }
  285. class sfValidatorFDTokenOperator
  286. {
  287. protected
  288. $class,
  289. $operator,
  290. $token;
  291. public function __construct($operator, $arguments = array())
  292. {
  293. $this->operator = $operator;
  294. $this->arguments = $arguments;
  295. $this->class = 'or' == $operator ? 'sfValidatorOr' : 'sfValidatorAnd';
  296. }
  297. public function __toString()
  298. {
  299. return $this->operator;
  300. }
  301. public function asPhp($tokenLeft, $tokenRight)
  302. {
  303. return sprintf('new %s(array(%s, %s), %s)',
  304. $this->class,
  305. in_array(get_class($tokenLeft), array('sfValidatorFDToken', 'sfValidatorFDTokenFilter')) ? $tokenLeft->asPhp() : $tokenLeft,
  306. in_array(get_class($tokenRight), array('sfValidatorFDToken', 'sfValidatorFDTokenFilter')) ? $tokenRight->asPhp() : $tokenRight,
  307. implode(', ', array_map(create_function('$a', 'return var_export($a, true);'), $this->arguments))
  308. );
  309. }
  310. public function getValidator($tokenLeft, $tokenRight)
  311. {
  312. $reflection = new ReflectionClass($this->class);
  313. $validators = array(
  314. in_array(get_class($tokenLeft), array('sfValidatorFDToken', 'sfValidatorFDTokenFilter')) ? $tokenLeft->getValidator() : $tokenLeft,
  315. in_array(get_class($tokenRight), array('sfValidatorFDToken', 'sfValidatorFDTokenFilter')) ? $tokenRight->getValidator() : $tokenRight,
  316. );
  317. return $reflection->newInstanceArgs(array_merge(array($validators), $this->arguments));
  318. }
  319. }
  320. class sfValidatorFDTokenLeftBracket
  321. {
  322. public function __toString()
  323. {
  324. return '(';
  325. }
  326. }
  327. class sfValidatorFDTokenRightBracket
  328. {
  329. public function __toString()
  330. {
  331. return ')';
  332. }
  333. }