1: <?php
2: namespace NGS;
3:
4: require_once(__DIR__.'/Utils.php');
5: require_once(__DIR__.'/BigDecimal.php');
6:
7: 8: 9: 10: 11: 12: 13:
14: class Money extends \NGS\BigDecimal
15: {
16: 17: 18:
19: protected $value;
20:
21: protected $scale = 2;
22:
23: 24: 25: 26: 27:
28: public function __construct($value)
29: {
30: if ($value instanceof \NGS\BigDecimal) {
31: $this->setValue($value->value);
32: } else {
33: $this->setValue($value);
34: }
35: }
36:
37: 38: 39: 40: 41:
42: protected function setValue($value)
43: {
44: if ($value === null) {
45: throw new \InvalidArgumentException('BigDecimal value cannot be null');
46: }
47: elseif (is_string($value)) {
48: if (!filter_var($value, FILTER_VALIDATE_INT)
49: && !preg_match('/^[-+]?\\d+([.]\\d+)?$/u', $value)) {
50: throw new \InvalidArgumentException('Invalid characters in BigDecimal constructor string: '.$value);
51: }
52: $rounded = round((float)$value, $this->scale, PHP_ROUND_HALF_UP);
53: $this->value = bcadd($rounded, 0, $this->scale);
54: }
55: elseif (is_int($value)) {
56: $this->value = bcadd($value, 0, $this->scale);
57: }
58: elseif (is_float($value)) {
59: $rounded = round($value, $this->scale, PHP_ROUND_HALF_UP);
60: $this->value = bcadd($rounded, 0, $this->scale);
61: }
62: else {
63: throw new \InvalidArgumentException('Invalid type for BigDecimal value, type was: "'.Utils::getType($value).'"');
64: }
65: }
66:
67: 68: 69: 70: 71: 72: 73: 74:
75: public static function toArray(array $items, $allowNullValuesValues=false)
76: {
77: $results = array();
78: try {
79: foreach ($items as $key => $val) {
80: if ($allowNullValuesValues && $val===null) {
81: $results[] = null;
82: } elseif ($val === null) {
83: throw new \InvalidArgumentException('Null value found in provided array');
84: } elseif (!$val instanceof \NGS\Money) {
85: $results[] = new \NGS\Money($val);
86: } else {
87: $results[] = $val;
88: }
89: }
90: }
91: catch(\Exception $e) {
92: throw new \InvalidArgumentException('Element at index '.$key.' could not be converted to BigDecimal!', 42, $e);
93: }
94: return $results;
95: }
96: }
97: