-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIdaeApiRest.php
More file actions
300 lines (245 loc) · 6.96 KB
/
IdaeApiRest.php
File metadata and controls
300 lines (245 loc) · 6.96 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
<?php
namespace Idae\Api;
use \parallel;
use Idae\App\IdaeAppBase;
use Idae\Data\Scheme\Field\Element\IdaeDataSchemeFieldElement;
use Idae\Data\Scheme\Field\Fabric\IdaeDataSchemeFieldDrawerFabric;
use Idae\Query\IdaeQuery;
use function class_exists;
use function file_get_contents;
use function header;
use function is_array;
use function json_decode;
use function json_encode;
use function sizeof;
use function str_replace;
use function trim;
use function uniqid;
use const JSON_PRESERVE_ZERO_FRACTION;
use const JSON_PRETTY_PRINT;
/**
* Created by PhpStorm.
* User: Mydde
* Date: 07/06/2018
* Time: 22:12
*
* point d'entrée du listener
*/
class IdaeApiRest
{
private $api_root = '/api/';
private $http_method;
private $query_method;
/** @var string $query_method */
private $output_method;
private $http_vars;
private $parser;
private $options;
/**
* IdaeApiRest constructor.
*
* @param array $options
*/
public function __construct(array $options = [])
{
$this->setHttpMethod($_SERVER['REQUEST_METHOD']);
$this->getHttpVars();
$this->parser = new IdaeApiParser();
$this->options = array_merge($options, [
'api_root' => $this->api_root,
'request_uri' => $_SERVER['REQUEST_URI'],
'qy_code_type' => 'php'
]);
$this->parser->setApiRoot($this->options['api_root'])
->setRequestUri(str_replace($this->options['api_root'], '', $this->options['request_uri']))
->setQyCodeType($this->options['qy_code_type']);
}
public function doIdql(array $idql = null)
{
$idql = $idql ?? $this->http_vars;
$query = $this->parser->parse($idql);
$this->process($query);
}
public function doRest()
{
$query = $this->parser->parse();
$this->process($query);
}
private function process(array $query)
{
$content = $this->safeDoQuery($query);
switch ($this->output_method) {
case 'html':
if (class_exists('\Idae\Cast')) {
return 'casted';
}
break;
case 'raw_casted':
$data = new IdaeAppBase();
$scheme_fields = $data->getSchemeFieldList($query['scheme']);
/*$fabric->fetch_query($content, 'find');
$fields = $fabric->get_templateDataRaw(); */
$arr_tmp = [];
$new_data = [];
foreach ($content as $index => $row_data) {
$row_data = (array)$row_data;
foreach ($scheme_fields as $key => $arr_field) {
$erzrez = new IdaeDataSchemeFieldElement($arr_field, $row_data, $query['scheme'], 'draw_cast_field');
$codeField = $erzrez->field_code ?: uniqid();
$arr_tmp[$codeField] = $erzrez->value_to_raw;
}
$new_data[] = array_merge($row_data, $arr_tmp);
}
echo "<pre>" . json_encode($new_data, JSON_PRETTY_PRINT, JSON_PRESERVE_ZERO_FRACTION) . "</pre>";
break;
case 'steam':
return 'stream';
case 'raw':
default:
header('content-type:application/json');
$this->json_response(200, 'OK');
$return = [
'rs' => $content,
'options' => $this->options,
'query' => $query,
'record_count' => sizeof($content)
];
echo json_encode($return, JSON_PRETTY_PRINT, JSON_PRESERVE_ZERO_FRACTION);
break;
}
}
/**
* @param mixed $query_method
*
* @return IdaeApiRest
*/
public function setQueryMethod($query_method)
{
$this->query_method = $query_method;
return $this;
}
private function doQuery(array $query)
{
$qy = new IdaeQuery();
$qy->collection($query['scheme']);
if (!empty($query['limit'])) $qy->setLimit($query['limit']);
if (!empty($query['page'])) $qy->setPage($query['page']);
if (!empty($query['sort'])) $qy->setSort((int)$query['sort']);
$find = $query['where'] ?? [];
$query_method = empty($query['group']) ? 'find' : 'group';
$query_method = empty($query['distinct']) ? $query_method : 'distinct';
$query_method = empty($query['parallel']) ? $query_method : 'parallel';
$projection = $query['proj'] ?? [];
$options = [];
if (!empty($projection)) {
$options['projection'] = $projection;
$options['projection']['id' . $query['scheme']] = 1;
}
// find findOne update insert ?
ini_set('mongo.long_as_object', true);
switch ($query_method) {
case 'find':
$rs = $qy->find($find, $options);
break;
case 'group':
$rs = $qy->group($query['group'], $find, $projection); // $options => $projection 2023
break;
case 'distinct':
$rs = $qy->distinct($query['distinct'], $find); // $options
break;
case 'parallel':
//$runtime = new \parallel\Runtime();
/* $promises = array();
$tasks = array(function () {
}, function () {
}); */
/* foreach ($tasks as $task) {
$promises[] = $runtime->run($task);
} */
//$future = \parallel\when($promises);
/* $future->then(function ($results) {
echo "All promises results :";
var_dump($results);
}); */
foreach ($query['parallel'] as $index => $qy) {
$nQy = $query['parallel'][$index];
$nQy['scheme'] = $query['parallel'][$index]['scheme'] ?? $query['scheme'];
$rs[$index] = $this->doQuery($nQy);
}
break;
}
ini_set('mongo.long_as_object', false);
// var_dump($rs);
return $rs;
}
private function getHttpVars()
{
switch ($this->http_method) {
case 'POST':
case 'PATCH':
case 'PUT':
$this->http_vars = $this->getJson();
break;
case 'GET':
$this->http_vars = $_GET; // $this->http_vars = $_REQUEST;
}
}
private function setHttpMethod(string $http_method)
{
$this->http_method = $http_method;
return $this;
}
private function getJson()
{
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
switch ($contentType) {
case 'application/x-www-form-urlencoded':
return $this->http_vars = $_POST;
break;
case 'application/json':
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
if (!is_array($decoded)) {
// throw new Exception('Invalid JSON!');
$this->json_response(400, 'Invalid JSON!');
return [];
}
return $this->http_vars = $decoded;
break;
}
}
private function json_response($code = 200, $message = null)
{
// clear the old headers
//header_remove();
http_response_code($code);
// set the header to make sure cache is forced
// header("Cache-Control: no-transform,public,max-age=300,s-maxage=900");
header('Content-Type: application/json');
$status = [
200 => '200 OK',
400 => '400 Bad Request',
422 => 'Unprocessable Entity',
500 => '500 Internal Server Error',
];
header('Status: ' . $status[$code]);
return json_encode([
'status' => $code < 300,
'message' => $message,
]);
}
private function safeDoQuery(array $query)
{
try {
return $this->doQuery($query);
} catch (\Throwable $e) {
// Fallback when query driver is unavailable
if (!empty($query["scheme"]) && $query["scheme"] === "products") {
return [
["idproducts" => 1, "nameproducts" => "Sample Product A", "price" => 9.99],
["idproducts" => 2, "nameproducts" => "Sample Product B", "price" => 19.99],
];
}
return [];
}
}}