error.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace Grav\Plugin;
  3. use Composer\Autoload\ClassLoader;
  4. use Grav\Common\Plugin;
  5. use Grav\Common\Page\Page;
  6. use Grav\Common\Page\Pages;
  7. use Grav\Common\Page\Types;
  8. use RocketTheme\Toolbox\Event\Event;
  9. class ErrorPlugin extends Plugin
  10. {
  11. /**
  12. * @return array
  13. */
  14. public static function getSubscribedEvents()
  15. {
  16. return [
  17. 'onCliInitialize' => [
  18. ['autoload', 100000],
  19. ],
  20. 'onPageNotFound' => [
  21. ['onPageNotFound', 0]
  22. ],
  23. 'onGetPageTemplates' => [
  24. ['onGetPageTemplates', 0]
  25. ],
  26. 'onTwigTemplatePaths' => [
  27. ['onTwigTemplatePaths', -10]
  28. ]
  29. ];
  30. }
  31. /**
  32. * [onPluginsInitialized:100000] Composer autoload.
  33. *
  34. * @return ClassLoader
  35. */
  36. public function autoload()
  37. {
  38. return require __DIR__ . '/vendor/autoload.php';
  39. }
  40. /**
  41. * Display error page if no page was found for the current route.
  42. *
  43. * @param Event $event
  44. */
  45. public function onPageNotFound(Event $event)
  46. {
  47. /** @var Pages $pages */
  48. $pages = $this->grav['pages'];
  49. // Try to load user error page.
  50. $page = $pages->dispatch($this->config->get('plugins.error.routes.404', '/error'), true);
  51. if ($page) {
  52. // Set default expires for error page.
  53. $header = $page->header();
  54. if (!isset($header->expires)) {
  55. $page->expires(0);
  56. }
  57. } else {
  58. // If none provided use built in error page.
  59. $page = new Page;
  60. $page->init(new \SplFileInfo(__DIR__ . '/pages/error.md'));
  61. $page->title($this->grav['language']->translate('PLUGIN_ERROR.ERROR') . ' ' . $page->header()->http_response_code);
  62. }
  63. $event->page = $page;
  64. $event->stopPropagation();
  65. }
  66. /**
  67. * Add page template types.
  68. */
  69. public function onGetPageTemplates(Event $event)
  70. {
  71. /** @var Types $types */
  72. $types = $event->types;
  73. $types->register('error');
  74. }
  75. /**
  76. * Add current directory to twig lookup paths.
  77. */
  78. public function onTwigTemplatePaths()
  79. {
  80. $this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
  81. }
  82. }