DecimalInputBehavior.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. <?php
  2. App::uses('ModelBehavior', 'Model');
  3. /**
  4. * Format numeric values according to locale settings of either the system or the app.
  5. * You can use setlocale(LC_NUMERIC, [your-locale]); or Configure::write('Localization') to set global settings.
  6. * Or you can pass the localization pattern as `transform` key to the behavior directly.
  7. *
  8. * You can use strict mode to reduce errors made by converting too much automatically.
  9. *
  10. * Use `observedTypes` to define what type of db field you want to automatically track/modify.
  11. * You can always manually add more fields using `fields`.
  12. * If you want to adjust weather you want convertion for output, as well, set `output` to true.
  13. *
  14. * `before` can be 'validate' or 'safe', defaults to 'validate'.
  15. *
  16. * If you store percentages for example, you might want to allow the user to add integer percentage values (0 ... 100)
  17. * and convert them using `multiply` and '0.01' as value. It will assume that this is the input rate. For output it will automatically
  18. * be inversed.
  19. *
  20. * Example for GERMAN:
  21. * IN:
  22. * 20,01 => 20.01 (!)
  23. * 11.222 => 11222 (or 11#222 in strict mode to invalidate correctly)
  24. * OUT:
  25. * 20.01 => 20,01
  26. *
  27. * @author Mark Scherer
  28. * @license MIT
  29. * @cakephp 2.x
  30. * @deprecated Use NumberFormatBehavior instead!
  31. */
  32. class DecimalInputBehavior extends ModelBehavior {
  33. protected $_defaultConfig = array(
  34. 'before' => 'validate', // save or validate
  35. 'input' => true, // true = activated
  36. 'output' => false, // true = activated
  37. 'fields' => array(
  38. ),
  39. 'observedTypes' => array(
  40. 'float'
  41. ),
  42. 'localeconv' => false,
  43. // based on input (output other direction)
  44. 'transform' => array(
  45. '.' => '',
  46. ',' => '.',
  47. ),
  48. 'multiply' => 0, // direction => in (revert is out)
  49. 'transformReverse' => array(),
  50. 'strict' => false,
  51. );
  52. public $delimiterBaseFormat = array();
  53. public $delimiterFromFormat = array();
  54. /**
  55. * Adjust configs like: $Model->Behaviors-attach('Tools.DecimalInput', array('fields'=>array('xyz')))
  56. * leave fields empty to auto-detect all float inputs
  57. *
  58. * @return void
  59. */
  60. public function setup(Model $Model, $config = array()) {
  61. $this->settings[$Model->alias] = $this->_defaultConfig;
  62. if (!empty($config['strict'])) {
  63. $this->settings[$Model->alias]['transform']['.'] = '#';
  64. }
  65. if ($this->settings[$Model->alias]['localeconv'] || !empty($config['localeconv'])) {
  66. // use locale settings
  67. $conv = localeconv();
  68. $loc = array(
  69. 'decimals' => $conv['decimal_point'],
  70. 'thousands' => $conv['thousands_sep']
  71. );
  72. } elseif ($configure = Configure::read('Localization')) {
  73. // Use configure settings
  74. $loc = (array)$configure;
  75. }
  76. if (!empty($loc)) {
  77. $this->settings[$Model->alias]['transform'] = array(
  78. $loc['thousands'] => $this->settings[$Model->alias]['transform']['.'],
  79. $loc['decimals'] => $this->settings[$Model->alias]['transform'][','],
  80. );
  81. }
  82. $this->settings[$Model->alias] = $config + $this->settings[$Model->alias];
  83. $numberFields = array();
  84. $schema = $Model->schema();
  85. foreach ($schema as $key => $values) {
  86. if (isset($values['type']) && !in_array($key, $this->settings[$Model->alias]['fields']) && in_array($values['type'], $this->settings[$Model->alias]['observedTypes'])) {
  87. array_push($numberFields, $key);
  88. }
  89. }
  90. $this->settings[$Model->alias]['fields'] = array_merge($this->settings[$Model->alias]['fields'], $numberFields);
  91. }
  92. public function beforeValidate(Model $Model, $options = array()) {
  93. if ($this->settings[$Model->alias]['before'] !== 'validate') {
  94. return true;
  95. }
  96. $this->prepInput($Model, $Model->data); // Direction is from interface to database
  97. return true;
  98. }
  99. public function beforeSave(Model $Model, $options = array()) {
  100. if ($this->settings[$Model->alias]['before'] !== 'save') {
  101. return true;
  102. }
  103. $this->prepInput($Model, $Model->data); // Direction is from interface to database
  104. return true;
  105. }
  106. public function afterFind(Model $Model, $results, $primary = false) {
  107. if (!$this->settings[$Model->alias]['output'] || empty($results)) {
  108. return $results;
  109. }
  110. $results = $this->prepOutput($Model, $results); // Direction is from database to interface
  111. return $results;
  112. }
  113. /**
  114. * @param array $results (by reference)
  115. * @return void
  116. */
  117. public function prepInput(Model $Model, &$data) {
  118. foreach ($data[$Model->alias] as $key => $field) {
  119. if (in_array($key, $this->settings[$Model->alias]['fields'])) {
  120. $data[$Model->alias][$key] = $this->formatInputOutput($Model, $field, 'in');
  121. }
  122. }
  123. }
  124. /**
  125. * @param array $results
  126. * @return array results
  127. */
  128. public function prepOutput(Model $Model, $data) {
  129. foreach ($data as $datakey => $record) {
  130. if (!isset($record[$Model->alias])) {
  131. return $data;
  132. }
  133. foreach ($record[$Model->alias] as $key => $value) {
  134. if (in_array($key, $this->settings[$Model->alias]['fields'])) {
  135. $data[$datakey][$Model->alias][$key] = $this->formatInputOutput($Model, $value, 'out');
  136. }
  137. }
  138. }
  139. return $data;
  140. }
  141. /**
  142. * Perform a single transformation
  143. *
  144. * @return string cleanedValue
  145. */
  146. public function formatInputOutput(Model $Model, $value, $dir = 'in') {
  147. $this->_setTransformations($Model, $dir);
  148. if ($dir === 'out') {
  149. if ($this->settings[$Model->alias]['multiply']) {
  150. $value *= (float)(1 / $this->settings[$Model->alias]['multiply']);
  151. }
  152. $value = str_replace($this->delimiterFromFormat, $this->delimiterBaseFormat, (string)$value);
  153. } else {
  154. $value = str_replace(' ', '', $value);
  155. $value = str_replace($this->delimiterFromFormat, $this->delimiterBaseFormat, $value);
  156. if (is_numeric($value)) {
  157. $value = (float)$value;
  158. if ($this->settings[$Model->alias]['multiply']) {
  159. $value *= $this->settings[$Model->alias]['multiply'];
  160. }
  161. }
  162. }
  163. return $value;
  164. }
  165. /**
  166. * Prep the transformation chars
  167. *
  168. * @return void
  169. */
  170. protected function _setTransformations(Model $Model, $dir) {
  171. $from = array();
  172. $base = array();
  173. $transform = $this->settings[$Model->alias]['transform'];
  174. if (!empty($this->settings[$Model->alias]['transformReverse'])) {
  175. $transform = $this->settings[$Model->alias]['transformReverse'];
  176. } else {
  177. if ($dir === 'out') {
  178. $transform = array_reverse($transform, true);
  179. }
  180. }
  181. $first = true;
  182. foreach ($transform as $key => $value) {
  183. /*
  184. if ($first) {
  185. $from[] = $key;
  186. $base[] = '#';
  187. $key = '#';
  188. $first = false;
  189. }
  190. */
  191. $from[] = $key;
  192. $base[] = $value;
  193. }
  194. if ($dir === 'out') {
  195. $this->delimiterFromFormat = $base;
  196. $this->delimiterBaseFormat = $from;
  197. } else {
  198. $this->delimiterFromFormat = $from;
  199. $this->delimiterBaseFormat = $base;
  200. }
  201. }
  202. }