Completed
Push — develop ( 0a4bcc...0131cc )
by Kirill
25:10
created

GoogleSearchMiddleware::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * This file is part of GitterBot package.
4
 *
5
 * @author Serafim <[email protected]>
6
 * @date 27.01.2016 10:41
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
namespace App\Gitter\Middlewares;
12
13
use App\Message;
14
use App\Gitter\Extensions\Middlewares\MiddlewareInterface;
15
16
/**
17
 * Class GoogleSearchMiddleware
18
 * @package App\Bot\Middlewares
19
 */
20
class GoogleSearchMiddleware implements MiddlewareInterface
21
{
22
    /**
23
     * @param Message $message
24
     * @param \Closure $next
25
     * @return string|null
26
     */
27
    public function handle(Message $message, \Closure $next)
28
    {
29
        $matches = $message->text->escape()->matches('(@.*?\s)?(?:погугли|гугли)\s(.*?)');
30
31
        if ($matches) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $matches of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
32
            if (!trim($matches[2])) {
33
                return $next($message);
34
            }
35
36
            $mention = $this->getUserLogin($message);
37
38
            return trim($matches[1]) && $mention
39
                ? trans('google.personal', [
40
                    'user'  => $mention->login,
41
                    'query' => urlencode($matches[2]),
42
                ])
43
                : trans('google.common', [
44
                    'query' => urlencode($matches[2]),
45
                ]);
46
        }
47
48
        return $next($message);
49
    }
50
51
    /**
52
     * @param Message $message
53
     * @return \App\User|null
54
     */
55
    protected function getUserLogin(Message $message)
56
    {
57
        $hasMentions = $message->mentions->count();
58
        $mention = null;
59
60
        if ($hasMentions) {
61
            $first = $message->mentions[0]->user;
62
            $mention = $first->login === \Auth::user()->login
63
                ? $message->user
64
                : $first;
65
        }
66
67
        return $mention;
68
    }
69
}
70
71