12-cactus/espinoso

View on GitHub
app/Handlers/BrainHandler.php

Summary

Maintainability
A
0 mins
Test Coverage
<?php
 
namespace App\Handlers;
 
use App\Espinoso;
use App\Handlers\BrainHandler\BrainNode;
use Telegram\Bot\Objects\Message;
 
/**
* Class BrainHandler
* @package App\Handlers
*/
class BrainHandler extends BaseHandler
{
/**
* @var static
*/
protected $allNodes;
/**
* @var \Illuminate\Support\Collection
*/
protected $matchedNodes;
 
/**
* BrainHandler constructor.
* @param Espinoso $espinoso
*/
public function __construct(Espinoso $espinoso)
{
parent::__construct($espinoso);
 
$this->matchedNodes = collect([]);
$this->allNodes = collect(trans('brain.patterns'))->map(function ($data, $regex) {
return new BrainNode($regex, $data);
});
}
 
/**
* @param Message $message
* @return bool
*/
public function shouldHandle(Message $message): bool
{
$this->message = $message;
 
$this->matchedNodes = $this->allNodes->filter(function ($node) {
return $node->matchMessage($this->message);
});
 
return $this->matchedNodes->isNotEmpty();
}
 
/**
*
*/
public function handle(): void
{
$this->matchedNodes->each(function (BrainNode $node) {
if ($node->shouldIgnoreTo($this->message->getFrom())) {
$this->espinoso->reply("Con vos no hablo, putite");
return;
}
$this->espinoso->reply($node->pickReply($this->message));
});
}
}