94d2da8bd5770a2fd4ddc5e85aefebb33063bbcb
[Packages/TYPO3.CMS.git] / typo3 / sysext / form / Classes / Domain / Filter / CurrencyFilter.php
1 <?php
2 namespace TYPO3\CMS\Form\Domain\Filter;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 /**
18 * Currency filter
19 */
20 class CurrencyFilter extends AbstractFilter implements FilterInterface
21 {
22 /**
23 * Separator between group of thousands
24 * Mostly dot, comma or whitespace
25 *
26 * @var string
27 */
28 protected $decimalsPoint;
29
30 /**
31 * Separator between group of thousands
32 * Mostly dot, comma or whitespace
33 *
34 * @var string
35 */
36 protected $thousandSeparator;
37
38 /**
39 * Constructor
40 *
41 * @param array $arguments Filter configuration
42 */
43 public function __construct($arguments = array())
44 {
45 $this->setDecimalsPoint($arguments['decimalPoint']);
46 $this->setThousandSeparator($arguments['thousandSeparator']);
47 }
48
49 /**
50 * Set the decimal point character
51 *
52 * @param string $decimalsPoint Character used for decimal point
53 * @return void
54 */
55 public function setDecimalsPoint($decimalsPoint = '.')
56 {
57 if (empty($decimalsPoint)) {
58 $this->decimalsPoint = '.';
59 } else {
60 $this->decimalsPoint = (string)$decimalsPoint;
61 }
62 }
63
64 /**
65 * Set the thousand separator character
66 *
67 * @param string $thousandSeparator Character used for thousand separator
68 * @return void
69 */
70 public function setThousandSeparator($thousandSeparator = ',')
71 {
72 if (empty($thousandSeparator)) {
73 $this->thousandSeparator = ',';
74 } elseif ($thousandSeparator === 'space') {
75 $this->thousandSeparator = ' ';
76 } elseif ($thousandSeparator === 'none') {
77 $this->thousandSeparator = '';
78 } else {
79 $this->thousandSeparator = (string)$thousandSeparator;
80 }
81 }
82
83 /**
84 * Change to float with 2 decimals
85 * Change the dot to comma if requested
86 *
87 * @param string $value
88 * @return string
89 */
90 public function filter($value)
91 {
92 $value = str_replace(
93 array(
94 $this->thousandSeparator,
95 $this->decimalsPoint,
96 ),
97 array(
98 '',
99 '.'
100 ),
101 (string)$value
102 );
103
104 // replace all non numeric characters, decimalPoint and negativ sign
105 $value = preg_replace("/[^0-9.-]/", "", $value);
106 $value = (double)$value;
107 return number_format($value, 2, $this->decimalsPoint, $this->thousandSeparator);
108 }
109 }