4
0

Error.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * MINZ - Copyright 2011 Marien Fressinaud
  5. * Sous licence AGPL3 <https://www.gnu.org/licenses/>
  6. */
  7. /**
  8. * The Minz_Error class logs and raises framework errors
  9. */
  10. class Minz_Error {
  11. public function __construct() {}
  12. /**
  13. * Permet de lancer une erreur
  14. * @param int $code le type de l'erreur, par défaut 404 (page not found)
  15. * @param string|array<'error'|'warning'|'notice',list<string>> $logs logs d'erreurs découpés de la forme
  16. * > $logs['error']
  17. * > $logs['warning']
  18. * > $logs['notice']
  19. * @param bool $redirect indique s'il faut forcer la redirection (les logs ne seront pas transmis)
  20. */
  21. public static function error(int $code = 404, string|array $logs = [], bool $redirect = true): void {
  22. $logs = self::processLogs($logs);
  23. Minz_Session::_params([
  24. 'error_code' => $code,
  25. 'error_logs' => $logs,
  26. ]);
  27. // Also pass the error code by URL, in case the session is lost (session ID rotation)
  28. Minz_Request::forward(['c' => 'error', 'params' => ['code' => $code]], $redirect);
  29. }
  30. /**
  31. * Returns filtered logs
  32. * @param string|array<'error'|'warning'|'notice',list<string>> $logs logs sorted by category (error, warning, notice)
  33. * @return list<string> list of matching logs, without the category, according to environment preferences (production / development)
  34. */
  35. private static function processLogs(string|array $logs): array {
  36. if (is_string($logs)) {
  37. return [$logs];
  38. }
  39. $error = [];
  40. $warning = [];
  41. $notice = [];
  42. if (is_array($logs['error'] ?? null)) {
  43. $error = $logs['error'];
  44. }
  45. if (is_array($logs['warning'] ?? null)) {
  46. $warning = $logs['warning'];
  47. }
  48. if (is_array($logs['notice'] ?? null)) {
  49. $notice = $logs['notice'];
  50. }
  51. switch (Minz_Configuration::get('system')->environment) {
  52. case 'development':
  53. return array_merge($error, $warning, $notice);
  54. case 'production':
  55. default:
  56. return $error;
  57. }
  58. }
  59. }