1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\SlashCommand\SlashCommandHandler; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection as IlluminateCollection; |
6
|
|
|
use Spatie\SlashCommand\InvalidSlashCommandHandler; |
7
|
|
|
use Spatie\SlashCommand\SlashCommandRequest; |
8
|
|
|
use Spatie\SlashCommand\SlashCommandResponse; |
9
|
|
|
|
10
|
|
|
class Collection extends IlluminateCollection |
11
|
|
|
{ |
12
|
|
|
/** @var \Spatie\SlashCommand\SlashCommandRequest */ |
13
|
|
|
protected $request; |
14
|
|
|
|
15
|
|
|
public static function createForClasses(array $commandHandlers) |
16
|
|
|
{ |
17
|
|
|
return new static($commandHandlers); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
public function __construct(array $commandHandlers, SlashCommandRequest $request) |
21
|
|
|
{ |
22
|
|
|
$this->request = $request; |
23
|
|
|
|
24
|
|
|
$commandHandlers = collect($commandHandlers) |
25
|
|
|
->each(function (string $className) { |
26
|
|
|
$this->guardAgainstInvalidHandlerClassName($className); |
27
|
|
|
}) |
28
|
|
|
->map(function (string $className) { |
29
|
|
|
return new $className($this->request); |
30
|
|
|
}) |
31
|
|
|
->toArray(); |
32
|
|
|
|
33
|
|
|
parent::__construct($commandHandlers); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
protected function guardAgainstInvalidHandlerClassName(string $className) |
37
|
|
|
{ |
38
|
|
|
if (!class_exists($className)) { |
39
|
|
|
throw InvalidSlashCommandHandler::handlerDoesNotExist($className); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
if (!$className instanceof BaseHandler) { |
43
|
|
|
throw InvalidSlashCommandHandler::handlerDoesNotExendFromBaseHandler($className); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function getResponse(): SlashCommandResponse |
48
|
|
|
{ |
49
|
|
|
$handler = $this->items |
|
|
|
|
50
|
|
|
->first(function (BaseHandler $commandHandler) { |
51
|
|
|
return $commandHandler->canHandle($this->request); |
52
|
|
|
}); |
53
|
|
|
|
54
|
|
|
if (!$handler) { |
55
|
|
|
throw RequestCouldNotBeProcessed::noHandlerFound($this->request); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$response = $handler->handle($this->slashCommandRequest); |
59
|
|
|
|
60
|
|
|
return $response; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.