Passed
Push — pulls/4.7/improve-stuff ( 4d54a2 )
by Robbie
10:00
created

src/ORM/FieldType/DBCurrency.php (2 issues)

1
<?php
2
3
namespace SilverStripe\ORM\FieldType;
4
5
use SilverStripe\Forms\CurrencyField;
6
7
/**
8
 * Represents a decimal field containing a currency amount.
9
 * The currency class only supports single currencies.  For multi-currency support, use {@link Money}
10
 *
11
 *
12
 * Example definition via {@link DataObject::$db}:
13
 * <code>
14
 * static $db = array(
15
 *  "Price" => "Currency",
16
 *  "Tax" => "Currency(5)",
17
 * );
18
 * </code>
19
 */
20
class DBCurrency extends DBDecimal
21
{
22
    /**
23
     * @config
24
     * @var string
25
     */
26
    private static $currency_symbol = '$';
27
28
    public function __construct($name = null, $wholeSize = 9, $decimalSize = 2, $defaultValue = 0)
29
    {
30
        parent::__construct($name, $wholeSize, $decimalSize, $defaultValue);
31
    }
32
33
    /**
34
     * Returns the number as a currency, eg “$1,000.00”.
35
     */
36
    public function Nice()
37
    {
38
        $val = $this->config()->currency_symbol . number_format(abs($this->value), 2);
0 ignored issues
show
Bug Best Practice introduced by
The property currency_symbol does not exist on SilverStripe\Core\Config\Config_ForClass. Since you implemented __get, consider adding a @property annotation.
Loading history...
39
        if ($this->value < 0) {
40
            return "($val)";
41
        }
42
43
        return $val;
44
    }
45
46
    /**
47
     * Returns the number as a whole-number currency, eg “$1,000”.
48
     */
49
    public function Whole()
50
    {
51
        $val = $this->config()->currency_symbol . number_format(abs($this->value), 0);
0 ignored issues
show
Bug Best Practice introduced by
The property currency_symbol does not exist on SilverStripe\Core\Config\Config_ForClass. Since you implemented __get, consider adding a @property annotation.
Loading history...
52
        if ($this->value < 0) {
53
            return "($val)";
54
        }
55
        return $val;
56
    }
57
58
    public function setValue($value, $record = null, $markChanged = true)
59
    {
60
        $matches = null;
61
        if (is_numeric($value)) {
62
            $this->value = $value;
63
        } elseif (preg_match('/-?\$?[0-9,]+(.[0-9]+)?([Ee][0-9]+)?/', $value, $matches)) {
64
            $this->value = str_replace(['$', ',', $this->config()->currency_symbol], '', $matches[0]);
65
        } else {
66
            $this->value = 0;
67
        }
68
69
        return $this;
70
    }
71
72
    /**
73
     * @param string $title
74
     * @param array $params
75
     *
76
     * @return CurrencyField
77
     */
78
    public function scaffoldFormField($title = null, $params = null)
79
    {
80
        return CurrencyField::create($this->getName(), $title);
81
    }
82
}
83