Completed
Push — master ( 4ee78f...ce1053 )
by Damian
14:52 queued 39s
created

CurrencyField::getSchemaValidation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\Forms;
4
5
use SilverStripe\ORM\FieldType\DBCurrency;
6
7
/**
8
 * Renders a text field, validating its input as a currency.
9
 * Limited to US-centric formats, including a hardcoded currency
10
 * symbol and decimal separators.
11
 * See {@link MoneyField} for a more flexible implementation.
12
 *
13
 * @todo Add localization support, see http://open.silverstripe.com/ticket/2931
14
 */
15
class CurrencyField extends TextField {
16
	/**
17
	 * allows the value to be set. removes the first character
18
	 * if it is not a number (probably a currency symbol)
19
	 *
20
	 * @param mixed $val
21
	 * @return $this
22
	 */
23
	public function setValue($val) {
24
		if(!$val) $val = 0.00;
25
		$this->value = DBCurrency::config()->get('currency_symbol')
26
			. number_format((double)preg_replace('/[^0-9.\-]/', '', $val), 2);
27
		return $this;
28
	}
29
	/**
30
	 * Overwrite the datavalue before saving to the db ;-)
31
	 * return 0.00 if no value, or value is non-numeric
32
	 */
33
	public function dataValue() {
34
		if($this->value) {
35
			return preg_replace('/[^0-9.\-]/','', $this->value);
36
		} else {
37
			return 0.00;
38
		}
39
	}
40
41
	public function Type() {
42
		return 'currency text';
43
	}
44
45
	/**
46
	 * Create a new class for this field
47
	 */
48
	public function performReadonlyTransformation() {
49
		return $this->castedCopy('SilverStripe\\Forms\\CurrencyField_Readonly');
50
	}
51
52
	public function validate($validator) {
53
        $currencySymbol = preg_quote(DBCurrency::config()->get('currency_symbol'));
54
        $regex = '/^\s*(\-?'.$currencySymbol.'?|'.$currencySymbol.'\-?)?(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?\s*$/';
55
		if (!empty($this->value) && !preg_match($regex, $this->value)) {
56
			$validator->validationError(
57
				$this->name,
58
				_t('Form.VALIDCURRENCY', "Please enter a valid currency"),
59
				"validation"
60
			);
61
			return false;
62
		}
63
		return true;
64
	}
65
66
	public function getSchemaValidation() {
67
		$rules = parent::getSchemaValidation();
68
		$rules['currency'] = true;
69
		return $rules;
70
	}
71
}
72