-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathSearch.php
110 lines (91 loc) · 3.29 KB
/
Search.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php declare(strict_types=1);
namespace GSoares\GoogleTrends\Search\Psr7;
use DateTimeImmutable;
use GSoares\GoogleTrends\Search\SearchFilter;
use GSoares\GoogleTrends\Search\SearchInterface;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Throwable;
/**
* @author Gabriel Felipe Soares <[email protected]>
*/
class Search
{
/**
* @var SearchInterface
*/
private $search;
public function __construct(SearchInterface $search)
{
$this->search = $search;
}
public function search(ServerRequestInterface $request): ResponseInterface
{
try {
$params = $request->getQueryParams();
$searchFilter = (new SearchFilter())
->withCategory((int)($params["categoryId"] ?? 0))
->withSearchTerm($params["searchTerm"] ?? 'google')
->withLocation($params["location"] ?? 'US')
->withinInterval(
new DateTimeImmutable($params["intervalFrom"] ?? 'now -7 days'),
new DateTimeImmutable($params["intervalTo"] ?? 'yesterday')
)
->withLanguage($params["language"] ?? 'en-US');
$this->configureSearchSource($params["searchSource"] ?? 'web', $searchFilter);
if (filter_var($params["withTopMetrics"] ?? false, FILTER_VALIDATE_BOOLEAN)) {
$searchFilter->withTopMetrics();
}
if (filter_var($params["withRisingMetrics"] ?? false, FILTER_VALIDATE_BOOLEAN)) {
$searchFilter->withRisingMetrics();
}
return new Response(
200,
[
'Content-Type' => 'application/json',
],
json_encode($this->search->search($searchFilter)->jsonSerialize())
);
} catch (Throwable $exception) {
return new Response(
400,
[
'Content-Type' => 'application/json',
],
json_encode(
[
'errors' => [
[
'status' => 400,
'code' => $exception->getCode(),
'title' => $exception->getMessage(),
'details' => $exception->getMessage(),
]
]
]
)
);
}
}
private function configureSearchSource(string $searchSource, SearchFilter $searchFilter): void
{
if ($searchSource === SearchFilter::SEARCH_SOURCE_NEWS) {
$searchFilter->considerNewsSearch();
return;
}
if ($searchSource === SearchFilter::SEARCH_SOURCE_IMAGES) {
$searchFilter->considerImageSearch();
return;
}
if ($searchSource === SearchFilter::SEARCH_SOURCE_YOUTUBE) {
$searchFilter->considerYoutubeSearch();
return;
}
if ($searchSource === SearchFilter::SEARCH_SOURCE_GOOGLE_SHOPPING) {
$searchFilter->considerGoogleShoppingSearch();
return;
}
$searchFilter->considerWebSearch();
}
}