Executing Tasks
$this->exec()executes aMagicTask(e.g. a bind task of n2n-bind) in a controller and converts invalid input into an appropriate http response.
exec()
protected final function exec(MagicTask $magicTask, mixed $input = null,
?int $rejectStatus = Response::STATUS_400_BAD_REQUEST): ExecResult
$magicTaskis the task to execute, e.g.Bind::attrs()->...,SimpleBind::unmarshalAttrs(...)or several tasks combined withMagicTasks::pipe(). It is executed with theN2nContextof the controller, so mappers and closures of the task can use dependency injection.$inputis passed to the task as input, e.g. the parsed request body.$rejectStatusis the http status of theStatusExceptionwhich is thrown if the task throws aTaskInputMismatchException, which happens if the input does not have the expected structure (e.g. a property has the wrong type). Defaults to 400. Ifnullis passed, anIllegalStateExceptionis thrown instead.
ExecResult
exec() returns an ExecResult which wraps the TaskResult of the task:
isValid()/hasErrors()— whether the input was valid.getErrorMap()— the error messages if the input was invalid.sendErrJson()— if the result has errors, it sends them as json to the client and returnstrue; otherwise it returnsfalse.get()— the result value of the task (only available if valid).
The json sent by sendErrJson() looks like this:
{
"status": "ERR",
"errorMap": { ... }
}
Example
class GroupApiController extends ControllerAdapter {
#[Inject]
private GroupService $groupService;
function postDoNewGroup(ParamBody $body): void {
$httpData = $body->parseJsonToHttpData();
$this->beginTransaction();
$execResult = $this->exec(SimpleBind::unmarshalAttrs(NewGroupStruct::class), $httpData);
if ($execResult->sendErrJson()) {
return;
}
$newGroupStruct = $execResult->get();
$group = $this->groupService->createGroup($newGroupStruct);
$this->commit();
$this->sendJson(['group' => $group]);
}
}
The common pattern is: execute the task, return early if sendErrJson() returns true, otherwise continue with
get(). See n2n-bind in Controllers for unmarshalling the request body.