Skip to content

Commit

Permalink
chore: update comments
Browse files Browse the repository at this point in the history
  • Loading branch information
ascky-thorben committed Dec 9, 2023
1 parent 55d4b69 commit d9847eb
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 8 deletions.
31 changes: 26 additions & 5 deletions lib/Rest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@

class Rest
{
public static $baseRoute = '';
private static $routes = [];
/** @var string The base route for all routes, defaults to 'api' */
public static string $baseRoute = '';

/** @var array The registered routes */
private static array $routes = [];

/**
* Registers a new route with the given arguments.
*
* @param array $routeArgs The arguments for the route
* @throws rex_exception
*/
public static function registerRoute(array $routeArgs): void
Expand All @@ -17,32 +23,44 @@ public static function registerRoute(array $routeArgs): void
self::$routes[] = new RestRoute($routeArgs);
}

/**
* Returns all registered routes.
*
* @return array The registered routes
*/
public static function getRoutes(): array
{
return self::$routes;
}

/**
* Returns the current path.
*
* @return string The current path
*/
public static function getCurrentPath(): string
{
$url = parse_url($_SERVER['REQUEST_URI']);
return trim($url['path'], '/') ?? '';
}

/**
* Handles all registered routes.
*
* @throws JsonException
* @throws rex_exception
*/
public static function handleRoutes(): bool
public static function handleRoutes(): void
{
if ('' === self::$baseRoute) {
return false;
return;
}

$currentPath = self::getCurrentPath();
$pathSegments = explode('/', $currentPath);

if ($pathSegments[0] !== self::$baseRoute) {
return false;
return;
}

foreach (self::$routes as $route) {
Expand All @@ -56,6 +74,9 @@ public static function handleRoutes(): bool
array_shift($matches);
preg_match_all('/\{[a-zA-Z0-9\_\-]+\}/', $routePath, $keys);

/**
* Extract the matched values.
*/
if (!empty($matches)) {
for ($i = 0, $iMax = count($matches); $i < $iMax; ++$i) {
$matches[trim($keys[0][$i], '{}')] = $matches[$i];
Expand Down
80 changes: 77 additions & 3 deletions lib/RestRoute.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,28 @@

class RestRoute
{
/** @var string The route to use */
protected string $route;

/** @var array The allowed request methods */
protected array $methods;

/** @var mixed The callback to execute */
protected mixed $callback;
protected array $arguments;

/** @var array The arguments for the route */
protected array $args;

/** @var array The parameters */
protected array $params;

/** @var string The permission to check */
protected string $permission;

/** @var array The validations */
protected array $validations;

/** @var array The allowed request methods */
private array $allowedMethods = [
'GET',
'POST',
Expand All @@ -31,12 +45,19 @@ public function __construct(array $args)
$this->setPermission();
}

/**
* Returns the route path.
*
* @return string The route
*/
public function getPath(): string
{
return trim($this->route, '/');
}

/**
* Sets the route.
*
* @throws rex_exception
*/
private function setRoute(): void
Expand All @@ -62,6 +83,8 @@ private function setMethods(): void
}

/**
* Validates the request methods.
*
* @throws rex_exception
*/
private function validateMethods(): void
Expand All @@ -76,6 +99,8 @@ private function validateMethods(): void
}

/**
* Validates the request method.
*
* @throws JsonException
*/
public function validateRequestMethod(): void
Expand All @@ -87,12 +112,19 @@ public function validateRequestMethod(): void
}
}

/**
* Returns the routes request method.
*
* @return string The request method
*/
public function getRequestMethod(): string
{
return rex_request::requestMethod();
}

/**
* Sets and validates the callback.
*
* @throws rex_exception
*/
private function setCallback(): void
Expand All @@ -106,6 +138,9 @@ private function setCallback(): void
}

/**
* Validates the callback.
* The callback must be callable.
*
* @throws rex_exception
*/
private function validateCallback(): void
Expand All @@ -115,6 +150,9 @@ private function validateCallback(): void
}
}

/**
* Sets the permission.
*/
public function setPermission(): void
{
if (!isset($this->args['permission']) || '' === $this->args['permission']) {
Expand All @@ -125,6 +163,9 @@ public function setPermission(): void
$this->permission = $this->args['permission'];
}

/**
* Sets the validations.
*/
public function setValidations(): void
{
if (!isset($this->args['validations']) || empty($this->args['validations'])) {
Expand All @@ -136,18 +177,23 @@ public function setValidations(): void
}

/**
* Validates the permission.
*
* @throws JsonException
*/
public function validatePermission(): void
{
if ('' !== $this->permission) {
if (!rex::getUser() || ('admin' === $this->permission && !rex::getUser()->isAdmin()) || !rex::getUser()->hasPerm($this->permission)) {
if (!rex::getUser() || ('admin' === $this->permission && !rex::getUser()->isAdmin()) || !rex::getUser(
)->hasPerm($this->permission)) {
$this->sendError('Only authenticated users can access the REST API', rex_response::HTTP_FORBIDDEN);
}
}
}

/**
* Validates all params.
*
* @throws JsonException
*/
public function validateParams(): void
Expand All @@ -164,11 +210,21 @@ public function validateParams(): void
}

if (!$this->validateType($type, $param)) {
$this->sendError(sprintf('Param "%s" needs to be "%s"!', $paramName, $type), rex_response::HTTP_BAD_REQUEST);
$this->sendError(
sprintf('Param "%s" needs to be "%s"!', $paramName, $type),
rex_response::HTTP_BAD_REQUEST,
);
}
}
}

/**
* Validates the given value against the given type.
*
* @param string $type The type to validate against
* @param mixed $value The value to validate
* @return bool
*/
private function validateType(string $type, mixed $value): bool
{
switch ($type) {
Expand All @@ -189,12 +245,22 @@ public function setParams(array $params): void
$this->params = $params;
}

/**
* Returns all params.
*
* @return array The parameters
*/
public function getParams(): array
{
return $this->params;
}

/**
* Returns the param with the given key.
* If the param does not exist, null is returned.
*
* @param string $key The key of the param
* @param string $type The type to cast the param to
* @return array|bool|float|int|mixed|object|string|null
*/
public function getParam(string $key, string $type = '')
Expand All @@ -207,6 +273,8 @@ public function getParam(string $key, string $type = '')
}

/**
* Executes the callback.
*
* @throws rex_exception
*/
public function executeCallback(): void
Expand All @@ -215,6 +283,10 @@ public function executeCallback(): void
}

/**
* Sends a response with the given content.
*
* @param array $content The content to send
* @param string $statusCode The status code to send
* @throws JsonException
* @return void
*/
Expand All @@ -228,6 +300,8 @@ public function sendContent(array $content, string $statusCode = rex_response::H
}

/**
* Sends an error response.
*
* @throws JsonException
*/
public function sendError(string $message, string $statusCode): void
Expand Down

0 comments on commit d9847eb

Please sign in to comment.