NumberFormatBehavior.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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 http://opensource.org/licenses/mit-license.php MIT
  29. */
  30. class NumberFormatBehavior extends ModelBehavior {
  31. protected $_defaultConfig = array(
  32. 'before' => 'validate', // save or validate
  33. 'input' => true, // true = activated
  34. 'output' => false, // true = activated
  35. 'fields' => array( // add fields manually
  36. ),
  37. 'observedTypes' => array( // disable by passing an empty array
  38. 'float'
  39. ),
  40. 'localeconv' => false, // use system settings for decimals and thousands
  41. 'currency' => false, // would make localeconf use mon_ values or Configure use Currency
  42. // based on input (output other direction)
  43. 'multiply' => 0, // direction 'in' (inverted value automatically used for 'out')
  44. 'transform' => array( // transform mask
  45. '.' => '',
  46. ',' => '.',
  47. ),
  48. 'transformReverse' => array(),
  49. 'strict' => false, // do not losely convert anything (expects 100% correct input) and reduce converting errors
  50. );
  51. public $delimiterBaseFormat = array();
  52. public $delimiterFromFormat = array();
  53. /**
  54. * Adjust configs like: $Model->Behaviors-attach('Tools.NumberFormat', array('fields'=>array('xyz')))
  55. * leave fields empty to auto-detect all float inputs
  56. */
  57. public function setup(Model $Model, $config = array()) {
  58. $this->settings[$Model->alias] = $this->_defaultConfig;
  59. if (!empty($config['strict'])) {
  60. $this->settings[$Model->alias]['transform']['.'] = '#';
  61. }
  62. if ($this->settings[$Model->alias]['localeconv'] || !empty($config['localeconv'])) {
  63. // use locale settings
  64. $conv = localeconv();
  65. $loc = array(
  66. 'decimals' => $conv['decimal_point'],
  67. 'thousands' => $conv['thousands_sep']
  68. );
  69. } elseif ($configure = Configure::read('Localization')) {
  70. // use configure settings
  71. $loc = (array)$configure;
  72. }
  73. if (!empty($loc)) {
  74. $this->settings[$Model->alias]['transform'] = array(
  75. $loc['thousands'] => $this->settings[$Model->alias]['transform']['.'],
  76. $loc['decimals'] => $this->settings[$Model->alias]['transform'][','],
  77. );
  78. }
  79. $this->settings[$Model->alias] = $config + $this->settings[$Model->alias];
  80. $numberFields = array();
  81. $schema = $Model->schema();
  82. foreach ($schema as $key => $values) {
  83. if (isset($values['type']) && !in_array($key, $this->settings[$Model->alias]['fields']) && in_array($values['type'], $this->settings[$Model->alias]['observedTypes'])) {
  84. array_push($numberFields, $key);
  85. }
  86. }
  87. $this->settings[$Model->alias]['fields'] = array_merge($this->settings[$Model->alias]['fields'], $numberFields);
  88. }
  89. public function beforeValidate(Model $Model, $options = array()) {
  90. if ($this->settings[$Model->alias]['before'] !== 'validate') {
  91. return true;
  92. }
  93. $this->prepInput($Model, $Model->data); //direction is from interface to database
  94. return true;
  95. }
  96. public function beforeSave(Model $Model, $options = array()) {
  97. if ($this->settings[$Model->alias]['before'] !== 'save') {
  98. return true;
  99. }
  100. $this->prepInput($Model, $Model->data); //direction is from interface to database
  101. return true;
  102. }
  103. public function afterFind(Model $Model, $results, $primary = false) {
  104. if (!$this->settings[$Model->alias]['output'] || empty($results)) {
  105. return $results;
  106. }
  107. $results = $this->prepOutput($Model, $results); //direction is from database to interface
  108. return $results;
  109. }
  110. /**
  111. * @param array $results (by reference)
  112. * @return void
  113. */
  114. public function prepInput(Model $Model, &$data) {
  115. foreach ($data[$Model->alias] as $key => $field) {
  116. if (in_array($key, $this->settings[$Model->alias]['fields'])) {
  117. $data[$Model->alias][$key] = $this->formatInputOutput($Model, $field, 'in');
  118. }
  119. }
  120. }
  121. /**
  122. * @param array $results
  123. * @return array results
  124. */
  125. public function prepOutput(Model $Model, $data) {
  126. foreach ($data as $datakey => $record) {
  127. if (!isset($record[$Model->alias])) {
  128. return $data;
  129. }
  130. foreach ($record[$Model->alias] as $key => $value) {
  131. if (in_array($key, $this->settings[$Model->alias]['fields'])) {
  132. $data[$datakey][$Model->alias][$key] = $this->formatInputOutput($Model, $value, 'out');
  133. }
  134. }
  135. }
  136. return $data;
  137. }
  138. /**
  139. * Perform a single transformation
  140. *
  141. * @return string cleanedValue
  142. */
  143. public function formatInputOutput(Model $Model, $value, $dir = 'in') {
  144. $this->_setTransformations($Model, $dir);
  145. if ($dir === 'out') {
  146. if ($this->settings[$Model->alias]['multiply']) {
  147. $value *= (float)(1 / $this->settings[$Model->alias]['multiply']);
  148. }
  149. $value = str_replace($this->delimiterFromFormat, $this->delimiterBaseFormat, (string)$value);
  150. } else {
  151. $value = str_replace(' ', '', $value);
  152. $value = str_replace($this->delimiterFromFormat, $this->delimiterBaseFormat, $value);
  153. if (is_numeric($value)) {
  154. $value = (float)$value;
  155. if ($this->settings[$Model->alias]['multiply']) {
  156. $value *= $this->settings[$Model->alias]['multiply'];
  157. }
  158. }
  159. }
  160. return $value;
  161. }
  162. /**
  163. * Prep the transformation chars
  164. *
  165. * @return void
  166. */
  167. protected function _setTransformations(Model $Model, $dir) {
  168. $from = array();
  169. $base = array();
  170. $transform = $this->settings[$Model->alias]['transform'];
  171. if (!empty($this->settings[$Model->alias]['transformReverse'])) {
  172. $transform = $this->settings[$Model->alias]['transformReverse'];
  173. } else {
  174. if ($dir === 'out') {
  175. $transform = array_reverse($transform, true);
  176. }
  177. }
  178. $first = true;
  179. foreach ($transform as $key => $value) {
  180. /*
  181. if ($first) {
  182. $from[] = $key;
  183. $base[] = '#';
  184. $key = '#';
  185. $first = false;
  186. }
  187. */
  188. $from[] = $key;
  189. $base[] = $value;
  190. }
  191. if ($dir === 'out') {
  192. $this->delimiterFromFormat = $base;
  193. $this->delimiterBaseFormat = $from;
  194. } else {
  195. $this->delimiterFromFormat = $from;
  196. $this->delimiterBaseFormat = $base;
  197. }
  198. }
  199. }