1
|
|
|
<?php |
2
|
|
|
namespace Thunder\Shortcode\Serializer; |
3
|
|
|
|
4
|
|
|
use Symfony\Component\Yaml\Yaml; |
5
|
|
|
use Thunder\Shortcode\Shortcode\Shortcode; |
6
|
|
|
use Thunder\Shortcode\Shortcode\ShortcodeInterface; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* @author Tomasz Kowalczyk <[email protected]> |
10
|
|
|
*/ |
11
|
|
View Code Duplication |
final class YamlSerializer implements SerializerInterface |
|
|
|
|
12
|
|
|
{ |
13
|
8 |
|
public function serialize(ShortcodeInterface $shortcode) |
14
|
|
|
{ |
15
|
8 |
|
return Yaml::dump(array( |
16
|
8 |
|
'name' => $shortcode->getName(), |
17
|
8 |
|
'parameters' => $shortcode->getParameters(), |
18
|
8 |
|
'content' => $shortcode->getContent(), |
19
|
8 |
|
'bbCode' => $shortcode->getBbCode(), |
20
|
8 |
|
)); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param string $text |
25
|
|
|
* |
26
|
|
|
* @return Shortcode |
27
|
|
|
*/ |
28
|
14 |
|
public function unserialize($text) |
29
|
|
|
{ |
30
|
|
|
/** @psalm-var array{name:string,parameters:array<string,string|null>,bbCode:string|null,content:string|null}|null $data */ |
31
|
14 |
|
$data = Yaml::parse($text); |
32
|
|
|
|
33
|
14 |
|
if(!is_array($data)) { |
34
|
1 |
|
throw new \InvalidArgumentException('Invalid YAML, cannot unserialize Shortcode!'); |
35
|
|
|
} |
36
|
13 |
|
if (!array_intersect(array_keys($data), array('name', 'parameters', 'content'))) { |
37
|
1 |
|
throw new \InvalidArgumentException('Malformed shortcode YAML, expected name, parameters, and content!'); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** @var string $name */ |
41
|
12 |
|
$name = array_key_exists('name', $data) ? $data['name'] : null; |
42
|
12 |
|
$parameters = array_key_exists('parameters', $data) ? $data['parameters'] : array(); |
43
|
12 |
|
$content = array_key_exists('content', $data) ? $data['content'] : null; |
44
|
12 |
|
$bbCode = array_key_exists('bbCode', $data) ? $data['bbCode'] : null; |
45
|
|
|
|
46
|
|
|
/** @psalm-suppress DocblockTypeContradiction */ |
47
|
12 |
|
if(!is_array($parameters)) { |
48
|
1 |
|
throw new \InvalidArgumentException('Parameters must be an array!'); |
49
|
|
|
} |
50
|
|
|
|
51
|
11 |
|
return new Shortcode($name, $parameters, $content, $bbCode); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.