SimplePageHandler.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace Grav\Common\Errors;
  3. use Whoops\Handler\Handler;
  4. use Whoops\Util\Misc;
  5. use Whoops\Util\TemplateHelper;
  6. class SimplePageHandler extends Handler
  7. {
  8. private $searchPaths = array();
  9. private $resourceCache = array();
  10. public function __construct()
  11. {
  12. // Add the default, local resource search path:
  13. $this->searchPaths[] = __DIR__ . "/Resources";
  14. }
  15. /**
  16. * @return int|null
  17. */
  18. public function handle()
  19. {
  20. $inspector = $this->getInspector();
  21. $helper = new TemplateHelper();
  22. $templateFile = $this->getResource("layout.html.php");
  23. $cssFile = $this->getResource("error.css");
  24. $code = $inspector->getException()->getCode();
  25. $message = $inspector->getException()->getMessage();
  26. if ($inspector->getException() instanceof \ErrorException) {
  27. $code = Misc::translateErrorCode($code);
  28. }
  29. $vars = array(
  30. "stylesheet" => file_get_contents($cssFile),
  31. "code" => $code,
  32. "message" => $message,
  33. );
  34. $helper->setVariables($vars);
  35. $helper->render($templateFile);
  36. return Handler::QUIT;
  37. }
  38. /**
  39. * @param $resource
  40. *
  41. * @return string
  42. */
  43. protected function getResource($resource)
  44. {
  45. // If the resource was found before, we can speed things up
  46. // by caching its absolute, resolved path:
  47. if (isset($this->resourceCache[$resource])) {
  48. return $this->resourceCache[$resource];
  49. }
  50. // Search through available search paths, until we find the
  51. // resource we're after:
  52. foreach ($this->searchPaths as $path) {
  53. $fullPath = $path . "/$resource";
  54. if (is_file($fullPath)) {
  55. // Cache the result:
  56. $this->resourceCache[$resource] = $fullPath;
  57. return $fullPath;
  58. }
  59. }
  60. // If we got this far, nothing was found.
  61. throw new \RuntimeException(
  62. "Could not find resource '$resource' in any resource paths."
  63. . "(searched: " . join(", ", $this->searchPaths). ")"
  64. );
  65. }
  66. public function addResourcePath($path)
  67. {
  68. if (!is_dir($path)) {
  69. throw new \InvalidArgumentException(
  70. "'$path' is not a valid directory"
  71. );
  72. }
  73. array_unshift($this->searchPaths, $path);
  74. }
  75. public function getResourcePaths()
  76. {
  77. return $this->searchPaths;
  78. }
  79. }