error.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace Grav\Plugin;
  3. use Grav\Common\Plugin;
  4. use Grav\Common\Grav;
  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. 'onPageNotFound' => ['onPageNotFound', 0],
  18. 'onGetPageTemplates' => ['onGetPageTemplates', 0],
  19. ];
  20. }
  21. /**
  22. * Display error page if no page was found for the current route.
  23. *
  24. * @param Event $event
  25. */
  26. public function onPageNotFound(Event $event)
  27. {
  28. $this->enable([
  29. 'onTwigTemplatePaths' => ['onTwigTemplatePaths', -10]
  30. ]);
  31. /** @var Pages $pages */
  32. $pages = $this->grav['pages'];
  33. // Try to load user error page.
  34. $page = $pages->dispatch($this->config->get('plugins.error.routes.404', '/error'), true);
  35. if (!$page) {
  36. // If none provided use built in error page.
  37. $page = new Page;
  38. $page->init(new \SplFileInfo(__DIR__ . '/pages/error.md'));
  39. }
  40. $event->page = $page;
  41. $event->stopPropagation();
  42. }
  43. /**
  44. * Add page template types.
  45. */
  46. public function onGetPageTemplates(Event $event)
  47. {
  48. /** @var Types $types */
  49. $types = $event->types;
  50. $types->register('error');
  51. }
  52. /**
  53. * Add current directory to twig lookup paths.
  54. */
  55. public function onTwigTemplatePaths()
  56. {
  57. $this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
  58. }
  59. }