Passed
Push — master ( 195aeb...469104 )
by Romain
36s
created

Nested::isValidButton()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 1
crap 3
1
<?php
2
namespace Kerox\Messenger\Model\Common\Buttons;
3
4
class Nested extends AbstractButtons
5
{
6
7
    /**
8
     * @var string
9
     */
10
    protected $title;
11
12
    /**
13
     * @var \Kerox\Messenger\Model\Common\Buttons\AbstractButtons[]
14
     */
15
    protected $buttons;
16
17
    /**
18
     * Nested constructor.
19
     *
20
     * @param string $title
21
     * @param \Kerox\Messenger\Model\Common\Buttons\AbstractButtons[] $buttons
22
     */
23 2
    public function __construct(string $title, array $buttons)
24
    {
25 2
        parent::__construct(self::TYPE_NESTED);
26
27 2
        $this->isValidString($title, 20);
28 2
        $this->isValidArray($buttons, 5);
29 2
        $this->isValidButton($buttons);
30
31 2
        $this->title = $title;
32 2
        $this->buttons = $buttons;
33 2
    }
34
35
    /**
36
     * @param \Kerox\Messenger\Model\Common\Buttons\AbstractButtons $button
37
     * @return \Kerox\Messenger\Model\Common\Buttons\Nested
38
     */
39 1
    public function addButton(AbstractButtons $button): Nested
40
    {
41 1
        $this->isValidButton([$button]);
42
43 1
        $this->buttons[] = $button;
44
45 1
        return $this;
46
    }
47
48
    /**
49
     * @param array $buttons
50
     */
51 2
    private function isValidButton(array $buttons)
52
    {
53 2
        $allowedButtonsType = $this->getAllowedButtonsType();
54
55
        /** @var AbstractButtons $button */
56 2
        foreach ($buttons as $button) {
57 2
            if (!in_array($button->getType(), $allowedButtonsType)) {
58 2
                throw new \InvalidArgumentException('Buttons can only be an instance of WebUrl, PostBack or Nested');
59
            }
60
        }
61 2
    }
62
63
    /**
64
     * @return array
65
     */
66 2
    private function getAllowedButtonsType(): array
67
    {
68
        return [
69 2
            AbstractButtons::TYPE_WEB_URL,
70 2
            AbstractButtons::TYPE_POSTBACK,
71 2
            AbstractButtons::TYPE_NESTED,
72
        ];
73
    }
74
75
    /**
76
     * @return array
77
     */
78 2
    public function jsonSerialize(): array
79
    {
80 2
        $json = parent::jsonSerialize();
81
        $json += [
82 2
            'title' => $this->title,
83 2
            'call_to_actions' => $this->buttons,
84
        ];
85
86 2
        return $json;
87
    }
88
}
89