1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Jaxon\Plugin\Response\DataBag; |
4
|
|
|
|
5
|
|
|
use Jaxon\Di\Container; |
6
|
|
|
use Jaxon\Plugin\AbstractResponsePlugin; |
7
|
|
|
|
8
|
|
|
use function is_array; |
9
|
|
|
use function is_string; |
10
|
|
|
use function json_decode; |
11
|
|
|
|
12
|
|
|
class DataBagPlugin extends AbstractResponsePlugin |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @const The plugin name |
16
|
|
|
*/ |
17
|
|
|
const NAME = 'bags'; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var Container |
21
|
|
|
*/ |
22
|
|
|
protected $di; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var DataBag |
26
|
|
|
*/ |
27
|
|
|
protected $xDataBag = null; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* The constructor |
31
|
|
|
*/ |
32
|
|
|
public function __construct(Container $di) |
33
|
|
|
{ |
34
|
|
|
$this->di = $di; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @return void |
39
|
|
|
*/ |
40
|
|
|
private function initDataBag() |
41
|
|
|
{ |
42
|
|
|
if($this->xDataBag !== null) |
43
|
|
|
{ |
44
|
|
|
return; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
// Get the databag contents from the HTTP request parameters. |
48
|
|
|
$xRequest = $this->di->getRequest(); |
49
|
|
|
$aBody = $xRequest->getParsedBody(); |
50
|
|
|
$aParams = $xRequest->getQueryParams(); |
51
|
|
|
$aData = is_array($aBody) ? |
52
|
|
|
$this->readData($aBody['jxnbags'] ?? []) : |
53
|
|
|
$this->readData($aParams['jxnbags'] ?? []); |
54
|
|
|
$this->xDataBag = new DataBag($this, $aData); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @inheritDoc |
59
|
|
|
*/ |
60
|
|
|
public function getName(): string |
61
|
|
|
{ |
62
|
|
|
return self::NAME; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param mixed $xData |
67
|
|
|
* |
68
|
|
|
* @return array |
69
|
|
|
*/ |
70
|
|
|
private function readData($xData): array |
71
|
|
|
{ |
72
|
|
|
// Todo: clean input data. |
73
|
|
|
return is_string($xData) ? |
74
|
|
|
(json_decode($xData, true) ?: []) : |
75
|
|
|
(is_array($xData) ? $xData : []); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @inheritDoc |
80
|
|
|
*/ |
81
|
|
|
public function getHash(): string |
82
|
|
|
{ |
83
|
|
|
// Use the version number as hash |
84
|
|
|
return '4.0.0'; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
/** |
88
|
|
|
* @return void |
89
|
|
|
*/ |
90
|
|
|
public function writeCommand() |
91
|
|
|
{ |
92
|
|
|
$this->initDataBag(); |
93
|
|
|
if($this->xDataBag->touched()) |
94
|
|
|
{ |
95
|
|
|
$this->addCommand('databag.set', ['values' => $this->xDataBag]); |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|
99
|
|
|
/** |
100
|
|
|
* @param string $sName |
101
|
|
|
* |
102
|
|
|
* @return DataBagContext |
103
|
|
|
*/ |
104
|
|
|
public function bag(string $sName): DataBagContext |
105
|
|
|
{ |
106
|
|
|
$this->initDataBag(); |
107
|
|
|
return new DataBagContext($this->xDataBag, $sName); |
108
|
|
|
} |
109
|
|
|
} |
110
|
|
|
|