slack/src/Interactive/ViewSubmission.php

120 lines
2.7 KiB
PHP

<?php
namespace Slack\Interactive;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Slack\Blockkit\Modal;
use Slack\Exceptions\SlackException;
use Slack\Models\Team;
/**
* Incoming modal view submission event.
*
* @package Slack\Interactive
*/
class ViewSubmission extends Base
{
protected const LOGKEY = 'IVS';
// View Submissions must respond with via a trigger or inline
public $respondNow = TRUE;
public function __get($key)
{
switch ($key) {
case 'blocks':
return collect(object_get($this->_data,'view.'.$key));
case 'callback':
return object_get($this->_data,'view.callback_id');
case 'callback_id':
return $this->callback('id');
case 'callback_value':
return $this->callback('value');
case 'meta':
return object_get($this->_data,'view.private_metadata');
case 'state':
return collect(object_get($this->_data,'view.'.$key.'.values'));
case 'view_id':
return object_get($this->_data,'view.id');
default:
return parent::__get($key);
}
}
/**
* Separate out an callback command to the id that the command relates to
*
* @param string $key
* @return string|null
* @throws SlackException
*/
private function callback(string $key): ?string
{
$regex = '/^([a-z_]+)\|([0-9]+)$/';
$id = NULL;
$value = NULL;
if (preg_match($regex,$this->callback)) {
$id = preg_replace($regex,'$1',$this->callback);
$value = preg_replace($regex,'$2',$this->callback);
}
switch ($key) {
case 'id':
return $id ?: $this->callback;
case 'value':
return $value;
default:
throw new SlackException('Unknown key: '.$key);
}
}
/**
* This method should be overridden by a local implementation
*
* @return Modal
* @throws \Exception
*/
public function respond(): Modal
{
// Do some magic with event data
Log::info(sprintf('%s:View Submission for Callback [%s] User [%s] in [%s]',self::LOGKEY,$this->callback_id,$this->user_id,$this->team_id),['m'=>__METHOD__]);
$action = NULL;
$id = NULL;
if (preg_match('/^(.*)\|([0-9]+)/',$this->callback_id)) {
[$action,$cid] = explode('|',$this->callback_id,2);
} elseif (preg_match('/^[a-z_]+$/',$this->callback_id)) {
$action = $this->callback_id;
} else {
// If we get here, its an action that we dont know about.
Log::notice(sprintf('%s:Unhandled CALLBACK [%s]',static::LOGKEY,$this->callback_id),['m'=>__METHOD__]);
}
switch ($action) {
default:
Log::notice(sprintf('%s:Unhandled ACTION [%s]',self::LOGKEY,$action),['m'=>__METHOD__]);
}
return new Modal;
}
public function value(string $block_id,string $action_id): ?string
{
return object_get($this->state->get($block_id),$action_id.'.value');
}
}