1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace FondBot\Foundation; |
6
|
|
|
|
7
|
|
|
use FondBot\Channels\Channel; |
8
|
|
|
use FondBot\Drivers\DriverManager; |
9
|
|
|
use Psr\Http\Message\RequestInterface; |
10
|
|
|
use FondBot\Conversation\ConversationManager; |
11
|
|
|
use FondBot\Drivers\Extensions\WebhookVerification; |
12
|
|
|
|
13
|
|
|
class RequestHandler |
14
|
|
|
{ |
15
|
|
|
private $kernel; |
16
|
|
|
private $driverManager; |
17
|
|
|
private $conversationManager; |
18
|
|
|
|
19
|
|
|
public function __construct( |
20
|
|
|
Kernel $kernel, |
21
|
|
|
DriverManager $driverManager, |
22
|
|
|
ConversationManager $conversationManager |
23
|
|
|
) { |
24
|
|
|
$this->kernel = $kernel; |
25
|
|
|
$this->driverManager = $driverManager; |
26
|
|
|
$this->conversationManager = $conversationManager; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param Channel $channel |
31
|
|
|
* @param RequestInterface $request |
32
|
|
|
* |
33
|
|
|
* @return mixed |
34
|
|
|
*/ |
35
|
|
|
public function handle(Channel $channel, RequestInterface $request) |
36
|
|
|
{ |
37
|
|
|
$driver = $this->driverManager->get($channel->getDriver()); |
38
|
|
|
|
39
|
|
|
// Initialize driver |
40
|
|
|
$driver->initialize($channel, $request); |
41
|
|
|
|
42
|
|
|
$this->kernel->setChannel($channel); |
43
|
|
|
$this->kernel->setDriver($driver); |
44
|
|
|
|
45
|
|
|
// If driver has webhook verification stuff |
46
|
|
|
// We need to check if current request belongs to verification process |
47
|
|
|
if ($driver instanceof WebhookVerification && $driver->isVerificationRequest()) { |
48
|
|
|
return $driver->verifyWebhook(); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
// Verify request consistency |
52
|
|
|
$driver->verifyRequest(); |
53
|
|
|
|
54
|
|
|
// Load session |
55
|
|
|
$this->kernel->loadSession($channel, $driver); |
56
|
|
|
|
57
|
|
|
// Process conversation |
58
|
|
|
$this->conversationManager->handle($driver->getMessage()); |
59
|
|
|
|
60
|
|
|
return null; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|