1
|
|
|
<?php |
2
|
|
|
namespace Domains\Bot\Middlewares; |
3
|
|
|
|
4
|
|
|
use AlgoliaSearch\Client; |
5
|
|
|
use Domains\Message; |
6
|
|
|
use Domains\Middleware\MiddlewareInterface; |
7
|
|
|
use Illuminate\Support\Collection; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class LaravelDocumentationSearcherMiddleware |
11
|
|
|
*/ |
12
|
|
|
class LaravelDocumentationSearcherMiddleware implements MiddlewareInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @param Message $message |
16
|
|
|
* @return mixed |
17
|
|
|
*/ |
18
|
|
|
public function handle(Message $message) |
19
|
|
|
{ |
20
|
|
|
$pattern = '/^(@?.*?\s?)(информация|доки|документация|laravel doc)\s+(?:про|по)?\s*(.*?)$/isu'; |
21
|
|
|
if (preg_match($pattern, $message->text_without_special_chars, $matches)) { |
22
|
|
|
|
23
|
|
|
if (!trim($query = $matches[3])) { |
24
|
|
|
return $message; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
$client = new Client( |
28
|
|
|
'8BB87I11DE', |
29
|
|
|
'8e1d446d61fce359f69cd7c8b86a50de' |
30
|
|
|
); |
31
|
|
|
|
32
|
|
|
$result = $client->initIndex('docs')->search($query); |
33
|
|
|
|
34
|
|
|
if ((int) array_get($result, 'nbHits') === 0) { |
35
|
|
|
$message->text = "погугли {$query}"; |
36
|
|
|
return app(NewGoogleSearchMiddleware::class)->handle($message); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
$response = ''; |
40
|
|
|
|
41
|
|
|
$hits = new Collection($result['hits']); |
42
|
|
|
|
43
|
|
|
$hits->unique(function ($row) { |
44
|
|
|
return $row['h1']; |
45
|
|
|
})->map(function ($row) { |
46
|
|
|
$row['link'] = 'https://laravel.com/docs/5.2/' . $row['link']; |
47
|
|
|
return $row; |
48
|
|
|
})->take(3)->each(function ($row) use (&$response) { |
49
|
|
|
$title = ''; |
50
|
|
|
foreach (['h1', 'h2', 'h3', 'h4', 'h5'] as $tag) { |
51
|
|
|
if (isset($row[$tag])) { |
52
|
|
|
$title .= ' ' . $row[$tag]; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$response .= "[*] [i][url={$row['link']}]{$title}[/url][/i]" . PHP_EOL; |
57
|
|
|
}); |
58
|
|
|
|
59
|
|
|
if (!empty($response)) { |
60
|
|
|
$message->answer(trans('search.results', [ |
61
|
|
|
'results' => '[list]' . PHP_EOL . $response . PHP_EOL . '[/list]', |
62
|
|
|
])); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
|
66
|
|
|
return null; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $message; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @return array |
74
|
|
|
*/ |
75
|
|
|
public function getGroup() |
76
|
|
|
{ |
77
|
|
|
return ['laravel', 'global']; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|