FileLinkFormatter.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\Debug;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\RequestStack;
  13. /**
  14. * Formats debug file links.
  15. *
  16. * @author Jérémy Romey <jeremy@free-agent.fr>
  17. */
  18. class FileLinkFormatter implements \Serializable
  19. {
  20. private $fileLinkFormat;
  21. private $requestStack;
  22. private $baseDir;
  23. private $urlFormat;
  24. public function __construct($fileLinkFormat = null, RequestStack $requestStack = null, $baseDir = null, $urlFormat = null)
  25. {
  26. $fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
  27. if ($fileLinkFormat && !is_array($fileLinkFormat)) {
  28. $i = strpos($f = $fileLinkFormat, '&', max(strrpos($f, '%f'), strrpos($f, '%l'))) ?: strlen($f);
  29. $fileLinkFormat = array(substr($f, 0, $i)) + preg_split('/&([^>]++)>/', substr($f, $i), -1, PREG_SPLIT_DELIM_CAPTURE);
  30. }
  31. $this->fileLinkFormat = $fileLinkFormat;
  32. $this->requestStack = $requestStack;
  33. $this->baseDir = $baseDir;
  34. $this->urlFormat = $urlFormat;
  35. }
  36. public function format($file, $line)
  37. {
  38. if ($fmt = $this->getFileLinkFormat()) {
  39. for ($i = 1; isset($fmt[$i]); ++$i) {
  40. if (0 === strpos($file, $k = $fmt[$i++])) {
  41. $file = substr_replace($file, $fmt[$i], 0, strlen($k));
  42. break;
  43. }
  44. }
  45. return strtr($fmt[0], array('%f' => $file, '%l' => $line));
  46. }
  47. return false;
  48. }
  49. public function serialize()
  50. {
  51. return serialize($this->getFileLinkFormat());
  52. }
  53. public function unserialize($serialized)
  54. {
  55. if (\PHP_VERSION_ID >= 70000) {
  56. $this->fileLinkFormat = unserialize($serialized, array('allowed_classes' => false));
  57. } else {
  58. $this->fileLinkFormat = unserialize($serialized);
  59. }
  60. }
  61. private function getFileLinkFormat()
  62. {
  63. if ($this->fileLinkFormat) {
  64. return $this->fileLinkFormat;
  65. }
  66. if ($this->requestStack && $this->baseDir && $this->urlFormat) {
  67. $request = $this->requestStack->getMasterRequest();
  68. if ($request instanceof Request) {
  69. return array(
  70. $request->getSchemeAndHttpHost().$request->getBaseUrl().$this->urlFormat,
  71. $this->baseDir.DIRECTORY_SEPARATOR, '',
  72. );
  73. }
  74. }
  75. }
  76. }