Completed
Push — master ( d56647...5f1d83 )
by Kirill
11s
created

GoogleSearch::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 9.4285
1
<?php
2
/**
3
 * This file is part of GitterBot package.
4
 *
5
 * @author Serafim <[email protected]>
6
 * @date   18.04.2016 16:29
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 Interfaces\Google;
12
13
use Amp\Artax\Client;
14
use Amp\Artax\Request;
15
use Amp\Artax\Response;
16
use Illuminate\Config\Repository;
17
use function Amp\wait;
18
19
/**
20
 * Class GoogleSearch
21
 * @package Domains\Bot\Middlewares\Common\GoogleSearch
22
 */
23
class GoogleSearch
24
{
25
    /**
26
     * @var Client
27
     */
28
    private $artax;
29
30
    /**
31
     * @var string
32
     */
33
    private $token;
34
35
    /**
36
     * GoogleSearch constructor.
37
     *
38
     * @param Repository $config
39
     */
40
    public function __construct(Repository $config)
41
    {
42
        $this->artax = new Client();
43
        $this->token = $config->get('google.token');
44
    }
45
46
    /**
47
     * @param string $query
48
     *
49
     * @return mixed
50
     * @throws \Throwable
51
     */
52
    public function search(string $query)
53
    {
54
        $url = 'https://www.googleapis.com/customsearch/v1?'.http_build_query([
55
            'key' => $this->token,
56
            'lr' => 'lang_ru',
57
            'cx' => '017648015832347857471:ap7pijkcqh4',
58
            'q' => $query,
59
        ]);
60
61
        $request = new Request();
62
        $request->setMethod('GET');
63
        $request->setUri($url);
64
        $request->setProtocol('1.1');
65
66
        /** @var Response $response */
67
        $response = wait($this->artax->request($request));
68
69
        $result = json_decode($response->getBody());
70
71
        if (json_last_error() !== JSON_ERROR_NONE) {
72
            throw new \RuntimeException('Broken google api response');
73
        }
74
75
        return property_exists($result, 'items') ? $result->items : [];
76
    }
77
78
    /**
79
     * @param string $query
80
     *
81
     * @throws \Throwable
82
     * @return string
83
     */
84
    public function searchGetMessage(string $query) : string
85
    {
86
        $result = [trans('google.results')];
87
        $response = $this->search($query);
88
89
        foreach ($response as $i => $link) {
90
            if ($i >= 3) {
91
                continue;
92
            }
93
94
            $result[] = sprintf('[*] [url=%s]%s[/url]', $link->link, $link->title);
95
        }
96
97
        if (! empty($result)) {
98
            $result = '[list]'.implode(PHP_EOL, $result).'[/list]';
99
        }
100
101
        return $result;
102
    }
103
}