Passed
Push — main ( e16d46...16e3d2 )
by Damien
07:21
created

MediaSingle::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 17
c 0
b 0
f 0
rs 9.8333
cc 2
nc 2
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DH\Adf\Node\Block;
6
7
use DH\Adf\Builder\MediaBuilder;
8
use DH\Adf\Node\BlockNode;
9
use DH\Adf\Node\Child\Media;
10
use DH\Adf\Node\Node;
11
use InvalidArgumentException;
12
use JsonSerializable;
13
14
/**
15
 * @see https://developer.atlassian.com/cloud/jira/platform/apis/document/nodes/mediaSingle
16
 */
17
class MediaSingle extends BlockNode implements JsonSerializable
18
{
19
    use MediaBuilder;
20
21
    public const LAYOUT_WRAP_LEFT = 'wrap-left';
22
    public const LAYOUT_CENTER = 'center';
23
    public const LAYOUT_WRAP_RIGHT = 'wrap-right';
24
    public const LAYOUT_WIDE = 'wide';
25
    public const LAYOUT_FULL_WIDTH = 'full-width';
26
    public const LAYOUT_ALIGN_START = 'align-start';
27
    public const LAYOUT_ALIGN_END = 'align-end';
28
29
    protected string $type = 'mediaSingle';
30
    protected array $allowedContentTypes = [
31
        Media::class,
32
    ];
33
    private string $layout;
34
    private ?int $width;
35
36
    public function __construct(string $layout, ?int $width = null, ?BlockNode $parent = null)
37
    {
38
        if (!\in_array($layout, [
39
            self::LAYOUT_WRAP_LEFT,
40
            self::LAYOUT_CENTER,
41
            self::LAYOUT_WRAP_RIGHT,
42
            self::LAYOUT_WIDE,
43
            self::LAYOUT_FULL_WIDTH,
44
            self::LAYOUT_ALIGN_START,
45
            self::LAYOUT_ALIGN_END,
46
        ], true)) {
47
            throw new InvalidArgumentException(sprintf('Invalid layout "%s"', $layout));
48
        }
49
50
        parent::__construct($parent);
51
        $this->layout = $layout;
52
        $this->width = $width;
53
    }
54
55
    public static function load(array $data, ?BlockNode $parent = null): self
56
    {
57
        self::checkNodeData(static::class, $data, ['attrs']);
58
        self::checkRequiredKeys(['layout'], $data['attrs']);
59
60
        $node = new self($data['attrs']['layout'], $data['attrs']['width'] ?? null, $parent);
61
62
        // set content if defined
63
        if (\array_key_exists('content', $data)) {
64
            foreach ($data['content'] as $nodeData) {
65
                $class = Node::NODE_MAPPING[$nodeData['type']];
66
                $child = $class::load($nodeData, $node);
67
68
                $node->append($child);
69
            }
70
        }
71
72
        return $node;
73
    }
74
75
    protected function attrs(): array
76
    {
77
        $attrs = parent::attrs();
78
79
        $attrs['layout'] = $this->layout;
80
81
        if (null !== $this->width) {
82
            $attrs['width'] = $this->width;
83
        }
84
85
        return $attrs;
86
    }
87
}
88