Skip to content

Commit d8a57e6

Browse files
committed
Adds helper for retrieving input state data from view_submission
1 parent 9f5c5c0 commit d8a57e6

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

src/Contexts/InputState.php

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace SlackPhp\Framework\Contexts;
6+
7+
use JsonSerializable;
8+
use SlackPhp\Framework\Context;
9+
10+
/**
11+
* Normalizes state data from all input types in `view_submission`s to key-value pairs.
12+
*/
13+
class InputState implements JsonSerializable
14+
{
15+
use HasData;
16+
17+
/**
18+
* Creates the InputState by extracting the data from the Context.
19+
*
20+
* @param Context $context
21+
* @return self
22+
*/
23+
public static function fromContext(Context $context): self
24+
{
25+
return new self($context->payload()->getState()->toArray());
26+
}
27+
28+
public function __construct(array $stateData)
29+
{
30+
$data = [];
31+
foreach ($stateData as $blockId => $input) {
32+
$elem = reset($input);
33+
$data[$blockId] = $elem['value']
34+
?? $elem['selected_option']['value']
35+
?? $elem['selected_date']
36+
?? $elem['selected_time']
37+
?? $elem['selected_user']
38+
?? $elem['selected_conversation']
39+
?? $elem['selected_channel']
40+
?? null;
41+
if ($data[$blockId] !== null) {
42+
continue;
43+
}
44+
45+
if (isset($elem['selected_options'])) {
46+
$data[$blockId] = array_column($elem['selected_options'], 'value');
47+
continue;
48+
}
49+
50+
$data[$blockId] = $elem['selected_users']
51+
?? $elem['selected_conversations']
52+
?? $elem['selected_channels']
53+
?? null;
54+
}
55+
56+
$this->setData($data);
57+
}
58+
}

0 commit comments

Comments
 (0)