DecimalInputBehavior.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 $_defaults = 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. public function setup(Model $Model, $config = array()) {
  59. $this->config[$Model->alias] = $this->_defaults;
  60. if (!empty($config['strict'])) {
  61. $this->config[$Model->alias]['transform']['.'] = '#';
  62. }
  63. if ($this->config[$Model->alias]['localeconv'] || !empty($config['localeconv'])) {
  64. # use locale settings
  65. $conv = localeconv();
  66. $loc = array(
  67. 'decimals' => $conv['decimal_point'],
  68. 'thousands' => $conv['thousands_sep']
  69. );
  70. } elseif ($configure = Configure::read('Localization')) {
  71. # use configure settings
  72. $loc = (array)$configure;
  73. }
  74. if (!empty($loc)) {
  75. $this->config[$Model->alias]['transform'] = array(
  76. $loc['thousands'] => $this->config[$Model->alias]['transform']['.'],
  77. $loc['decimals'] => $this->config[$Model->alias]['transform'][','],
  78. );
  79. }
  80. //debug($this->config[$Model->alias]);
  81. $this->config[$Model->alias] = array_merge($this->config[$Model->alias], $config);
  82. $numberFields = array();
  83. $schema = $Model->schema();
  84. foreach ($schema as $key => $values) {
  85. if (isset($values['type']) && !in_array($key, $this->config[$Model->alias]['fields']) && in_array($values['type'], $this->config[$Model->alias]['observedTypes'])) {
  86. array_push($numberFields, $key);
  87. }
  88. }
  89. $this->config[$Model->alias]['fields'] = array_merge($this->config[$Model->alias]['fields'], $numberFields);
  90. }
  91. public function beforeValidate(Model $Model, $options = array()) {
  92. if ($this->config[$Model->alias]['before'] !== 'validate') {
  93. return true;
  94. }
  95. $this->prepInput($Model, $Model->data); //direction is from interface to database
  96. return true;
  97. }
  98. public function beforeSave(Model $Model, $options = array()) {
  99. if ($this->config[$Model->alias]['before'] !== 'save') {
  100. return true;
  101. }
  102. $this->prepInput($Model, $Model->data); //direction is from interface to database
  103. return true;
  104. }
  105. public function afterFind(Model $Model, $results, $primary = false) {
  106. if (!$this->config[$Model->alias]['output'] || empty($results)) {
  107. return $results;
  108. }
  109. $results = $this->prepOutput($Model, $results); //direction is from database to interface
  110. return $results;
  111. }
  112. /**
  113. * @param array $results (by reference)
  114. * @return void
  115. */
  116. public function prepInput(Model $Model, &$data) {
  117. foreach ($data[$Model->alias] as $key => $field) {
  118. if (in_array($key, $this->config[$Model->alias]['fields'])) {
  119. $data[$Model->alias][$key] = $this->formatInputOutput($Model, $field, 'in');
  120. }
  121. }
  122. }
  123. /**
  124. * @param array $results
  125. * @return array results
  126. */
  127. public function prepOutput(Model $Model, $data) {
  128. foreach ($data as $datakey => $record) {
  129. if (!isset($record[$Model->alias])) {
  130. return $data;
  131. }
  132. foreach ($record[$Model->alias] as $key => $value) {
  133. if (in_array($key, $this->config[$Model->alias]['fields'])) {
  134. $data[$datakey][$Model->alias][$key] = $this->formatInputOutput($Model, $value, 'out');
  135. }
  136. }
  137. }
  138. return $data;
  139. }
  140. /**
  141. * Perform a single transformation
  142. *
  143. * @return string cleanedValue
  144. */
  145. public function formatInputOutput(Model $Model, $value, $dir = 'in') {
  146. $this->_setTransformations($Model, $dir);
  147. if ($dir === 'out') {
  148. if ($this->config[$Model->alias]['multiply']) {
  149. $value *= (float)(1 / $this->config[$Model->alias]['multiply']);
  150. }
  151. $value = str_replace($this->delimiterFromFormat, $this->delimiterBaseFormat, (string)$value);
  152. } else {
  153. $value = str_replace(' ', '', $value);
  154. $value = str_replace($this->delimiterFromFormat, $this->delimiterBaseFormat, $value);
  155. if (is_numeric($value)) {
  156. $value = (float)$value;
  157. if ($this->config[$Model->alias]['multiply']) {
  158. $value *= $this->config[$Model->alias]['multiply'];
  159. }
  160. }
  161. }
  162. return $value;
  163. }
  164. /**
  165. * Prep the transformation chars
  166. *
  167. * @return void
  168. */
  169. protected function _setTransformations(Model $Model, $dir) {
  170. $from = array();
  171. $base = array();
  172. $transform = $this->config[$Model->alias]['transform'];
  173. if (!empty($this->config[$Model->alias]['transformReverse'])) {
  174. $transform = $this->config[$Model->alias]['transformReverse'];
  175. } else {
  176. if ($dir === 'out') {
  177. $transform = array_reverse($transform, true);
  178. }
  179. }
  180. $first = true;
  181. foreach ($transform as $key => $value) {
  182. /*
  183. if ($first) {
  184. $from[] = $key;
  185. $base[] = '#';
  186. $key = '#';
  187. $first = false;
  188. }
  189. */
  190. $from[] = $key;
  191. $base[] = $value;
  192. }
  193. if ($dir === 'out') {
  194. $this->delimiterFromFormat = $base;
  195. $this->delimiterBaseFormat = $from;
  196. } else {
  197. $this->delimiterFromFormat = $from;
  198. $this->delimiterBaseFormat = $base;
  199. }
  200. }
  201. }