feat: add update endpoint
This commit is contained in:
@@ -178,4 +178,87 @@ class TaskController
|
||||
return $errorResponse;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function update(ServerRequestInterface $request, ResponseInterface $response, $id): ResponseInterface
|
||||
{
|
||||
$payloadWarnings = [];
|
||||
|
||||
$toUpdate = $request->getParsedBody()['payload']['update'];
|
||||
$toUpdate['updated_at'] = Carbon::now()->toDateTimeString();
|
||||
|
||||
$acceptableFields = [
|
||||
'task_owner',
|
||||
'name',
|
||||
'description',
|
||||
'start',
|
||||
'end'
|
||||
];
|
||||
|
||||
foreach ($toUpdate as $updateField => $value)
|
||||
{
|
||||
if($updateField !== 'updated_at' && !in_array($updateField, $acceptableFields))
|
||||
{
|
||||
$payloadWarnings[] = "W: An invalid, unknown, or locked field has been truncated: " . $updateField;
|
||||
unset($toUpdate[$updateField]);
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
$task = $this->repository->readById($id);
|
||||
// if we used the dirty implementation, we could skip all this code
|
||||
|
||||
foreach($toUpdate as $property => $value)
|
||||
{
|
||||
// ignore updated_at
|
||||
if($property !== 'updated_at')
|
||||
{
|
||||
$task->{'set' . ucfirst(snakeToCamel($property))}($value);
|
||||
}
|
||||
}
|
||||
|
||||
$finalFields = array_keys($toUpdate);
|
||||
$result = $this->repository->updateSelective($task, $finalFields);
|
||||
|
||||
if ($result && empty($payloadWarnings))
|
||||
{
|
||||
return $response->withStatus(204);
|
||||
}
|
||||
elseif($result)
|
||||
{
|
||||
$this->builder->setOptionalMessage('Task updated successfully with warnings.')
|
||||
->setPayload([
|
||||
'updated' => $toUpdate,
|
||||
'warnings' => $payloadWarnings,
|
||||
]);
|
||||
$response->getBody()->write($this->builder->build());
|
||||
|
||||
return $response;
|
||||
}
|
||||
else
|
||||
{
|
||||
$this->builder->setError()
|
||||
->setErrorMessage('An unexpected error occurred while updating the resource.')
|
||||
->setErrorCode(500);
|
||||
|
||||
$errorResponse = $response->withStatus(500)->withHeader('Content-Type', 'application/json');
|
||||
$errorResponse->getBody()->write($this->builder->build());
|
||||
|
||||
return $errorResponse;
|
||||
}
|
||||
|
||||
}
|
||||
catch (TaskNotFoundException $e)
|
||||
{
|
||||
$this->builder->setError()
|
||||
->setErrorMessage($e->getMessage())
|
||||
->setErrorCode(404);
|
||||
|
||||
$errorResponse = $response->withStatus(404)->withHeader('Content-Type', 'application/json');
|
||||
$errorResponse->getBody()->write($this->builder->build());
|
||||
|
||||
return $errorResponse;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user