Controller.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Controllers;
  3. use App\Exceptions\AuthenticationException;
  4. use App\Exceptions\UnauthorizedException;
  5. use App\Web\Session;
  6. use Flight;
  7. use League\Flysystem\Adapter\Local;
  8. use League\Flysystem\Filesystem;
  9. abstract class Controller
  10. {
  11. /**
  12. * @throws AuthenticationException
  13. */
  14. protected function checkLogin(): void
  15. {
  16. if (!Session::get('logged', false)) {
  17. Session::set('redirectTo', (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
  18. throw new AuthenticationException();
  19. }
  20. }
  21. /**
  22. * @throws AuthenticationException
  23. * @throws UnauthorizedException
  24. */
  25. protected function checkAdmin(): void
  26. {
  27. $this->checkLogin();
  28. if (!Session::get('admin', false)) {
  29. throw new UnauthorizedException();
  30. }
  31. }
  32. protected function humanFilesize($size, $precision = 2): string
  33. {
  34. for ($i = 0; ($size / 1024) > 0.9; $i++, $size /= 1024) {
  35. }
  36. return round($size, $precision) . ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][$i];
  37. }
  38. protected function getStorage(): Filesystem
  39. {
  40. return new Filesystem(new Local(Flight::get('config')['storage_dir']));
  41. }
  42. protected function http2push(string $url, string $as = 'image'): void
  43. {
  44. if (Flight::request()->scheme === 'HTTP/2.0') {
  45. $headers = isset(Flight::response()->headers()['Link']) ? Flight::response()->headers()['Link'] : [];
  46. $headers[] = "<${url}>; rel=preload; as=${as}";
  47. Flight::response()->header('Link', $headers);
  48. }
  49. }
  50. }