PageRenderTime 51ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/models/behaviors/trim.php

https://github.com/zpartakov/pmCake
PHP | 59 lines | 35 code | 4 blank | 20 comment | 4 complexity | 24ecac3e26f2a8d0e746f86a18de9a14 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-3.0
  1. <?php
  2. /**
  3. * Add an automatic trim() of values before saving them in the datasource.
  4. *
  5. * By default all fields are trimed, but an array of fields to trim can be passed in the settings
  6. *
  7. * Example:
  8. * //trim all fields
  9. * var $actsAs = array('Alaxos.Trim');
  10. *
  11. * //trim only lastname and firstname
  12. * var $actsAs = array('Alaxos.Trim' => array('fields' => array('lastname', 'firstname')));
  13. *
  14. * @author Nicolas Rod <nico@alaxos.com>
  15. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  16. * @link http://www.alaxos.net
  17. *
  18. */
  19. class TrimBehavior extends ModelBehavior
  20. {
  21. const ALL_FIELDS = '*';
  22. function setup(&$model, $settings)
  23. {
  24. if(isset($settings['fields']))
  25. {
  26. $this->settings[$model->alias]['fields'] = $settings['fields'];
  27. }
  28. else
  29. {
  30. /*
  31. * Default settings -> trim all fields
  32. */
  33. $this->settings[$model->alias]['fields'] = TrimBehavior::ALL_FIELDS;
  34. }
  35. }
  36. function beforeSave(&$model)
  37. {
  38. $fields_to_trim = array();
  39. if($this->settings[$model->alias]['fields'] == TrimBehavior::ALL_FIELDS)
  40. {
  41. $fields_to_trim = array_keys($model->data[$model->alias]);
  42. }
  43. else
  44. {
  45. $fields_to_trim = $this->settings[$model->alias]['fields'];
  46. }
  47. foreach($model->data[$model->alias] as $fieldname => $value)
  48. {
  49. if(in_array($fieldname, $fields_to_trim))
  50. {
  51. $model->data[$model->alias][$fieldname] = trim($value);
  52. }
  53. }
  54. }
  55. }