slack/src/Base.php
2021-08-12 14:09:40 +10:00

113 lines
2.2 KiB
PHP

<?php
namespace Slack;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Slack\Models\{Channel,Enterprise,Team,User};
/**
* Class Base - is a Base to all incoming Slack POST requests
*
* @package Slack
*/
abstract class Base
{
private const LOGKEY = 'SB-';
protected $_data = [];
public const signature_version = 'v0';
public function __construct(array $request)
{
$this->_data = json_decode(json_encode($request));
if (get_class($this) == self::class)
Log::debug(sprintf('SB-:Received from Slack [%s]',get_class($this)),['m'=>__METHOD__]);
}
/**
* Requests to the object should pull values from $_data
*
* @param string $key
* @return mixed
*/
abstract public function __get(string $key);
/**
* Return the Channel object that a Response is related to
*
* @param bool $create
* @return Channel|null
*/
final public function channel(bool $create=FALSE): ?Channel
{
$o = Channel::firstOrNew(
[
'channel_id'=>$this->channel_id,
]);
if (! $o->exists and $create) {
$o->team_id = $this->team()->id;
$o->active = FALSE;
$o->save();
}
return $o->exists ? $o : NULL;
}
final public function enterprise(): Enterprise
{
return Enterprise::firstOrNew(
[
'enterprise_id'=>$this->enterprise_id
]);
}
/**
* Return the SlackTeam object that a Response is related to
*
* @param bool $any
* @return Team|null
*/
final public function team(bool $any=FALSE): ?Team
{
$o = Team::firstOrNew(
[
'team_id'=>$this->team_id
]);
if (! $o->exists and $any) {
$o = $this->enterprise()->teams->first();
}
return $o->exists ? $o : NULL;
}
/**
* Return the User Object
* The user object may not exist, especially if the event was triggered by a different user
*
* @note Users with both team_id and enterprise_id set to NULL should never be created
*/
final public function user(): User
{
$o = User::firstOrNew(
[
'user_id'=>$this->user_id,
]);
if (! $o->exists) {
$o->team_id = $this->enterprise_id ? NULL : $this->team()->id;
$o->enterprise_id = ($x=$this->enterprise())->exists ? $x->id : NULL;
$o->save();
Log::debug(sprintf('%s: User Created in DB [%s] (%s)',self::LOGKEY,$this->user_id,$o->id));
}
return $o;
}
}