-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathYamlSerializer.php
More file actions
56 lines (49 loc) · 1.95 KB
/
YamlSerializer.php
File metadata and controls
56 lines (49 loc) · 1.95 KB
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
<?php
namespace Thunder\Shortcode\Serializer;
use Symfony\Component\Yaml\Yaml;
use Thunder\Shortcode\Shortcode\Shortcode;
use Thunder\Shortcode\Shortcode\ShortcodeInterface;
/**
* @author Tomasz Kowalczyk <tomasz@kowalczyk.cc>
* @psalm-suppress ReservedWord
* @psalm-suppress InvalidReturnStatement
* @psalm-suppress InvalidReturnType
*/
final class YamlSerializer implements SerializerInterface
{
public function serialize(ShortcodeInterface $shortcode)
{
return Yaml::dump(array(
'name' => $shortcode->getName(),
'parameters' => $shortcode->getParameters(),
'content' => $shortcode->getContent(),
'bbCode' => $shortcode->getBbCode(),
));
}
/**
* @param string $text
*
* @return Shortcode
*/
public function unserialize($text)
{
/** @psalm-var array{name:string,parameters:array<string,string|null>,bbCode:string|null,content:string|null}|null $data */
$data = Yaml::parse($text);
if(!is_array($data)) {
throw new \InvalidArgumentException('Invalid YAML, cannot unserialize Shortcode!');
}
if (!array_intersect(array_keys($data), array('name', 'parameters', 'content'))) {
throw new \InvalidArgumentException('Malformed shortcode YAML, expected name, parameters, and content!');
}
/** @var string $name */
$name = array_key_exists('name', $data) ? $data['name'] : null;
$parameters = array_key_exists('parameters', $data) ? $data['parameters'] : array();
$content = array_key_exists('content', $data) ? $data['content'] : null;
$bbCode = array_key_exists('bbCode', $data) ? $data['bbCode'] : null;
/** @psalm-suppress DocblockTypeContradiction */
if(!is_array($parameters)) {
throw new \InvalidArgumentException('Parameters must be an array!');
}
return new Shortcode($name, $parameters, $content, $bbCode);
}
}