1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Koded package. |
5
|
|
|
* |
6
|
|
|
* (c) Mihail Binev <[email protected]> |
7
|
|
|
* |
8
|
|
|
* Please view the LICENSE distributed with this source code |
9
|
|
|
* for the full copyright and license information. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Koded\Stdlib\Serializer; |
13
|
|
|
|
14
|
|
|
use Koded\Exceptions\SerializerException; |
15
|
|
|
use Koded\Stdlib\Serializer; |
16
|
|
|
use function extension_loaded; |
17
|
|
|
use function is_a; |
18
|
|
|
|
19
|
|
|
final class SerializerFactory |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* Factory that creates a new instance of Serializer. |
23
|
|
|
* |
24
|
|
|
* @param string $name The name of the supported serializer. |
25
|
|
|
* Provide a FQCN for custom serializers |
26
|
|
|
* @param $args [optional] Optional arguments for the serializer class |
27
|
|
|
* |
28
|
|
|
* @return Serializer |
29
|
|
|
* @throws SerializerException |
30
|
|
|
*/ |
31
|
2 |
|
public static function new(string $name, ...$args): Serializer |
32
|
|
|
{ |
33
|
|
|
switch ($name) { |
34
|
|
|
case Serializer::JSON: |
35
|
2 |
|
return new JsonSerializer(...$args); |
|
|
|
|
36
|
|
|
|
37
|
|
|
case Serializer::PHP: |
38
|
1 |
|
return new PhpSerializer; |
39
|
|
|
|
40
|
|
|
case Serializer::XML: |
41
|
2 |
|
empty($args) && $args = [null]; |
42
|
2 |
|
return new XmlSerializer(...$args); |
|
|
|
|
43
|
|
|
|
44
|
|
|
case Serializer::IGBINARY: |
45
|
|
|
// @codeCoverageIgnoreStart |
46
|
|
|
if (false === extension_loaded('igbinary')) { |
47
|
|
|
throw SerializerException::forMissingModule(Serializer::MSGPACK); |
48
|
|
|
} |
49
|
|
|
return new IgbinarySerializer; |
50
|
|
|
// @codeCoverageIgnoreEnd |
51
|
|
|
|
52
|
|
|
case Serializer::MSGPACK: |
53
|
|
|
// @codeCoverageIgnoreStart |
54
|
|
|
if (false === extension_loaded('msgpack')) { |
55
|
|
|
throw SerializerException::forMissingModule(Serializer::MSGPACK); |
56
|
|
|
} |
57
|
|
|
return new MsgpackSerializer; |
58
|
|
|
// @codeCoverageIgnoreEnd |
59
|
|
|
} |
60
|
2 |
|
if (is_a($name, Serializer::class, true)) { |
61
|
1 |
|
return new $name(...$args); |
62
|
|
|
} |
63
|
1 |
|
throw SerializerException::forCreateSerializer($name); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|