Skip to content

Commit

Permalink
fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
felix-schindler committed Dec 3, 2022
1 parent 8af8a51 commit cc58eee
Show file tree
Hide file tree
Showing 15 changed files with 148 additions and 111 deletions.
36 changes: 18 additions & 18 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "PHPStan",
"type": "shell",
"command": "php vendor/bin/phpstan analyse -c .phpstan.neon --memory-limit 500M",
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"reveal": "always",
"focus": true,
"showReuseMessage": false,
"clear": true
}
}
]
"version": "2.0.0",
"tasks": [
{
"label": "PHPStan",
"type": "shell",
"command": "php vendor/bin/phpstan analyse -c .phpstan.neon --memory-limit 500M",
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"reveal": "always",
"focus": true,
"showReuseMessage": false,
"clear": true
}
}
]
}
3 changes: 2 additions & 1 deletion Backend/Controllers/APIController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ class APIController extends Controller
protected array $paths = ['/api/sample'];
protected array $methods = ['POST'];

protected function execute(): View {
protected function execute(): View
{
return new APIView();
}
}
3 changes: 2 additions & 1 deletion Backend/Controllers/HomeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ class HomeController extends Controller
{
protected array $paths = ['/'];

protected function execute(): View {
protected function execute(): View
{
$layout = new LayoutView();
$layout->addChild(new HeadingView('Home'));
return $layout;
Expand Down
3 changes: 2 additions & 1 deletion Backend/Controllers/SecondHome.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ class SecondHome extends Controller
{
protected array $paths = ['/article/:id'];

protected function execute(): View {
protected function execute(): View
{
$layout = new LayoutView();
$layout->addChild(new TextView('Welcome to another route'));
if (($id = $this->param('id')) !== null) {
Expand Down
4 changes: 2 additions & 2 deletions Backend/Core/Data/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ public function __construct()
*
* @param string $queryStr SQL query as string
* @param array<string,string> $values Escaped values
* @throws PDOException When anything goes wrong
* @return bool Whether the query was executed successfully
* @throws PDOException When anything goes wrong
* @return bool Whether the query was executed successfully
*/
public function execute(string $queryStr, array $values): bool
{
Expand Down
9 changes: 6 additions & 3 deletions Backend/Core/Functions/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ class Auth
* @param string|null $token The auth (bearer) token
* @return boolean True if valid, otherwise false
*/
public static function validateToken(?string $token = null): bool {
public static function validateToken(?string $token = null): bool
{
if ($token === null) {
if (($token = IO::authHeader()) == null) {
return false;
Expand Down Expand Up @@ -46,7 +47,8 @@ public static function validateToken(?string $token = null): bool {
*
* @return string|null
*/
public static function tokenUuid(): ?string {
public static function tokenUuid(): ?string
{
if (($token = IO::authHeader()) != null) {
if (($decoded = base64_decode($token)) !== false) {
$decToken = explode(".", $decoded);
Expand All @@ -64,7 +66,8 @@ public static function tokenUuid(): ?string {
* @param string $hash Password hash of a user
* @return string Valid token for the next 30 days
*/
public static function generateToken(string $uuid, string $hash): string {
public static function generateToken(string $uuid, string $hash): string
{
$validUntil = (new DateTime())->add(new DateInterval('P30D'))->format("Y-m-d");
$hashHash = password_hash($hash, PASSWORD_DEFAULT);
return base64_encode(base64_encode($uuid) . "." . base64_encode($hashHash) . "." . base64_encode($validUntil));
Expand Down
11 changes: 7 additions & 4 deletions Backend/Core/Functions/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,20 @@ class Utils
* @param string $algo Hashing algorithmn - Standard: SHA256
* @return string Hashed data
*/
public static function encrypt(string $data, string $algo = 'sha256'): string {
public static function encrypt(string $data, string $algo = 'sha256'): string
{
return hash($algo, $data);
}

/**
* Generates a random uuid (Version 4)
*
* @param string|null $data Random bytes
* @throws Exception If an appropriate source of randomness cannot be found on the system
* @throws Exception If an appropriate source of randomness cannot be found on the system
* @return string A random uuid
*/
public static function uuid(?string $data = null): string {
public static function uuid(?string $data = null): string
{
// Generate 16 bytes (128 bits) of random data or use the data passed into the function.
$data ??= random_bytes(16);
assert(strlen($data) == 16);
Expand All @@ -43,7 +45,8 @@ public static function uuid(?string $data = null): string {
* @param string $uuid String to be checked
* @return boolean Whether it's the correct format or not
*/
public static function isUUID(string $uuid): bool {
public static function isUUID(string $uuid): bool
{
return preg_match("/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i", $uuid) === 1;
}
}
15 changes: 10 additions & 5 deletions Backend/Core/System/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ abstract class Controller
*
* @throws Exception When a path is already taken
*/
public function initRoutes(): void {
public function initRoutes(): void
{
foreach ($this->paths as $path)
Router::addRoute($path, $this);
}
Expand All @@ -47,7 +48,8 @@ public function initRoutes(): void {
* @param array<string,string> $params Parameters
* @throws Exception If there's no request URI set
*/
public function runExecute(array $params): void {
public function runExecute(array $params): void
{
if (($code = $this->checkAccess()) === 200) {
$this->params = $params;
$this->execute()->render();
Expand All @@ -67,7 +69,8 @@ abstract protected function execute(): View;
* @param string $var Name of variable
* @return string|null Value of variable or null if not exists
*/
protected function param(string $var): ?string {
protected function param(string $var): ?string
{
if (isset($this->params[$var]) && is_string($this->params[$var]))
return htmlspecialchars(urldecode(strval($this->params[$var])));
return null;
Expand All @@ -79,7 +82,8 @@ protected function param(string $var): ?string {
* @param string $url Redirectes to this
* @return never No code execution after this
*/
protected function redirect(string $url): never {
protected function redirect(string $url): never
{
header('Location: ' . $url);
exit;
}
Expand All @@ -90,7 +94,8 @@ protected function redirect(string $url): never {
* @throws Exception If there's no request method set
* @return int HTTP status code (200 === OK!)
*/
private function checkAccess(): int {
private function checkAccess(): int
{
$method = IO::method();
header('Access-Control-Allow-Methods: ' . implode(', ', array_merge(['OPTIONS', 'HEAD'], $this->methods)));
if (empty(array_intersect(['*', 'OPTIONS', 'HEAD', $method], $this->methods)))
Expand Down
15 changes: 9 additions & 6 deletions Backend/Core/System/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ class Router
*
* @throws Exception When not on server and not accessing via HTTPS or localhost
*/
public static function 艳颖(): void {
public static function 艳颖(): void
{
// Either access via localhost or HTTPS
if (!isset($_SERVER["HTTPS"]) && !(IO::domain() === "localhost"))
throw new Exception("Only access over HTTPS allowed");
Expand All @@ -32,7 +33,7 @@ public static function 艳颖(): void {
$routes = array_keys(self::$routes); // Get all routes as string
$reqRouteArr = explode("/", $reqRoute); // Split requested route

$routes = array_filter($routes, function($route) use ($reqRouteArr): bool { // Filter out all routes that don't match
$routes = array_filter($routes, function ($route) use ($reqRouteArr): bool { // Filter out all routes that don't match
$routeArr = explode("/", $route);
if (str_contains($route, ':')) // Only routes with variables, on direct hit it would have already exited
if (count($routeArr) == count($reqRouteArr)) // Routes have to same length to be a match
Expand All @@ -45,7 +46,7 @@ public static function 艳颖(): void {
foreach ($routes as $route) { // Calculate scores to get the route that fits best
$routeArr = explode("/", $route);
$hits[$route] = 0;
for ($i=0; $i < count($routeArr); $i++) {
for ($i = 0; $i < count($routeArr); $i++) {
if ($routeArr[$i] == $reqRouteArr[$i]) // Prioritise direct routes over variables
$hits[$route]++; // Increment hit score
elseif ($routeArr[$i][0] != ":") { // Remove route if does not match and not a variable
Expand All @@ -62,7 +63,7 @@ public static function 艳颖(): void {

$routeArr = explode("/", $route);
$params = [];
for ($i=0; $i < count($routeArr); $i++)
for ($i = 0; $i < count($routeArr); $i++)
if (isset($routeArr[$i][0]) && $routeArr[$i][0] === ":") // If part of URL is a variable
$params[substr($routeArr[$i], 1)] = $reqRouteArr[$i]; // Set as param (this could be a on-liner)
self::$routes[$route]->runExecute($params); // Execute controller for found route
Expand All @@ -80,7 +81,8 @@ public static function 艳颖(): void {
* @param Controller $con Controller to handle route
* @throws Exception When a route already exists with another controller
*/
public static function addRoute(string $route, Controller $con): void {
public static function addRoute(string $route, Controller $con): void
{
if (self::routeExists($route, $con))
throw new Exception("Route " . $route . " already used for " . self::$routes[$route]::class);
self::$routes[$route] = $con;
Expand All @@ -93,7 +95,8 @@ public static function addRoute(string $route, Controller $con): void {
* @param Controller|null $con Controller to be routed to
* @return boolean True if exists, false otherwise
*/
private static function routeExists(string $route, ?Controller $con = null): bool {
private static function routeExists(string $route, ?Controller $con = null): bool
{
if (isset(self::$routes[$route])) {
if ($con === null)
return true;
Expand Down
9 changes: 6 additions & 3 deletions Backend/Core/System/View.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,17 @@ abstract public function render(): void;
* @param View $child A child
* @return View Current view
*/
public function addChild(View $child): View {
public function addChild(View $child): View
{
$this->children[] = $child;
return $this;
}

/**
* Render children
*/
public function renderChildren(?string $element = null): void {
public function renderChildren(?string $element = null): void
{
foreach ($this->children as $child) {
if ($element === null)
$child->render();
Expand All @@ -41,7 +43,8 @@ public function renderChildren(?string $element = null): void {
/**
* Get rendered HTML as string
*/
public function __toString(): string {
public function __toString(): string
{
ob_start();
$this->render();
if (($content = ob_get_clean()) !== false)
Expand Down
6 changes: 4 additions & 2 deletions Backend/Views/Base/APIView.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ class APIView extends View
public function __construct(
public ?array $data = null,
private readonly int $maxAge = 300
){}
) {
}

public function render(): void {
public function render(): void
{
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: ' . DOMAIN);
header('Access-Control-Allow-Headers: Authorization, Origin, X-Requested-With, Content-Type, Accept');
Expand Down
8 changes: 5 additions & 3 deletions Backend/Views/Base/ErrorView.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ public function __construct(
public int $code = 404,
public bool $isAPI = false,
public ?string $message = null
){}
) {
}

public function render(): void {
public function render(): void
{
if ($this->message === null) {
$this->message = match($this->code) {
$this->message = match ($this->code) {
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
Expand Down
Loading

0 comments on commit cc58eee

Please sign in to comment.