1
|
<?php
|
2
|
|
3
|
namespace Illuminate\Http;
|
4
|
|
5
|
use JsonSerializable;
|
6
|
use InvalidArgumentException;
|
7
|
use Illuminate\Contracts\Support\Jsonable;
|
8
|
use Illuminate\Contracts\Support\Arrayable;
|
9
|
use Symfony\Component\HttpFoundation\JsonResponse as BaseJsonResponse;
|
10
|
|
11
|
class JsonResponse extends BaseJsonResponse
|
12
|
{
|
13
|
use ResponseTrait;
|
14
|
|
15
|
/**
|
16
|
* Constructor.
|
17
|
*
|
18
|
* @param mixed $data
|
19
|
* @param int $status
|
20
|
* @param array $headers
|
21
|
* @param int $options
|
22
|
*/
|
23
|
public function __construct($data = null, $status = 200, $headers = [], $options = 0)
|
24
|
{
|
25
|
$this->encodingOptions = $options;
|
26
|
|
27
|
parent::__construct($data, $status, $headers);
|
28
|
}
|
29
|
|
30
|
/**
|
31
|
* Get the json_decoded data from the response.
|
32
|
*
|
33
|
* @param bool $assoc
|
34
|
* @param int $depth
|
35
|
* @return mixed
|
36
|
*/
|
37
|
public function getData($assoc = false, $depth = 512)
|
38
|
{
|
39
|
return json_decode($this->data, $assoc, $depth);
|
40
|
}
|
41
|
|
42
|
/**
|
43
|
* {@inheritdoc}
|
44
|
*/
|
45
|
public function setData($data = [])
|
46
|
{
|
47
|
if ($data instanceof Arrayable) {
|
48
|
$this->data = json_encode($data->toArray(), $this->encodingOptions);
|
49
|
} elseif ($data instanceof Jsonable) {
|
50
|
$this->data = $data->toJson($this->encodingOptions);
|
51
|
} elseif ($data instanceof JsonSerializable) {
|
52
|
$this->data = json_encode($data->jsonSerialize(), $this->encodingOptions);
|
53
|
} else {
|
54
|
$this->data = json_encode($data, $this->encodingOptions);
|
55
|
}
|
56
|
|
57
|
if (JSON_ERROR_NONE !== json_last_error()) {
|
58
|
throw new InvalidArgumentException(json_last_error_msg());
|
59
|
}
|
60
|
|
61
|
return $this->update();
|
62
|
}
|
63
|
|
64
|
/**
|
65
|
* Get the JSON encoding options.
|
66
|
*
|
67
|
* @return int
|
68
|
*/
|
69
|
public function getJsonOptions()
|
70
|
{
|
71
|
return $this->getEncodingOptions();
|
72
|
}
|
73
|
|
74
|
/**
|
75
|
* {@inheritdoc}
|
76
|
*/
|
77
|
public function setEncodingOptions($encodingOptions)
|
78
|
{
|
79
|
return $this->setJsonOptions($encodingOptions);
|
80
|
}
|
81
|
|
82
|
/**
|
83
|
* Set the JSON encoding options.
|
84
|
*
|
85
|
* @param int $options
|
86
|
* @return mixed
|
87
|
*/
|
88
|
public function setJsonOptions($options)
|
89
|
{
|
90
|
$this->encodingOptions = (int) $options;
|
91
|
|
92
|
return $this->setData($this->getData());
|
93
|
}
|
94
|
}
|