user_api-1.0.0-beta1/src/Event/UserApiEventBase.php
src/Event/UserApiEventBase.php
<?php
declare(strict_types=1);
namespace Drupal\user_api\Event;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\EventDispatcher\Event;
use Wunderwerk\JsonApiError\JsonApiErrorResponse;
/**
* Base class for all user api events.
*
* Each event can be aborted by calling the abort() method.
* The rest resource then returns the response from getResponse().
*/
abstract class UserApiEventBase extends Event {
/**
* If event is aborted.
*/
protected bool $aborted = FALSE;
/**
* Error code.
*/
protected string $errorCode = '';
/**
* Error message.
*/
protected string $message = '';
/**
* HTTP status code.
*/
protected int $statusCode = Response::HTTP_BAD_REQUEST;
/**
* Checks if event has been aborted.
*/
public function isAborted(): bool {
return $this->aborted;
}
/**
* Abort the event and set error code and message.
*/
public function abort(string $errorCode, string $message, ?int $statusCode) {
$this->aborted = TRUE;
$this->errorCode = $errorCode;
$this->message = $message;
if ($statusCode) {
$this->statusCode = $statusCode;
}
}
/**
* Get error response.
*/
public function getResponse(): Response {
return JsonApiErrorResponse::fromError(
status: $this->statusCode,
code: $this->errorCode,
title: $this->message,
);
}
/**
* Get event name.
*/
abstract public static function getName(): string;
}
