Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
json.php
1<?php
2
4
5
9
11{
12 protected $data;
13 protected $jsonEncodingOptions = 0;
14
15 public function __construct($data = null, $options = 0)
16 {
17 parent::__construct();
18
19 $this->jsonEncodingOptions = $options;
20 $this->setData($data);
21 }
22
23 public function setData($data)
24 {
25 //todo It's a crutch. While we are supporting php 5.3 we have to keep this code.
26 //When minimal version is php 5.5 we can implement JsonSerializable in DateTime, Uri and remove this code.
27 $data = $this->processData($data);
28
29 if ($data instanceof \JsonSerializable)
30 {
31 $this->data = Main\Web\Json::encode($data->jsonSerialize(), $this->jsonEncodingOptions);
32 }
33 elseif ($data instanceof Contract\Jsonable)
34 {
35 $this->data = $data->toJson($this->jsonEncodingOptions);
36 }
37 elseif ($data instanceof Contract\Arrayable)
38 {
39 $this->data = Main\Web\Json::encode($data->toArray(), $this->jsonEncodingOptions);
40 }
41 else
42 {
43 $this->data = Main\Web\Json::encode($data, $this->jsonEncodingOptions);
44 }
45
46 return $this->setContent($this->data);
47 }
48
49 private function processData($data)
50 {
51 if ($data instanceof \JsonSerializable)
52 {
53 $data = $data->jsonSerialize();
54 }
55 elseif ($data instanceof Contract\Jsonable)
56 {
57 $data = $data->toJson($this->jsonEncodingOptions);
58 }
59 elseif ($data instanceof Contract\Arrayable)
60 {
61 $data = $data->toArray();
62 }
63
64 if ($data instanceof DateTime)
65 {
66 return date('c' , $data->getTimestamp());
67 }
68
69 if ($data instanceof Main\Type\Date)
70 {
72 return date('c', makeTimeStamp($data, FORMAT_DATE) + date("Z"));
73 }
74
75 if ($data instanceof Main\Web\Uri)
76 {
77 return $data->getUri();
78 }
79
80 if ($data instanceof Main\UI\PageNavigation)
81 {
82 return array(
83 'currentPage' => $data->getCurrentPage(),
84 'pageSize' => $data->getPageSize(),
85 'recordCount' => $data->getRecordCount(),
86 );
87 }
88
89 if (is_array($data) || $data instanceof \Traversable)
90 {
91 foreach ($data as $key => $item)
92 {
93 $data[$key] = $this->processData($item);
94 }
95 }
96
97 return $data;
98 }
99
100 public function send()
101 {
102 $this->addHeader('Content-Type', 'application/json; charset=UTF-8');
103 parent::send();
104 }
105}
__construct($data=null, $options=0)
Definition json.php:15
addHeader($name, $value='')
setContent($content)
Definition response.php:31