error.php 1.6 KB

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