Skip to main content

Executing Tasks

$this->exec() executes a MagicTask (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
  • $magicTask is the task to execute, e.g. Bind::attrs()->..., SimpleBind::unmarshalAttrs(...) or several tasks combined with MagicTasks::pipe(). It is executed with the N2nContext of the controller, so mappers and closures of the task can use dependency injection.
  • $input is passed to the task as input, e.g. the parsed request body.
  • $rejectStatus is the http status of the StatusException which is thrown if the task throws a TaskInputMismatchException, which happens if the input does not have the expected structure (e.g. a property has the wrong type). Defaults to 400. If null is passed, an IllegalStateException is 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 returns true; otherwise it returns false.
  • 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.