NewGoogleSearchMiddleware::getGoogleQuery()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 11
rs 9.4285
1
<?php
2
namespace Domains\Bot\Middlewares;
3
4
use Domains\Message;
5
use Domains\Middleware\MiddlewareInterface;
6
use Illuminate\Config\Repository;
7
use Illuminate\Support\Collection;
8
use Interfaces\Google\GoogleSearch;
9
10
/**
11
 * Class GoogleSearchMiddleware
12
 */
13
class NewGoogleSearchMiddleware implements MiddlewareInterface
14
{
15
    /**
16
     * @var GoogleSearch
17
     */
18
    private $search;
19
20
    /**
21
     * GoogleSearchMiddleware constructor.
22
     *
23
     * @param Repository $config
24
     */
25
    public function __construct(Repository $config)
26
    {
27
        $this->search = new GoogleSearch($config);
28
    }
29
30
    /**
31
     * @param Message $message
32
     *
33
     * @return Message
34
     */
35
    public function handle(Message $message)
36
    {
37
        $query = $this->getGoogleQuery($message);
38
39
        if ($query) {
40
            $search = '';
41
42
            try {
43
                $search = $this->search->searchGetMessage($query);
44
            } catch (\Throwable $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
45
            }
46
47
            $hasMentions = count($message->mentions);
48
            $mention = null;
49
50
            if ($hasMentions) {
51
                $mention = $message->mentions[0]->isBot()
52
                    ? $message->user
53
                    : $message->mentions[0];
54
            }
55
56
            if (count($message->mentions)) {
57
                return $message->answer(
58
                    trans('google.personal', [
59
                        'user' => $mention->login,
60
                        'query' => urlencode($query),
61
                    ]) .
62
                    PHP_EOL . $search
63
                );
64
            }
65
66
            return $message->answer(
67
                trans('google.common', ['query' => urlencode($query)]) .
68
                    PHP_EOL . $search
69
            );
70
        }
71
72
        return $message;
73
    }
74
75
    /**
76
     * @param Message $message
77
     *
78
     * @return string
79
     */
80
    private function getGoogleQuery(Message $message) : string
81
    {
82
        $words = (new Collection(trans('google.queries')))->map('preg_quote')->implode('|');
83
        $pattern = sprintf('/^(?:@.*?\s)?(?:%s)\s(.*?)$/isu', $words);
84
        $found = preg_match($pattern, $message->text_without_special_chars, $matches);
85
        if ($found) {
86
            return trim($matches[1]);
87
        }
88
89
        return '';
90
    }
91
}
92