-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Data.php
69 lines (60 loc) · 1.42 KB
/
Data.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
/**
*
*/
namespace Valar\Plugin;
use Mvc5\Exception;
use Mvc5\Plugin\GlobalVar;
use Mvc5\Plugin\ScopedCall;
use Mvc5\Plugin\Shared;
use function json_decode;
use function json_last_error;
use function json_last_error_msg;
use function strpos;
use const Mvc5\{ BODY, HEADERS };
final class Data
extends Shared
{
/**
* @param string $name
*/
function __construct(string $name = 'data')
{
parent::__construct($name, new ScopedCall($this));
}
/**
* @param string $body
* @return mixed
* @throws \Throwable
*/
static function decode(string $body) : array
{
return static::result(json_decode($body, true));
}
/**
* @param null|string $type
* @return bool
*/
static function isJson(?string $type) : bool
{
return $type && (false !== strpos($type, '/json') || false !== strpos($type, '+json'));
}
/**
* @param $result
* @return array
* @throws \Throwable
*/
static function result($result) : array
{
return JSON_ERROR_NONE === json_last_error() ? $result :
Exception::invalidArgument('JSON Decode Error: ' . json_last_error_msg());
}
/**
* @return \Closure
*/
function __invoke() : \Closure
{
return fn() => Data::isJson($this[HEADERS]['content-type']) ?
Data::decode((string) $this[BODY]) : new GlobalVar('_POST');
}
}