-
Notifications
You must be signed in to change notification settings - Fork 0
/
VocalendarCoreAPI.php
96 lines (80 loc) · 2.23 KB
/
VocalendarCoreAPI.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
<?php
namespace vocalendar;
define('API_URL', 'https://vocalendar.jp/core/events.json');
define('AMAZON_SEARCH_CORE_USER_AGENT', 'Vocalendar Amazon Search/1.0');
ini_set('user_agent', AMAZON_SEARCH_CORE_USER_AGENT);
/**
* Vocalendar Core Api class
*
* Core API IF
*/
class VocalendarCoreAPI
{
/**
* request to core
*
* @param array $params query parameters
* @return string responce body
*/
public function request(array $params): string
{
$url = API_URL;
if (!empty($params)) {
$url .= '?' . http_build_query($params);
}
$result = file_get_contents($url);
if ($result === false) {
throw new VocalendarCoreAPIException('Vocalendar Core APIのリクエストに失敗しました。');
}
return $result;
}
/**
* Json to Event Object Array
*
* @param string $json json string (from core responce)
* @return array event object array
*/
public function jsonToEvents(string $json)
{
$jsonObject = json_decode($json, true);
if (!is_array($jsonObject)) {
throw new VocalendarCoreAPIException('イベントJSONからイベントオブジェクトへの変換で失敗しました。');
}
$events = [];
foreach ($jsonObject as $index => $data) {
$events[$index] = new VocalendarCoreEvent($data);
}
return $events;
}
/**
* get events from core
*
* @param array $params query parameters
* @return array responce events
*/
public function get(array $params): array
{
$responce = $this->request($params);
$result = $this->jsonToEvents($responce);
return $result;
}
/**
* get by search query string
*
* @param string $query search query string
* @return VocalendarCoreEvent|null
*/
public function getBySearchQuery(string $query, $limit = 1)
{
$params = [
'q' => $query,
'limit' => $limit,
];
/** @var array<int, VocalendarCoreEvent> */
$results = $this->get($params);
if (count($results) >= 1) {
return reset($results);
}
return null;
}
}