-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Serializer.php
376 lines (324 loc) · 11.2 KB
/
Serializer.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
<?php
/**
* @author Marwan Al-Soltany <[email protected]>
* @copyright Marwan Al-Soltany 2020
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace MAKS\AmqpAgent\Helper;
use Exception;
use Closure;
use MAKS\AmqpAgent\Exception\SerializerViolationException;
/**
* A flexible serializer to be used in conjunction with the workers.
* @since 1.0.0
*/
class Serializer
{
/**
* The JSON serialization type constant.
* @var string
*/
public const TYPE_JSON = 'JSON';
/**
* The PHP serialization type constant.
* @var string
*/
public const TYPE_PHP = 'PHP';
/**
* The default data the serializer works with if none was provided.
* @var null
*/
public const DEFAULT_DATA = null;
/**
* The default type the serializer works with if none was provided.
* @var string
*/
public const DEFAULT_TYPE = self::TYPE_JSON;
/**
* The default strict value the serializer works with if none was provided.
* @var bool
*/
public const DEFAULT_STRICT = true;
/**
* The supported serialization types.
* @var array
*/
protected const SUPPORTED_TYPES = [self::TYPE_JSON, self::TYPE_PHP];
/**
* The current data the serializer has.
* @var mixed
*/
protected $data;
/**
* The current type the serializer uses.
* @var string
*/
protected $type;
/**
* The current strict value the serializer works with.
* @var bool
*/
protected $strict;
/**
* The result of the last (un)serialization operation.
* @var mixed
*/
protected $result;
/**
* Serializer object constructor.
* @param mixed $data [optional] The data to (un)serialize. Defaults to null.
* @param string|null $type [optional] The type of (un)serialization. Defaults to JSON.
* @param bool $strict [optional] Whether or not to assert that no errors have occurred while executing (un)serialization functions. Defaults to true.
* @throws SerializerViolationException
*/
public function __construct($data = null, ?string $type = null, ?bool $strict = null)
{
$this->setData($data ?? self::DEFAULT_DATA);
$this->setType($type ?? self::DEFAULT_TYPE);
$this->setStrict($strict ?? self::DEFAULT_STRICT);
}
/**
* Executes when calling the class like a function.
* @param mixed $data The data to (un)serialize.
* @param string|null $type [optional] The type of (un)serialization. Defaults to JSON.
* @param bool $strict [optional] Whether or not to assert that no errors have occurred while executing (un)serialization functions. Defaults to true.
* @return mixed Serialized or unserialized data depending on the passed parameters.
* @throws SerializerViolationException
*/
public function __invoke($data, ?string $type = self::DEFAULT_TYPE, ?bool $strict = self::DEFAULT_STRICT)
{
$this->setData($data);
$this->setType($type ?? self::DEFAULT_TYPE);
$this->setStrict($strict ?? self::DEFAULT_STRICT);
try {
$this->result = is_string($data) ? $this->unserialize() : $this->serialize();
} catch (Exception $error) {
$dataType = gettype($data);
throw new SerializerViolationException(
sprintf(
'The data passed to the serializer (data-type: %s) could not be processed!',
$dataType
),
(int)$error->getCode(),
$error
);
}
return $this->result;
}
/**
* Serializes the passed or registered data. When no parameters are passed, it uses the registered ones.
* @param mixed $data [optional] The data to serialize.
* @param string|null $type [optional] The type of serialization.
* @param bool $strict [optional] Whether or not to assert that no errors have occurred while executing serialization functions.
* @return string|null A serialized representation of the passed or registered data or null on failure.
* @throws SerializerViolationException
*/
public function serialize($data = null, ?string $type = null, ?bool $strict = null): string
{
if (null !== $data) {
$this->setData($data);
}
if (null !== $type) {
$this->setType($type);
}
if (null !== $strict) {
$this->setStrict($strict);
}
if (self::TYPE_PHP === $this->type) {
$this->assertNoPhpSerializationError(function () {
$this->result = serialize($this->data);
});
}
if (self::TYPE_JSON === $this->type) {
$this->assertNoJsonSerializationError(function () {
$this->result = json_encode($this->data);
});
}
return $this->result;
}
/**
* Unserializes the passed or registered data. When no parameters are passed, it uses the registered ones.
* @param string|null $data [optional] The data to unserialize.
* @param string|null $type [optional] The type of unserialization.
* @param bool $strict [optional] Whether or not to assert that no errors have occurred while executing unserialization functions.
* @return mixed A PHP type on success or false or null on failure.
* @throws SerializerViolationException
*/
public function unserialize(?string $data = null, ?string $type = null, ?bool $strict = null)
{
if (null !== $data) {
$this->setData($data);
}
if (null !== $type) {
$this->setType($type);
}
if (null !== $strict) {
$this->setStrict($strict);
}
if (self::TYPE_PHP === $this->type) {
$this->assertNoPhpSerializationError(function () {
$this->result = unserialize($this->data);
});
}
if (self::TYPE_JSON === $this->type) {
$this->assertNoJsonSerializationError(function () {
$this->result = json_decode($this->data, true);
});
}
return $this->result;
}
/**
* Deserializes the passed or registered data. When no parameters are passed, it uses the registered ones.
* @since 1.2.2 Alias for `self::unserialize()`.
* @param string|null $data [optional] The data to unserialize.
* @param string|null $type [optional] The type of unserialization.
* @param bool $strict [optional] Whether or not to assert that no errors have occurred while executing unserialization functions.
* @return mixed A PHP type on success or false or null on failure.
* @throws SerializerViolationException
*/
public function deserialize(?string $data = null, ?string $type = null, ?bool $strict = null)
{
return $this->unserialize($data, $type, $strict);
}
/**
* Registers the passed data in the object.
* @param mixed $data The data wished to be registered.
* @return self
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
/**
* Returns the currently registered data.
* @return mixed
*/
public function getData()
{
return $this->data;
}
/**
* Registers the passed type in the object.
* @param string $type The type wished to be registered.
* @return self
* @throws SerializerViolationException
*/
public function setType(string $type)
{
$type = strtoupper($type);
if (!in_array($type, static::SUPPORTED_TYPES)) {
throw new SerializerViolationException(
sprintf(
'"%s" is unsupported (un)serialization type. Supported types are: [%s]!',
$type,
implode(', ', static::SUPPORTED_TYPES)
)
);
}
$this->type = $type;
return $this;
}
/**
* Returns the currently registered type.
* @return string
*/
public function getType(): string
{
return $this->type;
}
/**
* Registers the passed strict value in the object.
* @since 1.2.2
* @param bool $strict The strict value wished to be registered.
* @return self
*/
public function setStrict(bool $strict)
{
$this->strict = $strict;
return $this;
}
/**
* Returns the currently registered strict value.
* @since 1.2.2
* @return bool
*/
public function isStrict()
{
return $this->strict;
}
/**
* Alias for `self::serialize()` that does not accept any parameters (works with currently registered parameters).
* @return string The serialized data.
* @throws SerializerViolationException
*/
public function getSerialized(): string
{
return $this->serialize();
}
/**
* Alias for `self::unserialize()` that does not accept any parameters (works with currently registered parameters).
* @return mixed The unserialized data.
* @throws SerializerViolationException
*/
public function getUnserialized()
{
return $this->unserialize();
}
/**
* Asserts that `serialize()` and/or `unserialize()` was executed successfully depending on strictness of the Serializer.
* @since 1.2.2
* @param Closure $callback The (un)serialization callback to execute.
* @return void
* @throws SerializerViolationException
*/
protected function assertNoPhpSerializationError(Closure $callback): void
{
$this->result = null;
try {
$callback();
} catch (Exception $error) {
if ($this->strict) {
throw new SerializerViolationException(
sprintf(
'An error occurred while executing serialize() or unserialize(): %s',
(string)$error->getMessage()
),
(int)$error->getCode(),
$error
);
}
}
}
/**
* Asserts that `json_encode()` and/or `json_decode()` was executed successfully depending on strictness of the Serializer.
* @since 1.2.2
* @param Closure $callback The (un)serialization callback to execute.
* @return void
* @throws SerializerViolationException
*/
protected function assertNoJsonSerializationError(Closure $callback): void
{
$this->result = null;
try {
$callback();
} catch (Exception $error) {
// JSON functions do not throw exceptions on PHP < v7.3.0
// The code down below takes care of throwing the exception.
}
if ($this->strict) {
$errorCode = json_last_error();
if ($errorCode !== JSON_ERROR_NONE) {
$errorMessage = json_last_error_msg();
throw new SerializerViolationException(
sprintf(
'An error occurred while executing json_encode() or json_decode(): %s',
$errorMessage
)
);
}
}
}
}