1+ <?php
2+
3+ namespace PhpTelegramBot \FluentKeyboard ;
4+
5+ abstract class KeyboardMarkup extends FluentEntity
6+ {
7+
8+ /**
9+ * Defines the field name that contains the rows and buttons.
10+ *
11+ * @var string
12+ */
13+ protected static $ keyboardFieldName = 'keyboard ' ;
14+
15+ protected $ currentRowIndex = 0 ;
16+
17+ public function __construct (array $ data = [])
18+ {
19+ parent ::__construct ($ data );
20+
21+ // Make sure we have one empty row from the beginning
22+ $ this ->data [static ::$ keyboardFieldName ] = [[]];
23+ }
24+
25+ /**
26+ * Adds a new row to the keyboard.
27+ *
28+ * @param array $buttons
29+ * @return $this
30+ */
31+ public function row (array $ buttons = [])
32+ {
33+ $ keyboard = &$ this ->data [static ::$ keyboardFieldName ];
34+
35+ // Last row is not empty
36+ if (! empty ($ keyboard [$ this ->currentRowIndex ])) {
37+ $ keyboard [] = [];
38+ $ this ->currentRowIndex ++;
39+ }
40+
41+ // argument is not empty
42+ if (! empty ($ buttons )) {
43+ $ keyboard [$ this ->currentRowIndex ] = $ buttons ;
44+ $ this ->currentRowIndex ++;
45+ }
46+
47+ return $ this ;
48+ }
49+
50+ /**
51+ * Adds buttons one per row to the keyboard.
52+ *
53+ * @param array $buttons
54+ * @return $this
55+ */
56+ public function stack (array $ buttons )
57+ {
58+ // Every button gets its own row
59+ foreach ($ buttons as $ button ) {
60+ $ this ->row ([$ button ]);
61+ }
62+
63+ return $ this ;
64+ }
65+
66+ /**
67+ * Adds a button to the last row.
68+ *
69+ * @param \JsonSerializable $button
70+ * @return $this
71+ */
72+ public function button (\JsonSerializable $ button )
73+ {
74+ $ keyboard = &$ this ->data [static ::$ keyboardFieldName ];
75+
76+ $ keyboard [$ this ->currentRowIndex ][] = $ button ;
77+
78+ return $ this ;
79+ }
80+
81+ }
0 commit comments