1: <?php
2: /*
3: You may not change or alter any portion of this comment or credits
4: of supporting developers from this source code or any supporting source code
5: which is considered copyrighted (c) material of the original comment or credit authors.
6:
7: This program is distributed in the hope that it will be useful,
8: but WITHOUT ANY WARRANTY; without even the implied warranty of
9: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10: */
11:
12: namespace Xoops\Core\Kernel\Dtype;
13:
14: use Xoops\Core\Kernel\XoopsObject;
15: use Xoops\Core\Kernel\Dtype;
16: use Money\Money;
17: use Money\Currency;
18:
19: /**
20: * DtypeMoney
21: *
22: * @category Xoops\Core\Kernel\Dtype\DtypeMoney
23: * @package Xoops\Core\Kernel
24: * @author Richard Griffith <richard@geekwright.com>
25: * @copyright 2015 XOOPS Project (http://xoops.org)
26: * @license GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
27: * @link http://xoops.org
28: */
29: class DtypeMoney extends DtypeAbstract
30: {
31: /**
32: * getVar get variable prepared according to format
33: *
34: * Recommended database column is varchar(32) or larger
35: *
36: * @param XoopsObject $obj object containing variable
37: * @param string $key name of variable
38: * @param string $format Dtype::FORMAT_* constant indicating desired formatting
39: *
40: * @return mixed
41: */
42: public function getVar(XoopsObject $obj, $key, $format)
43: {
44: $storedValue = $obj->vars[$key]['value'];
45: switch (strtolower($format)) {
46: case Dtype::FORMAT_NONE:
47: case 'n':
48: case 's':
49: case Dtype::FORMAT_SHOW:
50: default:
51: $value = $this->unserializeJson($storedValue);
52: break;
53: }
54: return $value;
55: }
56:
57: /**
58: * cleanVar prepare variable for persistence
59: *
60: * @param XoopsObject $obj object containing variable
61: * @param string $key name of variable
62: *
63: * @return string|null
64: */
65: public function cleanVar(XoopsObject $obj, $key)
66: {
67: $value = $obj->vars[$key]['value'];
68: return ($value instanceof Money) ? $this->serializeAsJson($value) : $value;
69: }
70:
71: /**
72: * Serialize Money data to JSON string
73: *
74: * @param Money $value Money object to serialize as json
75: *
76: * @return string json encoded data to un
77: */
78: private function serializeAsJson(Money $value)
79: {
80: return json_encode(
81: [
82: 'a' => $value->getAmount(),
83: 'c' => $value->getCurrency()->getName()
84: ]
85: );
86: }
87:
88: /**
89: * unserializeJson unserialize JSON string to Money
90: *
91: * @param string $value JSON serialized money data
92: *
93: * @return Money|null
94: */
95: private function unserializeJson($value)
96: {
97: $decoded = json_decode($value, true);
98: if (false === $decoded || !(isset($decoded['a']) && isset($decoded['c']))) {
99: return null;
100: }
101: return new Money((int) $decoded['a'], new Currency($decoded['c']));
102: }
103: }
104: