4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpKernel\Debug;
14 use Symfony\Component\HttpFoundation\Request;
15 use Symfony\Component\HttpFoundation\RequestStack;
16 use Symfony\Component\Routing\Exception\ExceptionInterface;
17 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
20 * Formats debug file links.
22 * @author Jérémy Romey <jeremy@free-agent.fr>
24 class FileLinkFormatter implements \Serializable
26 private $fileLinkFormat;
27 private $requestStack;
32 * @param string|\Closure $urlFormat the URL format, or a closure that returns it on-demand
34 public function __construct($fileLinkFormat = null, RequestStack $requestStack = null, $baseDir = null, $urlFormat = null)
36 $fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
37 if ($fileLinkFormat && !\is_array($fileLinkFormat)) {
38 $i = strpos($f = $fileLinkFormat, '&', max(strrpos($f, '%f'), strrpos($f, '%l'))) ?: \strlen($f);
39 $fileLinkFormat = array(substr($f, 0, $i)) + preg_split('/&([^>]++)>/', substr($f, $i), -1, PREG_SPLIT_DELIM_CAPTURE);
42 $this->fileLinkFormat = $fileLinkFormat;
43 $this->requestStack = $requestStack;
44 $this->baseDir = $baseDir;
45 $this->urlFormat = $urlFormat;
48 public function format($file, $line)
50 if ($fmt = $this->getFileLinkFormat()) {
51 for ($i = 1; isset($fmt[$i]); ++$i) {
52 if (0 === strpos($file, $k = $fmt[$i++])) {
53 $file = substr_replace($file, $fmt[$i], 0, \strlen($k));
58 return strtr($fmt[0], array('%f' => $file, '%l' => $line));
64 public function serialize()
66 return serialize($this->getFileLinkFormat());
69 public function unserialize($serialized)
71 if (\PHP_VERSION_ID >= 70000) {
72 $this->fileLinkFormat = unserialize($serialized, array('allowed_classes' => false));
74 $this->fileLinkFormat = unserialize($serialized);
81 public static function generateUrlFormat(UrlGeneratorInterface $router, $routeName, $queryString)
84 return $router->generate($routeName).$queryString;
85 } catch (ExceptionInterface $e) {
90 private function getFileLinkFormat()
92 if ($this->fileLinkFormat) {
93 return $this->fileLinkFormat;
95 if ($this->requestStack && $this->baseDir && $this->urlFormat) {
96 $request = $this->requestStack->getMasterRequest();
97 if ($request instanceof Request) {
98 if ($this->urlFormat instanceof \Closure && !$this->urlFormat = \call_user_func($this->urlFormat)) {
103 $request->getSchemeAndHttpHost().$request->getBasePath().$this->urlFormat,
104 $this->baseDir.\DIRECTORY_SEPARATOR, '',