Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
converter.php
1<?php
2
4
6
7final class Converter
8{
9 const TO_SNAKE = 0x00001;
10 const TO_CAMEL = 0x00002;
11 const TO_SNAKE_DIGIT = 0x00004;
12 const TO_UPPER = 0x00010;
13 const TO_LOWER = 0x00020;
14 const LC_FIRST = 0x00100;
15 const UC_FIRST = 0x00200;
16 const KEYS = 0x01000;
17 const VALUES = 0x02000;
18 const RECURSIVE = 0x04000;
19
20 const OUTPUT_JSON_FORMAT = self::KEYS | self::RECURSIVE | self::TO_CAMEL | self::LC_FIRST;
21
22 private $format;
23
24 public function __construct($format)
25 {
26 $this->setFormat($format);
27 }
28
29 public static function toJson()
30 {
31 return new self(self::OUTPUT_JSON_FORMAT);
32 }
33
34 public function process($data)
35 {
36 if (!$data)
37 {
38 return $data;
39 }
40
41 if (is_string($data))
42 {
43 return $this->formatString($data);
44 }
45
46 if (is_array($data))
47 {
48 return $this->formatArray($data);
49 }
50
51 return $data;
52 }
53
54 protected function formatArray(array $array)
55 {
56 $newData = [];
57 foreach ($array as $key => $item)
58 {
59 $itemConverted = false;
60 if ($this->format & self::VALUES)
61 {
62 if (($this->format & self::RECURSIVE) && is_array($item))
63 {
64 $item = $this->process($item);
65 }
66 elseif (is_string($item))
67 {
68 $item = $this->formatString($item);
69 }
70
71 $itemConverted = true;
72 }
73
74 if ($this->format & self::KEYS)
75 {
76 if (!is_int($key))
77 {
78 $key = $this->formatString($key);
79 }
80
81 if (($this->format & self::RECURSIVE) && is_array($item) && !$itemConverted)
82 {
83 $item = $this->formatArray($item);
84 }
85 }
86
87 $newData[$key] = $item;
88 }
89
90 return $newData;
91 }
92
93 protected function formatString($string)
94 {
95 if ($this->format & self::TO_SNAKE)
96 {
97 $string = StringHelper::camel2snake($string);
98 }
99
100 if ($this->format & self::TO_SNAKE_DIGIT)
101 {
102 $string = preg_replace('/(\d+)([A-Za-z])/', '$1_$2', $string);
103 $string = preg_replace('/([A-Za-z])(\d)/', '$1_$2', $string);
104 $string = preg_replace('/([^_])([A-Z])/', '$1_$2', $string);
105 $string = mb_strtolower($string);
106 }
107
108 if ($this->format & self::TO_CAMEL)
109 {
110 $string = StringHelper::snake2camel($string);
111 }
112
113 if ($this->format & self::TO_LOWER)
114 {
115 $string = mb_strtolower($string);
116 }
117
118 if ($this->format & self::TO_UPPER)
119 {
120 $string = mb_strtoupper($string);
121 }
122
123 if ($this->format & self::UC_FIRST)
124 {
125 $string = ucfirst($string);
126 }
127
128 if ($this->format & self::LC_FIRST)
129 {
130 $string = lcfirst($string);
131 }
132
133
134 return $string;
135 }
136
137 public function getFormat()
138 {
139 return $this->format;
140 }
141
142 public function setFormat($format)
143 {
144 $this->format = $format;
145
146 return $this;
147 }
148}