Validations.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. <?php
  2. /**
  3. * These two classes have been <i>heavily borrowed</i> from Ruby on Rails' ActiveRecord so much that
  4. * this piece can be considered a straight port. The reason for this is that the vaildation process is
  5. * tricky due to order of operations/events. The former combined with PHP's odd typecasting means
  6. * that it was easier to formulate this piece base on the rails code.
  7. *
  8. * @package ActiveRecord
  9. */
  10. namespace ActiveRecord;
  11. use ActiveRecord\Model;
  12. use IteratorAggregate;
  13. use ArrayIterator;
  14. /**
  15. * Manages validations for a {@link Model}.
  16. *
  17. * This class isn't meant to be directly used. Instead you define
  18. * validators thru static variables in your {@link Model}. Example:
  19. *
  20. * <code>
  21. * class Person extends ActiveRecord\Model {
  22. * static $validates_length_of = array(
  23. * array('name', 'within' => array(30,100),
  24. * array('state', 'is' => 2)
  25. * );
  26. * }
  27. *
  28. * $person = new Person();
  29. * $person->name = 'Tito';
  30. * $person->state = 'this is not two characters';
  31. *
  32. * if (!$person->is_valid())
  33. * print_r($person->errors);
  34. * </code>
  35. *
  36. * @package ActiveRecord
  37. * @see Errors
  38. * @link http://www.phpactiverecord.org/guides/validations
  39. */
  40. class Validations
  41. {
  42. private $model;
  43. private $options = array();
  44. private $validators = array();
  45. private $record;
  46. private static $VALIDATION_FUNCTIONS = array(
  47. 'validates_presence_of',
  48. 'validates_size_of',
  49. 'validates_length_of',
  50. 'validates_inclusion_of',
  51. 'validates_exclusion_of',
  52. 'validates_format_of',
  53. 'validates_numericality_of',
  54. 'validates_uniqueness_of'
  55. );
  56. private static $DEFAULT_VALIDATION_OPTIONS = array(
  57. 'on' => 'save',
  58. 'allow_null' => false,
  59. 'allow_blank' => false,
  60. 'message' => null,
  61. );
  62. private static $ALL_RANGE_OPTIONS = array(
  63. 'is' => null,
  64. 'within' => null,
  65. 'in' => null,
  66. 'minimum' => null,
  67. 'maximum' => null,
  68. );
  69. private static $ALL_NUMERICALITY_CHECKS = array(
  70. 'greater_than' => null,
  71. 'greater_than_or_equal_to' => null,
  72. 'equal_to' => null,
  73. 'less_than' => null,
  74. 'less_than_or_equal_to' => null,
  75. 'odd' => null,
  76. 'even' => null
  77. );
  78. /**
  79. * Constructs a {@link Validations} object.
  80. *
  81. * @param Model $model The model to validate
  82. * @return Validations
  83. */
  84. public function __construct(Model $model)
  85. {
  86. $this->model = $model;
  87. $this->record = new Errors($this->model);
  88. $this->klass = Reflections::instance()->get(get_class($this->model));
  89. $this->validators = array_intersect(array_keys($this->klass->getStaticProperties()), self::$VALIDATION_FUNCTIONS);
  90. }
  91. public function get_record()
  92. {
  93. return $this->record;
  94. }
  95. /**
  96. * Returns validator data.
  97. *
  98. * @return array
  99. */
  100. public function rules()
  101. {
  102. $data = array();
  103. foreach ($this->validators as $validate)
  104. {
  105. $attrs = $this->klass->getStaticPropertyValue($validate);
  106. foreach (wrap_strings_in_arrays($attrs) as $attr)
  107. {
  108. $field = $attr[0];
  109. if (!isset($data[$field]) || !is_array($data[$field]))
  110. $data[$field] = array();
  111. $attr['validator'] = $validate;
  112. unset($attr[0]);
  113. array_push($data[$field],$attr);
  114. }
  115. }
  116. return $data;
  117. }
  118. /**
  119. * Runs the validators.
  120. *
  121. * @return Errors the validation errors if any
  122. */
  123. public function validate()
  124. {
  125. foreach ($this->validators as $validate)
  126. {
  127. $definition = $this->klass->getStaticPropertyValue($validate);
  128. $this->$validate(wrap_strings_in_arrays($definition));
  129. }
  130. $model_reflection = Reflections::instance()->get($this->model);
  131. if ($model_reflection->hasMethod('validate') && $model_reflection->getMethod('validate')->isPublic())
  132. $this->model->validate();
  133. $this->record->clear_model();
  134. return $this->record;
  135. }
  136. /**
  137. * Validates a field is not null and not blank.
  138. *
  139. * <code>
  140. * class Person extends ActiveRecord\Model {
  141. * static $validates_presence_of = array(
  142. * array('first_name'),
  143. * array('last_name')
  144. * );
  145. * }
  146. * </code>
  147. *
  148. * Available options:
  149. *
  150. * <ul>
  151. * <li><b>message:</b> custom error message</li>
  152. * <li><b>allow_blank:</b> allow blank strings</li>
  153. * <li><b>allow_null:</b> allow null strings</li>
  154. * </ul>
  155. *
  156. * @param array $attrs Validation definition
  157. */
  158. public function validates_presence_of($attrs)
  159. {
  160. $configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('message' => Errors::$DEFAULT_ERROR_MESSAGES['blank'], 'on' => 'save'));
  161. foreach ($attrs as $attr)
  162. {
  163. $options = array_merge($configuration, $attr);
  164. $this->record->add_on_blank($options[0], $options['message']);
  165. }
  166. }
  167. /**
  168. * Validates that a value is included the specified array.
  169. *
  170. * <code>
  171. * class Car extends ActiveRecord\Model {
  172. * static $validates_inclusion_of = array(
  173. * array('fuel_type', 'in' => array('hyrdogen', 'petroleum', 'electric')),
  174. * );
  175. * }
  176. * </code>
  177. *
  178. * Available options:
  179. *
  180. * <ul>
  181. * <li><b>in/within:</b> attribute should/shouldn't be a value within an array</li>
  182. * <li><b>message:</b> custome error message</li>
  183. * <li><b>allow_blank:</b> allow blank strings</li>
  184. * <li><b>allow_null:</b> allow null strings</li>
  185. * </ul>
  186. *
  187. * @param array $attrs Validation definition
  188. */
  189. public function validates_inclusion_of($attrs)
  190. {
  191. $this->validates_inclusion_or_exclusion_of('inclusion', $attrs);
  192. }
  193. /**
  194. * This is the opposite of {@link validates_include_of}.
  195. *
  196. * Available options:
  197. *
  198. * <ul>
  199. * <li><b>in/within:</b> attribute should/shouldn't be a value within an array</li>
  200. * <li><b>message:</b> custome error message</li>
  201. * <li><b>allow_blank:</b> allow blank strings</li>
  202. * <li><b>allow_null:</b> allow null strings</li>
  203. * </ul>
  204. *
  205. * @param array $attrs Validation definition
  206. * @see validates_inclusion_of
  207. */
  208. public function validates_exclusion_of($attrs)
  209. {
  210. $this->validates_inclusion_or_exclusion_of('exclusion', $attrs);
  211. }
  212. /**
  213. * Validates that a value is in or out of a specified list of values.
  214. *
  215. * Available options:
  216. *
  217. * <ul>
  218. * <li><b>in/within:</b> attribute should/shouldn't be a value within an array</li>
  219. * <li><b>message:</b> custome error message</li>
  220. * <li><b>allow_blank:</b> allow blank strings</li>
  221. * <li><b>allow_null:</b> allow null strings</li>
  222. * </ul>
  223. *
  224. * @see validates_inclusion_of
  225. * @see validates_exclusion_of
  226. * @param string $type Either inclusion or exclusion
  227. * @param $attrs Validation definition
  228. */
  229. public function validates_inclusion_or_exclusion_of($type, $attrs)
  230. {
  231. $configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('message' => Errors::$DEFAULT_ERROR_MESSAGES[$type], 'on' => 'save'));
  232. foreach ($attrs as $attr)
  233. {
  234. $options = array_merge($configuration, $attr);
  235. $attribute = $options[0];
  236. $var = $this->model->$attribute;
  237. if (isset($options['in']))
  238. $enum = $options['in'];
  239. elseif (isset($options['within']))
  240. $enum = $options['within'];
  241. if (!is_array($enum))
  242. array($enum);
  243. $message = str_replace('%s', $var, $options['message']);
  244. if ($this->is_null_with_option($var, $options) || $this->is_blank_with_option($var, $options))
  245. continue;
  246. if (('inclusion' == $type && !in_array($var, $enum)) || ('exclusion' == $type && in_array($var, $enum)))
  247. $this->record->add($attribute, $message);
  248. }
  249. }
  250. /**
  251. * Validates that a value is numeric.
  252. *
  253. * <code>
  254. * class Person extends ActiveRecord\Model {
  255. * static $validates_numericality_of = array(
  256. * array('salary', 'greater_than' => 19.99, 'less_than' => 99.99)
  257. * );
  258. * }
  259. * </code>
  260. *
  261. * Available options:
  262. *
  263. * <ul>
  264. * <li><b>only_integer:</b> value must be an integer (e.g. not a float)</li>
  265. * <li><b>even:</b> must be even</li>
  266. * <li><b>odd:</b> must be odd"</li>
  267. * <li><b>greater_than:</b> must be greater than specified number</li>
  268. * <li><b>greater_than_or_equal_to:</b> must be greater than or equal to specified number</li>
  269. * <li><b>equal_to:</b> ...</li>
  270. * <li><b>less_than:</b> ...</li>
  271. * <li><b>less_than_or_equal_to:</b> ...</li>
  272. * <li><b>allow_blank:</b> allow blank strings</li>
  273. * <li><b>allow_null:</b> allow null strings</li>
  274. * </ul>
  275. *
  276. * @param array $attrs Validation definition
  277. */
  278. public function validates_numericality_of($attrs)
  279. {
  280. $configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('only_integer' => false));
  281. // Notice that for fixnum and float columns empty strings are converted to nil.
  282. // Validates whether the value of the specified attribute is numeric by trying to convert it to a float with Kernel.Float
  283. // (if only_integer is false) or applying it to the regular expression /\A[+\-]?\d+\Z/ (if only_integer is set to true).
  284. foreach ($attrs as $attr)
  285. {
  286. $options = array_merge($configuration, $attr);
  287. $attribute = $options[0];
  288. $var = $this->model->$attribute;
  289. $numericalityOptions = array_intersect_key(self::$ALL_NUMERICALITY_CHECKS, $options);
  290. if ($this->is_null_with_option($var, $options))
  291. continue;
  292. $not_a_number_message = (isset($options['message']) ? $options['message'] : Errors::$DEFAULT_ERROR_MESSAGES['not_a_number']);
  293. if (true === $options['only_integer'] && !is_integer($var))
  294. {
  295. if (!preg_match('/\A[+-]?\d+\Z/', (string)($var)))
  296. {
  297. $this->record->add($attribute, $not_a_number_message);
  298. continue;
  299. }
  300. }
  301. else
  302. {
  303. if (!is_numeric($var))
  304. {
  305. $this->record->add($attribute, $not_a_number_message);
  306. continue;
  307. }
  308. $var = (float)$var;
  309. }
  310. foreach ($numericalityOptions as $option => $check)
  311. {
  312. $option_value = $options[$option];
  313. $message = (isset($options['message']) ? $options['message'] : Errors::$DEFAULT_ERROR_MESSAGES[$option]);
  314. if ('odd' != $option && 'even' != $option)
  315. {
  316. $option_value = (float)$options[$option];
  317. if (!is_numeric($option_value))
  318. throw new ValidationsArgumentError("$option must be a number");
  319. $message = str_replace('%d', $option_value, $message);
  320. if ('greater_than' == $option && !($var > $option_value))
  321. $this->record->add($attribute, $message);
  322. elseif ('greater_than_or_equal_to' == $option && !($var >= $option_value))
  323. $this->record->add($attribute, $message);
  324. elseif ('equal_to' == $option && !($var == $option_value))
  325. $this->record->add($attribute, $message);
  326. elseif ('less_than' == $option && !($var < $option_value))
  327. $this->record->add($attribute, $message);
  328. elseif ('less_than_or_equal_to' == $option && !($var <= $option_value))
  329. $this->record->add($attribute, $message);
  330. }
  331. else
  332. {
  333. if (('odd' == $option && !Utils::is_odd($var)) || ('even' == $option && Utils::is_odd($var)))
  334. $this->record->add($attribute, $message);
  335. }
  336. }
  337. }
  338. }
  339. /**
  340. * Alias of {@link validates_length_of}
  341. *
  342. * @param array $attrs Validation definition
  343. */
  344. public function validates_size_of($attrs)
  345. {
  346. $this->validates_length_of($attrs);
  347. }
  348. /**
  349. * Validates that a value is matches a regex.
  350. *
  351. * <code>
  352. * class Person extends ActiveRecord\Model {
  353. * static $validates_format_of = array(
  354. * array('email', 'with' => '/^.*?@.*$/')
  355. * );
  356. * }
  357. * </code>
  358. *
  359. * Available options:
  360. *
  361. * <ul>
  362. * <li><b>with:</b> a regular expression</li>
  363. * <li><b>message:</b> custom error message</li>
  364. * <li><b>allow_blank:</b> allow blank strings</li>
  365. * <li><b>allow_null:</b> allow null strings</li>
  366. * </ul>
  367. *
  368. * @param array $attrs Validation definition
  369. */
  370. public function validates_format_of($attrs)
  371. {
  372. $configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('message' => Errors::$DEFAULT_ERROR_MESSAGES['invalid'], 'on' => 'save', 'with' => null));
  373. foreach ($attrs as $attr)
  374. {
  375. $options = array_merge($configuration, $attr);
  376. $attribute = $options[0];
  377. $var = $this->model->$attribute;
  378. if (is_null($options['with']) || !is_string($options['with']) || !is_string($options['with']))
  379. throw new ValidationsArgumentError('A regular expression must be supplied as the [with] option of the configuration array.');
  380. else
  381. $expression = $options['with'];
  382. if ($this->is_null_with_option($var, $options) || $this->is_blank_with_option($var, $options))
  383. continue;
  384. if (!@preg_match($expression, $var))
  385. $this->record->add($attribute, $options['message']);
  386. }
  387. }
  388. /**
  389. * Validates the length of a value.
  390. *
  391. * <code>
  392. * class Person extends ActiveRecord\Model {
  393. * static $validates_length_of = array(
  394. * array('name', 'within' => array(1,50))
  395. * );
  396. * }
  397. * </code>
  398. *
  399. * Available options:
  400. *
  401. * <ul>
  402. * <li><b>is:</b> attribute should be exactly n characters long</li>
  403. * <li><b>in/within:</b> attribute should be within an range array(min,max)</li>
  404. * <li><b>maximum/minimum:</b> attribute should not be above/below respectively</li>
  405. * <li><b>message:</b> custome error message</li>
  406. * <li><b>allow_blank:</b> allow blank strings</li>
  407. * <li><b>allow_null:</b> allow null strings. (Even if this is set to false, a null string is always shorter than a maximum value.)</li>
  408. * </ul>
  409. *
  410. * @param array $attrs Validation definition
  411. */
  412. public function validates_length_of($attrs)
  413. {
  414. $configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array(
  415. 'too_long' => Errors::$DEFAULT_ERROR_MESSAGES['too_long'],
  416. 'too_short' => Errors::$DEFAULT_ERROR_MESSAGES['too_short'],
  417. 'wrong_length' => Errors::$DEFAULT_ERROR_MESSAGES['wrong_length']
  418. ));
  419. foreach ($attrs as $attr)
  420. {
  421. $options = array_merge($configuration, $attr);
  422. $range_options = array_intersect(array_keys(self::$ALL_RANGE_OPTIONS), array_keys($attr));
  423. sort($range_options);
  424. switch (sizeof($range_options))
  425. {
  426. case 0:
  427. throw new ValidationsArgumentError('Range unspecified. Specify the [within], [maximum], or [is] option.');
  428. case 1:
  429. break;
  430. default:
  431. throw new ValidationsArgumentError('Too many range options specified. Choose only one.');
  432. }
  433. $attribute = $options[0];
  434. $var = $this->model->$attribute;
  435. if ($this->is_null_with_option($var, $options) || $this->is_blank_with_option($var, $options))
  436. continue;
  437. if ($range_options[0] == 'within' || $range_options[0] == 'in')
  438. {
  439. $range = $options[$range_options[0]];
  440. if (!(Utils::is_a('range', $range)))
  441. throw new ValidationsArgumentError("$range_option must be an array composing a range of numbers with key [0] being less than key [1]");
  442. $range_options = array('minimum', 'maximum');
  443. $attr['minimum'] = $range[0];
  444. $attr['maximum'] = $range[1];
  445. }
  446. foreach ($range_options as $range_option)
  447. {
  448. $option = $attr[$range_option];
  449. if ((int)$option <= 0)
  450. throw new ValidationsArgumentError("$range_option value cannot use a signed integer.");
  451. if (is_float($option))
  452. throw new ValidationsArgumentError("$range_option value cannot use a float for length.");
  453. if (!($range_option == 'maximum' && is_null($this->model->$attribute)))
  454. {
  455. $messageOptions = array('is' => 'wrong_length', 'minimum' => 'too_short', 'maximum' => 'too_long');
  456. if (isset($options['message']))
  457. $message = $options['message'];
  458. else
  459. $message = $options[$messageOptions[$range_option]];
  460. $message = str_replace('%d', $option, $message);
  461. $attribute_value = $this->model->$attribute;
  462. $len = strlen($attribute_value);
  463. $value = (int)$attr[$range_option];
  464. if ('maximum' == $range_option && $len > $value)
  465. $this->record->add($attribute, $message);
  466. if ('minimum' == $range_option && $len < $value)
  467. $this->record->add($attribute, $message);
  468. if ('is' == $range_option && $len !== $value)
  469. $this->record->add($attribute, $message);
  470. }
  471. }
  472. }
  473. }
  474. /**
  475. * Validates the uniqueness of a value.
  476. *
  477. * <code>
  478. * class Person extends ActiveRecord\Model {
  479. * static $validates_uniqueness_of = array(
  480. * array('name'),
  481. * array(array('blah','bleh'), 'message' => 'blech')
  482. * );
  483. * }
  484. * </code>
  485. *
  486. * Available options:
  487. *
  488. * <ul>
  489. * <li><b>with:</b> a regular expression</li>
  490. * <li><b>message:</b> custom error message</li>
  491. * <li><b>allow_blank:</b> allow blank strings</li>
  492. * <li><b>allow_null:</b> allow null strings</li>
  493. * </ul>
  494. *
  495. * @param array $attrs Validation definition
  496. */
  497. public function validates_uniqueness_of($attrs)
  498. {
  499. $configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array(
  500. 'message' => Errors::$DEFAULT_ERROR_MESSAGES['unique']
  501. ));
  502. // Retrieve connection from model for quote_name method
  503. $connection = $this->klass->getMethod('connection')->invoke(null);
  504. foreach ($attrs as $attr)
  505. {
  506. $options = array_merge($configuration, $attr);
  507. $pk = $this->model->get_primary_key();
  508. $pk_value = $this->model->$pk[0];
  509. if (is_array($options[0]))
  510. {
  511. $add_record = join("_and_", $options[0]);
  512. $fields = $options[0];
  513. }
  514. else
  515. {
  516. $add_record = $options[0];
  517. $fields = array($options[0]);
  518. }
  519. $sql = "";
  520. $conditions = array("");
  521. $pk_quoted = $connection->quote_name($pk[0]);
  522. if ($pk_value === null)
  523. $sql = "{$pk_quoted} IS NOT NULL";
  524. else
  525. {
  526. $sql = "{$pk_quoted} != ?";
  527. array_push($conditions,$pk_value);
  528. }
  529. foreach ($fields as $field)
  530. {
  531. $field = $this->model->get_real_attribute_name($field);
  532. $quoted_field = $connection->quote_name($field);
  533. $sql .= " AND {$quoted_field}=?";
  534. array_push($conditions,$this->model->$field);
  535. }
  536. $conditions[0] = $sql;
  537. if ($this->model->exists(array('conditions' => $conditions)))
  538. $this->record->add($add_record, $options['message']);
  539. }
  540. }
  541. private function is_null_with_option($var, &$options)
  542. {
  543. return (is_null($var) && (isset($options['allow_null']) && $options['allow_null']));
  544. }
  545. private function is_blank_with_option($var, &$options)
  546. {
  547. return (Utils::is_blank($var) && (isset($options['allow_blank']) && $options['allow_blank']));
  548. }
  549. }
  550. /**
  551. * Class that holds {@link Validations} errors.
  552. *
  553. * @package ActiveRecord
  554. */
  555. class Errors implements IteratorAggregate
  556. {
  557. private $model;
  558. private $errors;
  559. public static $DEFAULT_ERROR_MESSAGES = array(
  560. 'inclusion' => "is not included in the list",
  561. 'exclusion' => "is reserved",
  562. 'invalid' => "is invalid",
  563. 'confirmation' => "doesn't match confirmation",
  564. 'accepted' => "must be accepted",
  565. 'empty' => "can't be empty",
  566. 'blank' => "can't be blank",
  567. 'too_long' => "is too long (maximum is %d characters)",
  568. 'too_short' => "is too short (minimum is %d characters)",
  569. 'wrong_length' => "is the wrong length (should be %d characters)",
  570. 'taken' => "has already been taken",
  571. 'not_a_number' => "is not a number",
  572. 'greater_than' => "must be greater than %d",
  573. 'equal_to' => "must be equal to %d",
  574. 'less_than' => "must be less than %d",
  575. 'odd' => "must be odd",
  576. 'even' => "must be even",
  577. 'unique' => "must be unique",
  578. 'less_than_or_equal_to' => "must be less than or equal to %d",
  579. 'greater_than_or_equal_to' => "must be greater than or equal to %d"
  580. );
  581. /**
  582. * Constructs an {@link Errors} object.
  583. *
  584. * @param Model $model The model the error is for
  585. * @return Errors
  586. */
  587. public function __construct(Model $model)
  588. {
  589. $this->model = $model;
  590. }
  591. /**
  592. * Nulls $model so we don't get pesky circular references. $model is only needed during the
  593. * validation process and so can be safely cleared once that is done.
  594. */
  595. public function clear_model()
  596. {
  597. $this->model = null;
  598. }
  599. /**
  600. * Add an error message.
  601. *
  602. * @param string $attribute Name of an attribute on the model
  603. * @param string $msg The error message
  604. */
  605. public function add($attribute, $msg)
  606. {
  607. if (is_null($msg))
  608. $msg = self :: $DEFAULT_ERROR_MESSAGES['invalid'];
  609. if (!isset($this->errors[$attribute]))
  610. $this->errors[$attribute] = array($msg);
  611. else
  612. $this->errors[$attribute][] = $msg;
  613. }
  614. /**
  615. * Adds an error message only if the attribute value is {@link http://www.php.net/empty empty}.
  616. *
  617. * @param string $attribute Name of an attribute on the model
  618. * @param string $msg The error message
  619. */
  620. public function add_on_empty($attribute, $msg)
  621. {
  622. if (empty($msg))
  623. $msg = self::$DEFAULT_ERROR_MESSAGES['empty'];
  624. if (empty($this->model->$attribute))
  625. $this->add($attribute, $msg);
  626. }
  627. /**
  628. * Retrieve error messages for an attribute.
  629. *
  630. * @param string $attribute Name of an attribute on the model
  631. * @return array or null if there is no error.
  632. */
  633. public function __get($attribute)
  634. {
  635. if (!isset($this->errors[$attribute]))
  636. return null;
  637. return $this->errors[$attribute];
  638. }
  639. /**
  640. * Adds the error message only if the attribute value was null or an empty string.
  641. *
  642. * @param string $attribute Name of an attribute on the model
  643. * @param string $msg The error message
  644. */
  645. public function add_on_blank($attribute, $msg)
  646. {
  647. if (!$msg)
  648. $msg = self::$DEFAULT_ERROR_MESSAGES['blank'];
  649. if (($value = $this->model->$attribute) === '' || $value === null)
  650. $this->add($attribute, $msg);
  651. }
  652. /**
  653. * Returns true if the specified attribute had any error messages.
  654. *
  655. * @param string $attribute Name of an attribute on the model
  656. * @return boolean
  657. */
  658. public function is_invalid($attribute)
  659. {
  660. return isset($this->errors[$attribute]);
  661. }
  662. /**
  663. * Returns the error message(s) for the specified attribute or null if none.
  664. *
  665. * @param string $attribute Name of an attribute on the model
  666. * @return string/array Array of strings if several error occured on this attribute.
  667. */
  668. public function on($attribute)
  669. {
  670. $errors = $this->$attribute;
  671. return $errors && count($errors) == 1 ? $errors[0] : $errors;
  672. }
  673. /**
  674. * Returns the internal errors object.
  675. *
  676. * <code>
  677. * $model->errors->get_raw_errors();
  678. *
  679. * # array(
  680. * # "name" => array("can't be blank"),
  681. * # "state" => array("is the wrong length (should be 2 chars)",
  682. * # )
  683. * </code>
  684. */
  685. public function get_raw_errors()
  686. {
  687. return $this->errors;
  688. }
  689. /**
  690. * Returns all the error messages as an array.
  691. *
  692. * <code>
  693. * $model->errors->full_messages();
  694. *
  695. * # array(
  696. * # "Name can't be blank",
  697. * # "State is the wrong length (should be 2 chars)"
  698. * # )
  699. * </code>
  700. *
  701. * @return array
  702. */
  703. public function full_messages()
  704. {
  705. $full_messages = array();
  706. $this->to_array(function($attribute, $message) use (&$full_messages) {
  707. $full_messages[] = $message;
  708. });
  709. return $full_messages;
  710. }
  711. /**
  712. * Returns all the error messages as an array, including error key.
  713. *
  714. * <code>
  715. * $model->errors->errors();
  716. *
  717. * # array(
  718. * # "name" => array("Name can't be blank"),
  719. * # "state" => array("State is the wrong length (should be 2 chars)")
  720. * # )
  721. * </code>
  722. *
  723. * @param array $closure Closure to fetch the errors in some other format (optional)
  724. * This closure has the signature function($attribute, $message)
  725. * and is called for each available error message.
  726. * @return array
  727. */
  728. public function to_array($closure=null)
  729. {
  730. $errors = array();
  731. if ($this->errors)
  732. {
  733. foreach ($this->errors as $attribute => $messages)
  734. {
  735. foreach ($messages as $msg)
  736. {
  737. if (is_null($msg))
  738. continue;
  739. $errors[$attribute][] = ($message = Utils::human_attribute($attribute) . ' ' . $msg);
  740. if ($closure)
  741. $closure($attribute,$message);
  742. }
  743. }
  744. }
  745. return $errors;
  746. }
  747. /**
  748. * Convert all error messages to a String.
  749. * This function is called implicitely if the object is casted to a string:
  750. *
  751. * <code>
  752. * echo $error;
  753. *
  754. * # "Name can't be blank\nState is the wrong length (should be 2 chars)"
  755. * </code>
  756. * @return string
  757. */
  758. public function __toString()
  759. {
  760. return implode("\n", $this->full_messages());
  761. }
  762. /**
  763. * Returns true if there are no error messages.
  764. * @return boolean
  765. */
  766. public function is_empty()
  767. {
  768. return empty($this->errors);
  769. }
  770. /**
  771. * Clears out all error messages.
  772. */
  773. public function clear()
  774. {
  775. $this->errors = array();
  776. }
  777. /**
  778. * Returns the number of error messages there are.
  779. * @return int
  780. */
  781. public function size()
  782. {
  783. if ($this->is_empty())
  784. return 0;
  785. $count = 0;
  786. foreach ($this->errors as $attribute => $error)
  787. $count += count($error);
  788. return $count;
  789. }
  790. /**
  791. * Returns an iterator to the error messages.
  792. *
  793. * This will allow you to iterate over the {@link Errors} object using foreach.
  794. *
  795. * <code>
  796. * foreach ($model->errors as $msg)
  797. * echo "$msg\n";
  798. * </code>
  799. *
  800. * @return ArrayIterator
  801. */
  802. public function getIterator()
  803. {
  804. return new ArrayIterator($this->full_messages());
  805. }
  806. };
  807. ?>