Error.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * MINZ - Copyright 2011 Marien Fressinaud
  5. * Sous licence AGPL3 <http://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. $error_filename = APP_PATH . '/Controllers/errorController.php';
  24. if (file_exists($error_filename)) {
  25. Minz_Session::_params([
  26. 'error_code' => $code,
  27. 'error_logs' => $logs,
  28. ]);
  29. Minz_Request::forward(['c' => 'error'], $redirect);
  30. } else {
  31. echo '<h1>An error occurred</h1>' . "\n";
  32. if (!empty($logs)) {
  33. echo '<ul>' . "\n";
  34. foreach ($logs as $log) {
  35. echo '<li>' . $log . '</li>' . "\n";
  36. }
  37. echo '</ul>' . "\n";
  38. }
  39. exit();
  40. }
  41. }
  42. /**
  43. * Returns filtered logs
  44. * @param string|array<'error'|'warning'|'notice',list<string>> $logs logs sorted by category (error, warning, notice)
  45. * @return list<string> list of matching logs, without the category, according to environment preferences (production / development)
  46. */
  47. private static function processLogs(string|array $logs): array {
  48. if (is_string($logs)) {
  49. return [$logs];
  50. }
  51. $error = [];
  52. $warning = [];
  53. $notice = [];
  54. if (is_array($logs['error'] ?? null)) {
  55. $error = $logs['error'];
  56. }
  57. if (is_array($logs['warning'] ?? null)) {
  58. $warning = $logs['warning'];
  59. }
  60. if (is_array($logs['notice'] ?? null)) {
  61. $notice = $logs['notice'];
  62. }
  63. switch (Minz_Configuration::get('system')->environment) {
  64. case 'development':
  65. return array_merge($error, $warning, $notice);
  66. case 'production':
  67. default:
  68. return $error;
  69. }
  70. }
  71. }