getSearchInformation()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace JanDrda\LaravelGoogleCustomSearchEngine;
4
5
use Exception;
6
7
class LaravelGoogleCustomSearchEngine
8
{
9
10
    /**
11
     * Custom search engine ID
12
     *
13
     * @var string
14
     */
15
    protected $engineId;
16
17
    /**
18
     * Google console API key
19
     *
20
     * @var string
21
     */
22
    protected $apiKey;
23
24
    /**
25
     * Original response converted to array
26
     *
27
     * @var \stdClass
28
     */
29
    protected $originalResponse;
30
31
    /**
32
     * Constructor
33
     *
34
     * LaravelGoogleCustomSearchEngine constructor.
35
     * @param $engineId
36
     * @param $apiKey
37
     */
38
    public function __construct()
39
    {
40
        $this->engineId = config('laravelGoogleCustomSearchEngine.engineId');
41
        $this->apiKey = config('laravelGoogleCustomSearchEngine.apiKey');
42
    }
43
44
    /**
45
     * Setter for engineId, overrides the value from config
46
     *
47
     * @param $engineId
48
     */
49
    public function setEngineId($engineId){
50
        $this->engineId = $engineId;
51
    }
52
53
    /**
54
     * Setter for apiKey, overrides the value from config
55
     *
56
     * @param $engineId
57
     */
58
    public function setApiKey($apiKey){
59
        $this->apiKey = $apiKey;
60
    }
61
62
    /**
63
     * Get search results
64
     *
65
     * Gets results from CSE only as array of objects where the most important variables are
66
     * [title] - page title
67
     * [htmlTitle] - page title with HTML tags
68
     * [link] - page URL
69
     * [displayLink] - displayed part of page URL
70
     * [snippet] - short text from page with the searched phrase
71
     * [htmlSnippet] - short text from page with the searched phrase with HTML tags
72
     * complete list of parameters with description is located at
73
     * https://developers.google.com/custom-search/json-api/v1/reference/cse/list#response
74
     *
75
     * Input parameters are available here
76
     * https://developers.google.com/custom-search/json-api/v1/reference/cse/list#parameters
77
     *
78
     * @param $phrase
79
     * @return array
80
     * @throws Exception
81
     * @link https://developers.google.com/custom-search/json-api/v1/reference/cse/list#response
82
     * @link https://developers.google.com/custom-search/json-api/v1/reference/cse/list#parameters
83
     */
84
    public function getResults($phrase, $parameters = array())
85
    {
86
87
        /**
88
         * Check required parameters
89
         */
90
        if ($phrase == '') {
91
            return array();
92
        }
93
94
        if ($this->engineId == '') {
95
            throw new \Exception('You must specify a engineId');
96
        }
97
98
        if ($this->apiKey == '') {
99
            throw new \Exception('You must specify a apiKey');
100
        }
101
102
        /**
103
         * Create search aray
104
         */
105
        $searchArray = http_build_query(array_merge(
106
            ['key' => $this->apiKey],
107
            ['q' => $phrase],
108
            $parameters
109
        ));
110
111
        /**
112
         * Add unencoded search engine id
113
         */
114
        $searchArray = '?cx=' . $this->engineId . '&' . $searchArray;
115
116
        /**
117
         * Prepare CUrl and get result
118
         */
119
        $ch = curl_init();
120
121
        curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/customsearch/v1" . $searchArray);
122
        curl_setopt($ch, CURLOPT_HEADER, 0);
123
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
124
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
125
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
126
        curl_setopt($ch, CURLOPT_POST, 0);
127
128
        $output = curl_exec($ch);
129
130
        $info = curl_getinfo($ch);
131
132
        curl_close($ch);
133
134
        /**
135
         * Check HTTP code of the result
136
         */
137
        if ($output === false || $info['http_code'] != 200) {
138
139
            throw new \Exception("No data returned, code [". $info['http_code']. "] - " . curl_error($ch));
140
        }
141
142
        /**
143
         * Convert JSON format to object and save
144
         */
145
        $this->originalResponse = json_decode($output);
146
147
        /**
148
         * If there are some results, return them, otherwise return blank array
149
         */
150
        if(isset($this->originalResponse->items)){
151
            return $this->originalResponse->items;
152
        }
153
        else{
154
            return array();
155
        }
156
157
    }
158
159
    /**
160
     * Get full original response
161
     *
162
     * Gets full originated response converted from JSON to StdClass
163
     * Full list of parameters is located at
164
     * complete list of parameters with description is located at
165
     * https://developers.google.com/custom-search/json-api/v1/reference/cse/list#response
166
     *
167
     * @return \stdClass
168
     * @url https://developers.google.com/custom-search/json-api/v1/reference/cse/list#response
169
     */
170
    public function getRawResult(){
171
        return $this->originalResponse;
172
    }
173
174
    /**
175
     * Get search information
176
     *
177
     * Gets basic information about search
178
     * [searchTime] - time costs of the search
179
     * [formattedSearchTime] - time costs of the search formatted according to locale style
180
     * [totalResults] - number of results
181
     * [formattedTotalResults] - number of results formatted according to locale style
182
     *
183
     * @return \stdClass
184
     */
185
    public function getSearchInformation(){
186
        return $this->originalResponse->searchInformation;
187
    }
188
189
    /**
190
     * Get the total number of pages where the search phrase is located
191
     *
192
     * @return integer
193
     */
194
    public function getTotalNumberOfpages(){
195
        return $this->originalResponse->searchInformation->totalResults;
196
    }
197
198
}
199