/lib/validator/sfValidatorBase.class.php

https://github.com/bheneka/gitta · PHP · 498 lines · 200 code · 58 blank · 240 comment · 13 complexity · 055f7f853b4a4c927219f6fb541c387c MD5 · raw file

  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. * sfValidatorBase is the base class for all validators.
  11. *
  12. * It also implements the required option for all validators.
  13. *
  14. * @package symfony
  15. * @subpackage validator
  16. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  17. * @version SVN: $Id$
  18. */
  19. abstract class sfValidatorBase
  20. {
  21. protected static
  22. $charset = 'UTF-8',
  23. $globalDefaultMessages = array('invalid' => 'Invalid.', 'required' => 'Required.');
  24. protected
  25. $requiredOptions = array(),
  26. $defaultMessages = array(),
  27. $defaultOptions = array(),
  28. $messages = array(),
  29. $options = array();
  30. /**
  31. * Constructor.
  32. *
  33. * Available options:
  34. *
  35. * * required: true if the value is required, false otherwise (default to true)
  36. * * trim: true if the value must be trimmed, false otherwise (default to false)
  37. * * empty_value: empty value when value is not required
  38. *
  39. * Available error codes:
  40. *
  41. * * required
  42. * * invalid
  43. *
  44. * @param array $options An array of options
  45. * @param array $messages An array of error messages
  46. */
  47. public function __construct($options = array(), $messages = array())
  48. {
  49. $this->options = array_merge(array('required' => true, 'trim' => false, 'empty_value' => null), $this->options);
  50. $this->messages = array_merge(array('required' => self::$globalDefaultMessages['required'], 'invalid' => self::$globalDefaultMessages['invalid']), $this->messages);
  51. $this->configure($options, $messages);
  52. $this->setDefaultOptions($this->getOptions());
  53. $this->setDefaultMessages($this->getMessages());
  54. $currentOptionKeys = array_keys($this->options);
  55. $optionKeys = array_keys($options);
  56. // check option names
  57. if ($diff = array_diff($optionKeys, array_merge($currentOptionKeys, $this->requiredOptions)))
  58. {
  59. throw new InvalidArgumentException(sprintf('%s does not support the following options: \'%s\'.', get_class($this), implode('\', \'', $diff)));
  60. }
  61. // check error code names
  62. if ($diff = array_diff(array_keys($messages), array_keys($this->messages)))
  63. {
  64. throw new InvalidArgumentException(sprintf('%s does not support the following error codes: \'%s\'.', get_class($this), implode('\', \'', $diff)));
  65. }
  66. // check required options
  67. if ($diff = array_diff($this->requiredOptions, array_merge($currentOptionKeys, $optionKeys)))
  68. {
  69. throw new RuntimeException(sprintf('%s requires the following options: \'%s\'.', get_class($this), implode('\', \'', $diff)));
  70. }
  71. $this->options = array_merge($this->options, $options);
  72. $this->messages = array_merge($this->messages, $messages);
  73. }
  74. /**
  75. * Configures the current validator.
  76. *
  77. * This method allows each validator to add options and error messages
  78. * during validator creation.
  79. *
  80. * If some options and messages are given in the sfValidatorBase constructor
  81. * they will take precedence over the options and messages you configure
  82. * in this method.
  83. *
  84. * @param array $options An array of options
  85. * @param array $messages An array of error messages
  86. *
  87. * @see __construct()
  88. */
  89. protected function configure($options = array(), $messages = array())
  90. {
  91. }
  92. /**
  93. * Returns an error message given an error code.
  94. *
  95. * @param string $name The error code
  96. *
  97. * @return string The error message, or the empty string if the error code does not exist
  98. */
  99. public function getMessage($name)
  100. {
  101. return isset($this->messages[$name]) ? $this->messages[$name] : '';
  102. }
  103. /**
  104. * Adds a new error code with a default error message.
  105. *
  106. * @param string $name The error code
  107. * @param string $value The error message
  108. *
  109. * @return sfValidatorBase The current validator instance
  110. */
  111. public function addMessage($name, $value)
  112. {
  113. $this->messages[$name] = isset(self::$globalDefaultMessages[$name]) ? self::$globalDefaultMessages[$name] : $value;
  114. return $this;
  115. }
  116. /**
  117. * Changes an error message given the error code.
  118. *
  119. * @param string $name The error code
  120. * @param string $value The error message
  121. *
  122. * @return sfValidatorBase The current validator instance
  123. */
  124. public function setMessage($name, $value)
  125. {
  126. if (!in_array($name, array_keys($this->messages)))
  127. {
  128. throw new InvalidArgumentException(sprintf('%s does not support the following error code: \'%s\'.', get_class($this), $name));
  129. }
  130. $this->messages[$name] = $value;
  131. return $this;
  132. }
  133. /**
  134. * Returns an array of current error messages.
  135. *
  136. * @return array An array of messages
  137. */
  138. public function getMessages()
  139. {
  140. return $this->messages;
  141. }
  142. /**
  143. * Changes all error messages.
  144. *
  145. * @param array $values An array of error messages
  146. *
  147. * @return sfValidatorBase The current validator instance
  148. */
  149. public function setMessages($values)
  150. {
  151. $this->messages = array_merge(array('required' => self::$globalDefaultMessages['required'], 'invalid' => self::$globalDefaultMessages['invalid']), $values);
  152. return $this;
  153. }
  154. /**
  155. * Gets an option value.
  156. *
  157. * @param string $name The option name
  158. *
  159. * @return mixed The option value
  160. */
  161. public function getOption($name)
  162. {
  163. return isset($this->options[$name]) ? $this->options[$name] : null;
  164. }
  165. /**
  166. * Adds a new option value with a default value.
  167. *
  168. * @param string $name The option name
  169. * @param mixed $value The default value
  170. *
  171. * @return sfValidatorBase The current validator instance
  172. */
  173. public function addOption($name, $value = null)
  174. {
  175. $this->options[$name] = $value;
  176. return $this;
  177. }
  178. /**
  179. * Changes an option value.
  180. *
  181. * @param string $name The option name
  182. * @param mixed $value The value
  183. *
  184. * @return sfValidatorBase The current validator instance
  185. */
  186. public function setOption($name, $value)
  187. {
  188. if (!in_array($name, array_merge(array_keys($this->options), $this->requiredOptions)))
  189. {
  190. throw new InvalidArgumentException(sprintf('%s does not support the following option: \'%s\'.', get_class($this), $name));
  191. }
  192. $this->options[$name] = $value;
  193. return $this;
  194. }
  195. /**
  196. * Returns true if the option exists.
  197. *
  198. * @param string $name The option name
  199. *
  200. * @return bool true if the option exists, false otherwise
  201. */
  202. public function hasOption($name)
  203. {
  204. return isset($this->options[$name]);
  205. }
  206. /**
  207. * Returns all options.
  208. *
  209. * @return array An array of options
  210. */
  211. public function getOptions()
  212. {
  213. return $this->options;
  214. }
  215. /**
  216. * Changes all options.
  217. *
  218. * @param array $values An array of options
  219. *
  220. * @return sfValidatorBase The current validator instance
  221. */
  222. public function setOptions($values)
  223. {
  224. $this->options = array_merge(array('required' => true, 'trim' => false, 'empty_value' => null), $values);
  225. return $this;
  226. }
  227. /**
  228. * Adds a required option.
  229. *
  230. * @param string $name The option name
  231. *
  232. * @return sfValidatorBase The current validator instance
  233. */
  234. public function addRequiredOption($name)
  235. {
  236. $this->requiredOptions[] = $name;
  237. return $this;
  238. }
  239. /**
  240. * Returns all required option names.
  241. *
  242. * @return array An array of required option names
  243. */
  244. public function getRequiredOptions()
  245. {
  246. return $this->requiredOptions;
  247. }
  248. /**
  249. * Sets the default message for a given name.
  250. *
  251. * @param string $name The name of the message
  252. * @param string $message The default message string
  253. */
  254. static public function setDefaultMessage($name, $message)
  255. {
  256. self::$globalDefaultMessages[$name] = $message;
  257. }
  258. /**
  259. * Cleans the input value.
  260. *
  261. * This method is also responsible for trimming the input value
  262. * and checking the required option.
  263. *
  264. * @param mixed $value The input value
  265. *
  266. * @return mixed The cleaned value
  267. *
  268. * @throws sfValidatorError
  269. */
  270. public function clean($value)
  271. {
  272. $clean = $value;
  273. if ($this->options['trim'] && is_string($clean))
  274. {
  275. $clean = trim($clean);
  276. }
  277. // empty value?
  278. if ($this->isEmpty($clean))
  279. {
  280. // required?
  281. if ($this->options['required'])
  282. {
  283. throw new sfValidatorError($this, 'required');
  284. }
  285. return $this->getEmptyValue();
  286. }
  287. return $this->doClean($clean);
  288. }
  289. /**
  290. * Cleans the input value.
  291. *
  292. * Every subclass must implements this method.
  293. *
  294. * @param mixed $value The input value
  295. *
  296. * @return mixed The cleaned value
  297. *
  298. * @throws sfValidatorError
  299. */
  300. abstract protected function doClean($value);
  301. /**
  302. * Sets the charset to use when validating strings.
  303. *
  304. * @param string $charset The charset
  305. */
  306. static public function setCharset($charset)
  307. {
  308. self::$charset = $charset;
  309. }
  310. /**
  311. * Returns the charset to use when validating strings.
  312. *
  313. * @return string The charset (default to UTF-8)
  314. */
  315. static public function getCharset()
  316. {
  317. return self::$charset;
  318. }
  319. /**
  320. * Returns true if the value is empty.
  321. *
  322. * @param mixed $value The input value
  323. *
  324. * @return bool true if the value is empty, false otherwise
  325. */
  326. protected function isEmpty($value)
  327. {
  328. return in_array($value, array(null, '', array()), true);
  329. }
  330. /**
  331. * Returns an empty value for this validator.
  332. *
  333. * @return mixed The empty value for this validator
  334. */
  335. protected function getEmptyValue()
  336. {
  337. return $this->getOption('empty_value');
  338. }
  339. /**
  340. * Returns an array of all error codes for this validator.
  341. *
  342. * @return array An array of possible error codes
  343. *
  344. * @see getDefaultMessages()
  345. */
  346. final public function getErrorCodes()
  347. {
  348. return array_keys($this->getDefaultMessages());
  349. }
  350. /**
  351. * Returns default messages for all possible error codes.
  352. *
  353. * @return array An array of default error codes and messages
  354. */
  355. public function getDefaultMessages()
  356. {
  357. return $this->defaultMessages;
  358. }
  359. /**
  360. * Sets default messages for all possible error codes.
  361. *
  362. * @param array $messages An array of default error codes and messages
  363. */
  364. protected function setDefaultMessages($messages)
  365. {
  366. $this->defaultMessages = $messages;
  367. }
  368. /**
  369. * Returns default option values.
  370. *
  371. * @return array An array of default option values
  372. */
  373. public function getDefaultOptions()
  374. {
  375. return $this->defaultOptions;
  376. }
  377. /**
  378. * Sets default option values.
  379. *
  380. * @param array $options An array of default option values
  381. */
  382. protected function setDefaultOptions($options)
  383. {
  384. $this->defaultOptions = $options;
  385. }
  386. /**
  387. * Returns a string representation of this validator.
  388. *
  389. * @param int $indent Indentation (number of spaces before each line)
  390. *
  391. * @return string The string representation of the validator
  392. */
  393. public function asString($indent = 0)
  394. {
  395. $options = $this->getOptionsWithoutDefaults();
  396. $messages = $this->getMessagesWithoutDefaults();
  397. return sprintf('%s%s(%s%s)',
  398. str_repeat(' ', $indent),
  399. str_replace('sfValidator', '', get_class($this)),
  400. $options ? sfYamlInline::dump($options) : ($messages ? '{}' : ''),
  401. $messages ? ', '.sfYamlInline::dump($messages) : ''
  402. );
  403. }
  404. /**
  405. * Returns all error messages with non default values.
  406. *
  407. * @return string A string representation of the error messages
  408. */
  409. protected function getMessagesWithoutDefaults()
  410. {
  411. $messages = $this->messages;
  412. // remove default option values
  413. foreach ($this->getDefaultMessages() as $key => $value)
  414. {
  415. if (array_key_exists($key, $messages) && $messages[$key] === $value)
  416. {
  417. unset($messages[$key]);
  418. }
  419. }
  420. return $messages;
  421. }
  422. /**
  423. * Returns all options with non default values.
  424. *
  425. * @return string A string representation of the options
  426. */
  427. protected function getOptionsWithoutDefaults()
  428. {
  429. $options = $this->options;
  430. // remove default option values
  431. foreach ($this->getDefaultOptions() as $key => $value)
  432. {
  433. if (array_key_exists($key, $options) && $options[$key] === $value)
  434. {
  435. unset($options[$key]);
  436. }
  437. }
  438. return $options;
  439. }
  440. }