blob: 3538f19482b504f51c3a1c6555915cbb5112d593 (
plain)
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
|
<?php
/**
* Nextcloud - News
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Paul Tirk <paultirk@paultirk.com>
* @copyright 2020 Paul Tirk
*/
namespace OCA\News\Controller;
use \OCP\AppFramework\Http;
use \OCP\AppFramework\Http\JSONResponse;
use \OCA\News\Db\IAPI;
trait ApiV2ResponseTrait
{
/**
* Serialize all data
*
* @param mixed $data IAPI or array,
* anything else will return an empty array
*
* @return array
*/
public function serialize($data, bool $reduced = false): array
{
if ($data instanceof IAPI) {
return $data->toAPI2($reduced);
}
$return = [];
if (!is_array($data)) {
return $return;
}
foreach ($data as $entity) {
if ($entity instanceof IAPI) {
$return[] = $entity->toAPI2($reduced);
}
}
return $return;
}
public function response($data, $code = Http::STATUS_OK)
{
return new JSONResponse($data, $code);
}
/**
* @param \Exception $exception
* @param int $code
* @return \OCP\AppFramework\Http\JSONResponse
*/
public function errorResponse(\Exception $exception, $code)
{
return new JSONResponse([
'error' => [
'code' => $exception->getCode(),
'message' => $exception->getMessage()
]
], $code);
}
}
|