Skip to content

Commit 4213330

Browse files
committed
Add custom Matcher, curl_options, configuration file.
1 parent 27820b4 commit 4213330

17 files changed

+231
-68
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,6 @@
33
composer.lock
44
.php_cs.cache
55
/vendor/
6-
update.bat
6+
update.bat
7+
.phpunit.result.cache
8+
todo.txt

README.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/botman/botman/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/botman/botman/?branch=master)
88
[![Packagist](https://img.shields.io/packagist/l/botman/botman.svg)]()
99
[![StyleCI](https://styleci.io/repos/65017574/shield?branch=master)](https://styleci.io/repos/65017574)
10-
[![Slack](https://rauchg-slackin-jtdkltstsj.now.sh/badge.svg)](https://rauchg-slackin-jtdkltstsj.now.sh)
10+
[![Slack](https://slack.botman.io/badge.svg)](https://slack.botman.io)
1111
[![Monthly Downloads](https://img.shields.io/packagist/dm/botman/botman.svg?style=flat-square)](https://packagist.org/packages/botman/botman)
1212

1313
[![https://phppackagedevelopment.com](https://display-demo.schlein.net/images/phppd.jpg)](https://phppackagedevelopment.com)
@@ -30,6 +30,14 @@ $botman->hears('I want cross-platform bots with PHP!', function (BotMan $bot) {
3030

3131
You can find the BotMan documentation at [https://botman.io](https://botman.io).
3232

33+
## Stand Alone Configuration
34+
35+
If you are installing Botman in a stand alone Laravel application, you can publish the configuration file with the following command:
36+
37+
```
38+
php artisan vendor:publish --tag=config --provider="BotMan\BotMan\BotManServiceProvider"
39+
```
40+
3341
## Support the development
3442
**Do you like this project? Support it by donating**
3543

assets/config.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
3+
return [
4+
5+
/*
6+
|--------------------------------------------------------------------------
7+
| Conversation Cache Time
8+
|--------------------------------------------------------------------------
9+
|
10+
| BotMan caches each started conversation. This value defines the
11+
| number of minutes that a conversation will remain stored in
12+
| the cache.
13+
|
14+
*/
15+
'conversation_cache_time' => 40,
16+
17+
/*
18+
|--------------------------------------------------------------------------
19+
| User Cache Time
20+
|--------------------------------------------------------------------------
21+
|
22+
| BotMan caches user information of the incoming messages.
23+
| This value defines the number of minutes that this
24+
| data will remain stored in the cache.
25+
|
26+
*/
27+
'user_cache_time' => 30,
28+
29+
/*
30+
|--------------------------------------------------------------------------
31+
| cURL Options
32+
|--------------------------------------------------------------------------
33+
|
34+
| BotMan will use this array to prepare every cURL request.
35+
| The same option can be set per driver in the relative
36+
| driver configuration file. It uses the
37+
| curl_setopt_array() function.
38+
|
39+
*/
40+
'curl_options' => [],
41+
42+
];

composer.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@
2929
"mockery/mockery": "^1.1",
3030
"doctrine/cache": "^1.6",
3131
"symfony/cache": "^3.4.35 || ^4.3.7 || ^5.0",
32-
"ext-curl": "*"
32+
"ext-curl": "*",
33+
"dms/phpunit-arraysubset-asserts": "^0.4.0"
3334
},
3435
"suggest": {
3536
"doctrine/cache": "Use any Doctrine cache driver for cache",
@@ -63,4 +64,4 @@
6364
},
6465
"prefer-stable": true,
6566
"minimum-stability": "dev"
66-
}
67+
}

src/BotMan.php

Lines changed: 54 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -127,20 +127,18 @@ class BotMan
127127
* @param array $config
128128
* @param StorageInterface $storage
129129
*/
130-
public function __construct(CacheInterface $cache, DriverInterface $driver, $config, StorageInterface $storage)
130+
public function __construct(CacheInterface $cache, DriverInterface $driver, $config, StorageInterface $storage, ?Matcher $matcher = null)
131131
{
132-
if (!isset($config['bot_id'])) {
133-
$config['bot_id'] = '';
134-
}
132+
$this->config = $config;
133+
$this->config['bot_id'] = $this->config['bot_id'] ?? '';
135134

136135
$this->cache = $cache;
137-
$this->message = new IncomingMessage('', '', '', null, $config['bot_id']);
136+
$this->message = new IncomingMessage('', '', '', null, $this->config['bot_id']);
138137
$this->driver = $driver;
139-
$this->config = $config;
140138
$this->storage = $storage;
141139
$this->matcher = new Matcher();
142140
$this->middleware = new MiddlewareManager($this);
143-
$this->conversationManager = new ConversationManager();
141+
$this->conversationManager = new ConversationManager($matcher);
144142
$this->exceptionHandler = new ExceptionHandler();
145143
}
146144

@@ -234,13 +232,16 @@ public function runsOnSocket($running = null)
234232
*/
235233
public function getUser()
236234
{
237-
if ($user = $this->cache->get('user_'.$this->driver->getName().'_'.$this->getMessage()->getSender())) {
235+
if ($user = $this->cache->get('user_' . $this->driver->getName() . '_' . $this->getMessage()->getSender())) {
238236
return $user;
239237
}
240238

241239
$user = $this->getDriver()->getUser($this->getMessage());
242-
$this->cache->put('user_'.$this->driver->getName().'_'.$user->getId(), $user,
243-
$this->config['user_cache_time'] ?? 30);
240+
$this->cache->put(
241+
'user_' . $this->driver->getName() . '_' . $user->getId(),
242+
$user,
243+
$this->config['user_cache_time'] ?? 30
244+
);
244245

245246
return $user;
246247
}
@@ -269,7 +270,7 @@ protected function compileParameterNames($value)
269270
public function hears($pattern, $callback, $in = null)
270271
{
271272
if (is_array($pattern)) {
272-
$pattern = '(?|'.implode('|', $pattern).')';
273+
$pattern = '(?|' . implode('|', $pattern) . ')';
273274
}
274275

275276
$command = new Command($pattern, $callback, $in);
@@ -288,7 +289,7 @@ public function hears($pattern, $callback, $in = null)
288289
*/
289290
public function on($names, $callback)
290291
{
291-
if (! is_array($names)) {
292+
if (!is_array($names)) {
292293
$names = [$names];
293294
}
294295

@@ -314,7 +315,7 @@ public function receivesImages($callback)
314315
}
315316

316317
/**
317-
* Listening for image files.
318+
* Listening for video files.
318319
*
319320
* @param $callback
320321
* @return Command
@@ -419,7 +420,7 @@ public function listen()
419420
try {
420421
$isVerificationRequest = $this->verifyServices();
421422

422-
if (! $isVerificationRequest) {
423+
if (!$isVerificationRequest) {
423424
$this->fireDriverEvents();
424425

425426
if ($this->firedDriverEvents === false) {
@@ -428,15 +429,15 @@ public function listen()
428429
if ($this->loadedConversation === false) {
429430
$this->callMatchingMessages();
430431
}
432+
}
431433

432-
/*
433-
* If the driver has a "messagesHandled" method, call it.
434-
* This method can be used to trigger driver methods
435-
* once the messages are handles.
436-
*/
437-
if (method_exists($this->getDriver(), 'messagesHandled')) {
438-
$this->getDriver()->messagesHandled();
439-
}
434+
/*
435+
* If the driver has a "messagesHandled" method, call it.
436+
* This method can be used to trigger driver methods
437+
* once the messages are handles.
438+
*/
439+
if (method_exists($this->getDriver(), 'messagesHandled')) {
440+
$this->getDriver()->messagesHandled();
440441
}
441442

442443
$this->firedDriverEvents = false;
@@ -452,8 +453,12 @@ public function listen()
452453
*/
453454
protected function callMatchingMessages()
454455
{
455-
$matchingMessages = $this->conversationManager->getMatchingMessages($this->getMessages(), $this->middleware,
456-
$this->getConversationAnswer(), $this->getDriver());
456+
$matchingMessages = $this->conversationManager->getMatchingMessages(
457+
$this->getMessages(),
458+
$this->middleware,
459+
$this->getConversationAnswer(),
460+
$this->getDriver()
461+
);
457462

458463
foreach ($matchingMessages as $matchingMessage) {
459464
$this->command = $matchingMessage->getCommand();
@@ -468,15 +473,18 @@ protected function callMatchingMessages()
468473
return $middleware instanceof Heard;
469474
})->toArray();
470475

471-
$this->message = $this->middleware->applyMiddleware('heard', $matchingMessage->getMessage(),
472-
$commandMiddleware);
476+
$this->message = $this->middleware->applyMiddleware(
477+
'heard',
478+
$matchingMessage->getMessage(),
479+
$commandMiddleware
480+
);
473481

474482
$parameterNames = $this->compileParameterNames($this->command->getPattern());
475483

476484
$parameters = $matchingMessage->getMatches();
477485
if (\count($parameterNames) !== \count($parameters)) {
478486
$parameters = array_merge(
479-
//First, all named parameters (eg. function ($a, $b, $c))
487+
//First, all named parameters (eg. function ($a, $b, $c))
480488
array_filter(
481489
$parameters,
482490
'\is_string',
@@ -501,7 +509,7 @@ protected function callMatchingMessages()
501509
}
502510
}
503511

504-
if (empty($matchingMessages) && empty($this->getBotMessages()) && ! \is_null($this->fallbackMessage)) {
512+
if (empty($matchingMessages) && empty($this->getBotMessages()) && !\is_null($this->fallbackMessage)) {
505513
$this->callFallbackMessage();
506514
}
507515
}
@@ -513,7 +521,7 @@ protected function callFallbackMessage()
513521
{
514522
$messages = $this->getMessages();
515523

516-
if (! isset($messages[0])) {
524+
if (!isset($messages[0])) {
517525
return;
518526
}
519527

@@ -537,7 +545,7 @@ protected function verifyServices()
537545
/**
538546
* @param string|Question|OutgoingMessage $message
539547
* @param string|array $recipients
540-
* @param string|DriverInterface|null $driver
548+
* @param string|DriverInterface|string|null $driver
541549
* @param array $additionalParameters
542550
* @return Response
543551
* @throws BotManException
@@ -559,12 +567,8 @@ public function say($message, $recipients, $driver = null, $additionalParameters
559567

560568
$recipients = \is_array($recipients) ? $recipients : [$recipients];
561569

562-
if (!isset($this->config['bot_id'])) {
563-
$this->config['bot_id'] = '';
564-
}
565-
566570
foreach ($recipients as $recipient) {
567-
$this->message = new IncomingMessage('', $recipient, '', null, $this->config['bot_id']);
571+
$this->message = new IncomingMessage('', $recipient, '', null, $this->config['bot_id'] ?? '');
568572
$response = $this->reply($message, $additionalParameters);
569573
}
570574

@@ -584,7 +588,7 @@ public function say($message, $recipients, $driver = null, $additionalParameters
584588
*/
585589
public function ask($question, $next, $additionalParameters = [], $recipient = null, $driver = null)
586590
{
587-
if (! \is_null($recipient) && ! \is_null($driver)) {
591+
if (!\is_null($recipient) && !\is_null($driver)) {
588592
if (\is_string($driver)) {
589593
$driver = DriverManager::loadFromName($driver, $this->config);
590594
}
@@ -609,13 +613,12 @@ public function types()
609613
}
610614

611615
/**
612-
* @param int $seconds Number of seconds to wait
616+
* @param float $seconds Number of seconds to wait
613617
* @return $this
614618
*/
615-
public function typesAndWaits($seconds)
619+
public function typesAndWaits(float $seconds)
616620
{
617-
$this->getDriver()->types($this->message);
618-
sleep($seconds);
621+
$this->getDriver()->typesAndWaits($this->message, $seconds);
619622

620623
return $this;
621624
}
@@ -635,7 +638,7 @@ public function sendRequest($endpoint, $additionalParameters = [])
635638
return $driver->sendRequest($endpoint, $additionalParameters, $this->message);
636639
}
637640

638-
throw new BadMethodCallException('The driver '.$this->getDriver()->getName().' does not support low level requests.');
641+
throw new BadMethodCallException('The driver ' . $this->getDriver()->getName() . ' does not support low level requests.');
639642
}
640643

641644
/**
@@ -647,8 +650,11 @@ public function reply($message, $additionalParameters = [])
647650
{
648651
$this->outgoingMessage = \is_string($message) ? OutgoingMessage::create($message) : $message;
649652

650-
return $this->sendPayload($this->getDriver()->buildServicePayload($this->outgoingMessage, $this->message,
651-
$additionalParameters));
653+
return $this->sendPayload($this->getDriver()->buildServicePayload(
654+
$this->outgoingMessage,
655+
$this->message,
656+
$additionalParameters
657+
));
652658
}
653659

654660
/**
@@ -683,13 +689,14 @@ public function randomReply(array $messages)
683689
*/
684690
protected function makeInvokableAction($action)
685691
{
686-
if (! method_exists($action, '__invoke')) {
692+
if (!method_exists($action, '__invoke')) {
687693
throw new UnexpectedValueException(sprintf(
688-
'Invalid hears action: [%s]', $action
694+
'Invalid hears action: [%s]',
695+
$action
689696
));
690697
}
691698

692-
return $action.'@__invoke';
699+
return $action . '@__invoke';
693700
}
694701

695702
/**
@@ -755,7 +762,7 @@ public function __call($name, $arguments)
755762
return \call_user_func_array([$this->getDriver(), $name], $arguments);
756763
}
757764

758-
throw new BadMethodCallException('Method ['.$name.'] does not exist.');
765+
throw new BadMethodCallException('Method [' . $name . '] does not exist.');
759766
}
760767

761768
/**

src/BotManFactory.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ public static function create(
6464
$storageDriver = new FileStorage(__DIR__);
6565
}
6666

67-
$driverManager = new DriverManager($config, new Curl());
67+
$driverManager = new DriverManager($config, new Curl($config['curl_options'] ?? []));
6868
$driver = $driverManager->getMatchingDriver($request);
6969

7070
return new BotMan($cache, $driver, $config, $storageDriver);
@@ -97,7 +97,7 @@ public static function createForSocket(
9797
$storageDriver = new FileStorage(__DIR__);
9898
}
9999

100-
$driverManager = new DriverManager($config, new Curl());
100+
$driverManager = new DriverManager($config, new Curl($config['curl_options'] ?? []));
101101

102102
$botman = new BotMan($cache, DriverManager::loadFromName('Null', $config), $config, $storageDriver);
103103
$botman->runsOnSocket(true);
@@ -129,7 +129,7 @@ public static function passRequestToSocket($port = 8080, Request $request = null
129129
$request = Request::createFromGlobals();
130130
}
131131

132-
$client = stream_socket_client('tcp://127.0.0.1:'.$port);
132+
$client = stream_socket_client('tcp://127.0.0.1:' . $port);
133133
fwrite($client, json_encode([
134134
'attributes' => $request->attributes->all(),
135135
'query' => $request->query->all(),

0 commit comments

Comments
 (0)