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:
17: /**
18: * DtypeJson
19: *
20: * @category Xoops\Core\Kernel\Dtype\DtypeJson
21: * @package Xoops\Core\Kernel
22: * @author Richard Griffith <richard@geekwright.com>
23: * @copyright 2015 XOOPS Project (http://xoops.org)
24: * @license GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
25: * @link http://xoops.org
26: */
27: class DtypeJson extends DtypeAbstract
28: {
29: /**
30: * getVar get variable prepared according to format
31: *
32: * @param XoopsObject $obj object containing variable
33: * @param string $key name of variable
34: * @param string $format Dtype::FORMAT_* constant indicating desired formatting
35: *
36: * @return mixed
37: */
38: public function getVar(XoopsObject $obj, $key, $format)
39: {
40: $value = $obj->vars[$key]['value'];
41: switch (strtolower($format)) {
42: case Dtype::FORMAT_NONE:
43: case 'n':
44: break;
45: default:
46: $decoded = json_decode($value, true);
47: $value = (false === $decoded) ? null : $decoded;
48: break;
49: }
50: return $value;
51: }
52:
53: /**
54: * cleanVar prepare variable for persistence
55: *
56: * @param XoopsObject $obj object containing variable
57: * @param string $key name of variable
58: *
59: * @return string|null
60: */
61: public function cleanVar(XoopsObject $obj, $key)
62: {
63: $value = $obj->vars[$key]['value'];
64: $value = ($value===null || $value==='' || $value===false) ? null : $value;
65: if ($value!==null && null === json_decode($value, true)) {
66: $value = json_encode($value, JSON_FORCE_OBJECT);
67: if ($value===false) {
68: \Xoops::getInstance()->logger()->warning(
69: sprintf('Failed to encode to JSON - %s', json_last_error_msg())
70: );
71: $value = null;
72: }
73: }
74: return $value;
75: }
76: }
77: