problems.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace Grav\Plugin;
  3. use Grav\Common\Plugin;
  4. use Grav\Common\Uri;
  5. use Grav\Plugin\Problems\Base\ProblemChecker;
  6. class ProblemsPlugin extends Plugin
  7. {
  8. protected $checker;
  9. protected $problems = [];
  10. /**
  11. * @return array
  12. */
  13. public static function getSubscribedEvents()
  14. {
  15. return [
  16. 'onPluginsInitialized' => ['onPluginsInitialized', 100001],
  17. 'onFatalException' => ['onFatalException', 0]
  18. ];
  19. }
  20. public function onFatalException()
  21. {
  22. if ($this->isAdmin()) {
  23. return;
  24. }
  25. // Run through potential issues
  26. if ($this->problemsFound()) {
  27. $this->renderProblems();
  28. }
  29. }
  30. public function onPluginsInitialized()
  31. {
  32. if ($this->isAdmin()) {
  33. return;
  34. }
  35. require __DIR__ . '/vendor/autoload.php';
  36. $this->checker = new ProblemChecker();
  37. if (!$this->checker->statusFileExists()) {
  38. // If no issues remain, save a state file in the cache
  39. if (!$this->problemsFound()) {
  40. // delete any existing validated files
  41. foreach (new \GlobIterator(CACHE_DIR . ProblemChecker::PROBLEMS_PREFIX . '*') as $fileInfo) {
  42. @unlink($fileInfo->getPathname());
  43. }
  44. // create a file in the cache dir so it only runs on cache changes
  45. $this->checker->storeStatusFile();
  46. } else {
  47. $this->renderProblems();
  48. }
  49. }
  50. }
  51. private function renderProblems()
  52. {
  53. /** @var Uri $uri */
  54. $uri = $this->grav['uri'];
  55. /** @var \Twig_Environment $twig */
  56. $twig = $this->getTwig();
  57. $data = [
  58. 'problems' => $this->problems,
  59. 'base_url' => $baseUrlRelative = $uri->rootUrl(false),
  60. 'problems_url' => $baseUrlRelative . '/user/plugins/problems',
  61. ];
  62. echo $twig->render('problems.html.twig', $data);
  63. http_response_code(500);
  64. exit();
  65. }
  66. private function problemsFound()
  67. {
  68. $status = $this->checker->check(__DIR__ . '/classes/Problems');
  69. $this->problems = $this->checker->getProblems();
  70. return $status;
  71. }
  72. private function getTwig()
  73. {
  74. $loader = new \Twig_Loader_Filesystem(__DIR__ . '/templates');
  75. $twig = new \Twig_Environment($loader, ['debug' => true]);
  76. $twig->addExtension(New \Twig_Extension_Debug());
  77. return $twig;
  78. }
  79. }