/
Api.php
718 lines (624 loc) · 17.1 KB
/
Api.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
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
<?php
namespace Kirby\Api;
use Closure;
use Exception;
use Throwable;
use Kirby\Exception\NotFoundException;
use Kirby\Http\Router;
use Kirby\Http\Response;
use Kirby\Toolkit\F;
use Kirby\Toolkit\Properties;
use Kirby\Toolkit\Str;
/**
* The API class is a generic container
* for API routes, models and collections and is used
* to run our REST API. You can find our API setup
* in `kirby/config/api.php`.
*
* @package Kirby Api
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier GmbH
* @license https://getkirby.com/license
*/
class Api
{
use Properties;
/**
* Authentication callback
*
* @var Closure
*/
protected $authentication;
/**
* Debugging flag
*
* @var boolean
*/
protected $debug = false;
/**
* Collection definition
*
* @var array
*/
protected $collections = [];
/**
* Injected data/dependencies
*
* @var array
*/
protected $data = [];
/**
* Model definitions
*
* @var array
*/
protected $models = [];
/**
* The current route
*
* @var Route
*/
protected $route;
/**
* The Router instance
*
* @var Router
*/
protected $router;
/**
* Route definition
*
* @var array
*/
protected $routes = [];
/**
* Request data
* [query, body, files]
*
* @var array
*/
protected $requestData = [];
/**
* The applied request method
* (GET, POST, PATCH, etc.)
*
* @var string
*/
protected $requestMethod;
/**
* Magic accessor for any given data
*
* @param string $method
* @param array $args
* @return mixed
*/
public function __call(string $method, array $args = [])
{
return $this->data($method, ...$args);
}
/**
* Creates a new API instance
*
* @param array $props
*/
public function __construct(array $props)
{
$this->setProperties($props);
}
/**
* Runs the authentication method
* if set
*
* @return mixed
*/
public function authenticate()
{
if ($auth = $this->authentication()) {
return $auth->call($this);
}
return true;
}
/**
* Returns the authentication callback
*
* @return Closure|null
*/
public function authentication()
{
return $this->authentication;
}
/**
* Execute an API call for the given path,
* request method and optional request data
*
* @param string $path
* @param string $method
* @param array $requestData
* @return mixed
*/
public function call(string $path = null, string $method = 'GET', array $requestData = [])
{
$path = rtrim($path, '/');
$this->setRequestMethod($method);
$this->setRequestData($requestData);
$this->router = new Router($this->routes());
$this->route = $this->router->find($path, $method);
$auth = $this->route->attributes()['auth'] ?? true;
if ($auth !== false) {
$this->authenticate();
}
$output = $this->route->action()->call($this, ...$this->route->arguments());
if (is_object($output) === true) {
return $this->resolve($output)->toResponse();
}
return $output;
}
/**
* Setter and getter for an API collection
*
* @param string $name
* @param array|null $collection
* @return Kirby\Api\Collection
*
* @throws NotFoundException If no collection for `$name` exists
*/
public function collection(string $name, $collection = null)
{
if (isset($this->collections[$name]) === false) {
throw new NotFoundException(sprintf('The collection "%s" does not exist', $name));
}
return new Collection($this, $collection, $this->collections[$name]);
}
/**
* Returns the collections definition
*
* @return array
*/
public function collections(): array
{
return $this->collections;
}
/**
* Returns the injected data array
* or certain parts of it by key
*
* @param string|null $key
* @param mixed ...$args
* @return mixed
*
* @throws NotFoundException If no data for `$key` exists
*/
public function data($key = null, ...$args)
{
if ($key === null) {
return $this->data;
}
if ($this->hasData($key) === false) {
throw new NotFoundException(sprintf('Api data for "%s" does not exist', $key));
}
// lazy-load data wrapped in Closures
if (is_a($this->data[$key], 'Closure') === true) {
return $this->data[$key]->call($this, ...$args);
}
return $this->data[$key];
}
/**
* Returns the debugging flag
*
* @return boolean
*/
public function debug(): bool
{
return $this->debug;
}
/**
* Checks if injected data exists for the given key
*
* @param string $key
* @return boolean
*/
public function hasData(string $key): bool
{
return isset($this->data[$key]) === true;
}
/**
* Returns an API model instance by name
*
* @param string $name
* @param mixed $object
* @return Kirby\Api\Model
*
* @throws NotFoundException If no model for `$name` exists
*/
public function model(string $name, $object = null)
{
if (isset($this->models[$name]) === false) {
throw new NotFoundException(sprintf('The model "%s" does not exist', $name));
}
return new Model($this, $object, $this->models[$name]);
}
/**
* Returns all model definitions
*
* @return array
*/
public function models(): array
{
return $this->models;
}
/**
* Getter for request data
* Can either get all the data
* or certain parts of it.
*
* @param string $type
* @param string $key
* @param mixed $default
* @return mixed
*/
public function requestData(string $type = null, string $key = null, $default = null)
{
if ($type === null) {
return $this->requestData;
}
if ($key === null) {
return $this->requestData[$type] ?? [];
}
$data = array_change_key_case($this->requestData($type));
$key = strtolower($key);
return $data[$key] ?? $default;
}
/**
* Returns the request body if available
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public function requestBody(string $key = null, $default = null)
{
return $this->requestData('body', $key, $default);
}
/**
* Returns the files from the request if available
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public function requestFiles(string $key = null, $default = null)
{
return $this->requestData('files', $key, $default);
}
/**
* Returns all headers from the request if available
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public function requestHeaders(string $key = null, $default = null)
{
return $this->requestData('headers', $key, $default);
}
/**
* Returns the request method
*
* @return string
*/
public function requestMethod(): string
{
return $this->requestMethod;
}
/**
* Returns the request query if available
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public function requestQuery(string $key = null, $default = null)
{
return $this->requestData('query', $key, $default);
}
/**
* Turns a Kirby object into an
* API model or collection representation
*
* @param mixed $object
* @return Kirby\Api\Model|Kirby\Api\Collection
*
* @throws NotFoundException If `$object` cannot be resolved
*/
public function resolve($object)
{
if (is_a($object, 'Kirby\Api\Model') === true || is_a($object, 'Kirby\Api\Collection') === true) {
return $object;
}
$className = strtolower(get_class($object));
$lastDash = strrpos($className, '\\');
if ($lastDash !== false) {
$className = substr($className, $lastDash + 1);
}
if (isset($this->models[$className]) === true) {
return $this->model($className, $object);
}
if (isset($this->collections[$className]) === true) {
return $this->collection($className, $object);
}
// now models deeply by checking for the actual type
foreach ($this->models as $modelClass => $model) {
if (is_a($object, $model['type']) === true) {
return $this->model($modelClass, $object);
}
}
throw new NotFoundException(sprintf('The object "%s" cannot be resolved', $className));
}
/**
* Returns all defined routes
*
* @return array
*/
public function routes(): array
{
return $this->routes;
}
/**
* Setter for the authentication callback
*
* @param Closure $authentication
* @return self
*/
protected function setAuthentication(Closure $authentication = null)
{
$this->authentication = $authentication;
return $this;
}
/**
* Setter for the collections definition
*
* @param array $collections
* @return self
*/
protected function setCollections(array $collections = null)
{
if ($collections !== null) {
$this->collections = array_change_key_case($collections);
}
return $this;
}
/**
* Setter for the injected data
*
* @param array $data
* @return self
*/
protected function setData(array $data = null)
{
$this->data = $data ?? [];
return $this;
}
/**
* Setter for the debug flag
*
* @param boolean $debug
* @return self
*/
protected function setDebug(bool $debug = false)
{
$this->debug = $debug;
return $this;
}
/**
* Setter for the model definitions
*
* @param array $models
* @return self
*/
protected function setModels(array $models = null)
{
if ($models !== null) {
$this->models = array_change_key_case($models);
}
return $this;
}
/**
* Setter for the request data
*
* @param array $requestData
* @return self
*/
protected function setRequestData(array $requestData = null)
{
$defaults = [
'query' => [],
'body' => [],
'files' => []
];
$this->requestData = array_merge($defaults, (array)$requestData);
return $this;
}
/**
* Setter for the request method
*
* @param string $requestMethod
* @return self
*/
protected function setRequestMethod(string $requestMethod = null)
{
$this->requestMethod = $requestMethod ?? 'GET';
return $this;
}
/**
* Setter for the route definitions
*
* @param array $routes
* @return self
*/
protected function setRoutes(array $routes = null)
{
$this->routes = $routes ?? [];
return $this;
}
/**
* Renders the API call
*
* @param string $path
* @param string $method
* @param array $requestData
* @return mixed
*/
public function render(string $path, $method = 'GET', array $requestData = [])
{
try {
$result = $this->call($path, $method, $requestData);
} catch (Throwable $e) {
if (is_a($e, 'Kirby\Exception\Exception') === true) {
$result = [
'status' => 'error',
'route' => ($this->route)? $this->route->pattern() : null
] + $e->toArray();
} else {
// remove the document root from the file path
$file = $e->getFile();
if (empty($_SERVER['DOCUMENT_ROOT']) === false) {
$file = ltrim(Str::after($file, $_SERVER['DOCUMENT_ROOT']), '/');
}
$result = [
'status' => 'error',
'exception' => get_class($e),
'message' => $e->getMessage(),
'file' => $file,
'line' => $e->getLine(),
'code' => empty($e->getCode()) === false ? $e->getCode() : 500,
'route' => $this->route ? $this->route->pattern() : null
];
}
}
if ($result === null) {
$result = [
'status' => 'error',
'message' => 'not found',
'code' => 404,
];
}
if ($result === true) {
$result = [
'status' => 'ok',
];
}
if ($result === false) {
$result = [
'status' => 'error',
'message' => 'bad request',
'code' => 400,
];
}
if (is_array($result) === false) {
return $result;
}
// pretty print json data
$pretty = (bool)($requestData['query']['pretty'] ?? false) === true;
// remove critical info from the result set if
// debug mode is switched off
if ($this->debug !== true) {
unset(
$result['file'],
$result['exception'],
$result['line'],
$result['route']
);
}
if (($result['status'] ?? 'ok') === 'error') {
$code = $result['code'] ?? 400;
// sanitize the error code
if ($code < 400 || $code > 599) {
$code = 500;
}
return Response::json($result, $code, $pretty);
}
return Response::json($result, 200, $pretty);
}
/**
* Upload helper method
*
* @param Closure $callback
* @param boolean $single
* @return array
*
* @throws Exception If request has no files
* @throws Exception If there was an error with the upload
*/
public function upload(Closure $callback, $single = false): array
{
$trials = 0;
$uploads = [];
$errors = [];
$files = $this->requestFiles();
if (empty($files) === true) {
throw new Exception('No uploaded files');
}
foreach ($files as $upload) {
if (isset($upload['tmp_name']) === false && is_array($upload)) {
continue;
}
$trials++;
try {
if ($upload['error'] !== 0) {
throw new Exception('Upload error');
}
// get the extension of the uploaded file
$extension = F::extension($upload['name']);
// try to detect the correct mime and add the extension
// accordingly. This will avoid .tmp filenames
if (empty($extension) === true || in_array($extension, ['tmp', 'temp'])) {
$mime = F::mime($upload['tmp_name']);
$extension = F::mimeToExtension($mime);
$filename = F::name($upload['name']) . '.' .$extension;
} else {
$filename = basename($upload['name']);
}
$source = dirname($upload['tmp_name']) . '/' . uniqid() . '.' . $filename;
// move the file to a location including the extension,
// for better mime detection
if (move_uploaded_file($upload['tmp_name'], $source) === false) {
throw new Exception('The uploaded file could not be moved');
}
$data = $callback($source, $filename);
if (is_object($data) === true) {
$data = $this->resolve($data)->toArray();
}
$uploads[$upload['name']] = $data;
} catch (Exception $e) {
$errors[$upload['name']] = $e->getMessage();
}
if ($single === true) {
break;
}
}
// return a single upload response
if ($trials === 1) {
if (empty($errors) === false) {
return [
'status' => 'error',
'message' => current($errors)
];
}
return [
'status' => 'ok',
'data' => current($uploads)
];
}
if (empty($errors) === false) {
return [
'status' => 'error',
'errors' => $errors
];
}
return [
'status' => 'ok',
'data' => $uploads
];
}
}