Error.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * MINZ - Copyright 2011 Marien Fressinaud
  4. * Sous licence AGPL3 <http://www.gnu.org/licenses/>
  5. */
  6. /**
  7. * The Minz_Error class logs and raises framework errors
  8. */
  9. class Minz_Error {
  10. public function __construct() { }
  11. /**
  12. * Permet de lancer une erreur
  13. * @param int $code le type de l'erreur, par défaut 404 (page not found)
  14. * @param string|array<'error'|'warning'|'notice',array<string>> $logs logs d'erreurs découpés de la forme
  15. * > $logs['error']
  16. * > $logs['warning']
  17. * > $logs['notice']
  18. * @param bool $redirect indique s'il faut forcer la redirection (les logs ne seront pas transmis)
  19. */
  20. public static function error(int $code = 404, $logs = [], bool $redirect = true): void {
  21. $logs = self::processLogs($logs);
  22. $error_filename = APP_PATH . '/Controllers/errorController.php';
  23. if (file_exists($error_filename)) {
  24. Minz_Session::_params([
  25. 'error_code' => $code,
  26. 'error_logs' => $logs,
  27. ]);
  28. Minz_Request::forward(['c' => 'error'], $redirect);
  29. } else {
  30. echo '<h1>An error occurred</h1>' . "\n";
  31. if (!empty($logs)) {
  32. echo '<ul>' . "\n";
  33. foreach ($logs as $log) {
  34. echo '<li>' . $log . '</li>' . "\n";
  35. }
  36. echo '</ul>' . "\n";
  37. }
  38. exit();
  39. }
  40. }
  41. /**
  42. * Returns filtered logs
  43. * @param string|array<'error'|'warning'|'notice',array<string>> $logs logs sorted by category (error, warning, notice)
  44. * @return array<string> list of matching logs, without the category, according to environment preferences (production / development)
  45. */
  46. private static function processLogs($logs): array {
  47. if (is_string($logs)) {
  48. return [$logs];
  49. }
  50. $error = [];
  51. $warning = [];
  52. $notice = [];
  53. if (isset($logs['error']) && is_array($logs['error'])) {
  54. $error = $logs['error'];
  55. }
  56. if (isset($logs['warning']) && is_array($logs['warning'])) {
  57. $warning = $logs['warning'];
  58. }
  59. if (isset($logs['notice']) && is_array($logs['notice'])) {
  60. $notice = $logs['notice'];
  61. }
  62. switch (Minz_Configuration::get('system')->environment) {
  63. case 'development':
  64. return array_merge($error, $warning, $notice);
  65. case 'production':
  66. default:
  67. return $error;
  68. }
  69. }
  70. }