Skip to content
This repository was archived by the owner on Dec 11, 2022. It is now read-only.

Commit fd3ac04

Browse files
committed
Some REST server improvements.
1 parent 834c783 commit fd3ac04

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

src/REST.php

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ protected function POST($action = '', $data = '') {
8989
$ents = [$ents];
9090
}
9191
$created = [];
92+
$hadSuccess = false;
9293
$invalidData = false;
9394
foreach ($ents as $entData) {
9495
if ((int) $entData['guid'] > 0) {
@@ -103,14 +104,18 @@ protected function POST($action = '', $data = '') {
103104
try {
104105
if ($entity->save()) {
105106
$created[] = $entity;
107+
$hadSuccess = true;
108+
} else {
109+
$created[] = false;
106110
}
107111
} catch (Exceptions\EntityInvalidDataException $e) {
108112
$invalidData = true;
113+
$created[] = null;
109114
} catch (\Exception $e) {
110115
return $this->httpError(500, 'Internal Server Error', $e);
111116
}
112117
}
113-
if (empty($created)) {
118+
if (!$hadSuccess) {
114119
if ($invalidData) {
115120
return $this->httpError(400, 'Bad Request');
116121
} else {
@@ -168,7 +173,11 @@ protected function POST($action = '', $data = '') {
168173
$args['params']
169174
);
170175
header('Content-Type: application/json');
171-
echo json_encode(['entity' => $entity, 'return' => $ret]);
176+
if ($args['stateless']) {
177+
echo json_encode(['return' => $ret]);
178+
} else {
179+
echo json_encode(['entity' => $entity, 'return' => $ret]);
180+
}
172181
} catch (\Exception $e) {
173182
return $this->httpError(500, 'Internal Server Error', $e);
174183
}
@@ -232,6 +241,7 @@ protected function doPutOrPatch($action, $data, $patch) {
232241
$ents = [$ents];
233242
}
234243
$saved = [];
244+
$hadSuccess = false;
235245
$invalidData = false;
236246
$notfound = false;
237247
$lastException = null;
@@ -248,14 +258,18 @@ protected function doPutOrPatch($action, $data, $patch) {
248258
try {
249259
if ($entity->save()) {
250260
$saved[] = $entity;
261+
$hadSuccess = true;
262+
} else {
263+
$saved[] = false;
251264
}
252265
} catch (Exceptions\EntityInvalidDataException $e) {
253266
$invalidData = true;
267+
$saved[] = null;
254268
} catch (\Exception $e) {
255269
$lastException = $e;
256270
}
257271
}
258-
if (empty($saved)) {
272+
if (!$hadSuccess) {
259273
if ($invalidData) {
260274
return $this->httpError(400, 'Bad Request');
261275
} elseif ($notfound) {
@@ -468,7 +482,7 @@ protected function loadEntity($entityData, $patch = false) {
468482
* @return boolean Always returns false.
469483
*/
470484
protected function httpError($errorCode, $message, $exception = null) {
471-
header("HTTP/1.1 $errorCode $message", true, $errorCode);
485+
http_response_code($errorCode);
472486
if ($exception) {
473487
echo json_encode(
474488
[

0 commit comments

Comments
 (0)