CodeHelper.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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\Bundle\FrameworkBundle\Templating\Helper;
  11. use Symfony\Component\Templating\Helper\Helper;
  12. /**
  13. * @author Fabien Potencier <fabien@symfony.com>
  14. */
  15. class CodeHelper extends Helper
  16. {
  17. protected $fileLinkFormat;
  18. protected $rootDir;
  19. protected $charset;
  20. /**
  21. * @param string $fileLinkFormat The format for links to source files
  22. * @param string $rootDir The project root directory
  23. * @param string $charset The charset
  24. */
  25. public function __construct($fileLinkFormat, $rootDir, $charset)
  26. {
  27. $this->fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
  28. $this->rootDir = str_replace('\\', '/', $rootDir).'/';
  29. $this->charset = $charset;
  30. }
  31. /**
  32. * Formats an array as a string.
  33. *
  34. * @param array $args The argument array
  35. *
  36. * @return string
  37. */
  38. public function formatArgsAsText(array $args)
  39. {
  40. return strip_tags($this->formatArgs($args));
  41. }
  42. public function abbrClass($class)
  43. {
  44. $parts = explode('\\', $class);
  45. $short = array_pop($parts);
  46. return sprintf('<abbr title="%s">%s</abbr>', $class, $short);
  47. }
  48. public function abbrMethod($method)
  49. {
  50. if (false !== strpos($method, '::')) {
  51. list($class, $method) = explode('::', $method, 2);
  52. $result = sprintf('%s::%s()', $this->abbrClass($class), $method);
  53. } elseif ('Closure' === $method) {
  54. $result = sprintf('<abbr title="%s">%1$s</abbr>', $method);
  55. } else {
  56. $result = sprintf('<abbr title="%s">%1$s</abbr>()', $method);
  57. }
  58. return $result;
  59. }
  60. /**
  61. * Formats an array as a string.
  62. *
  63. * @param array $args The argument array
  64. *
  65. * @return string
  66. */
  67. public function formatArgs(array $args)
  68. {
  69. $result = array();
  70. foreach ($args as $key => $item) {
  71. if ('object' === $item[0]) {
  72. $parts = explode('\\', $item[1]);
  73. $short = array_pop($parts);
  74. $formattedValue = sprintf('<em>object</em>(<abbr title="%s">%s</abbr>)', $item[1], $short);
  75. } elseif ('array' === $item[0]) {
  76. $formattedValue = sprintf('<em>array</em>(%s)', \is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
  77. } elseif ('string' === $item[0]) {
  78. $formattedValue = sprintf("'%s'", htmlspecialchars($item[1], ENT_QUOTES, $this->getCharset()));
  79. } elseif ('null' === $item[0]) {
  80. $formattedValue = '<em>null</em>';
  81. } elseif ('boolean' === $item[0]) {
  82. $formattedValue = '<em>'.strtolower(var_export($item[1], true)).'</em>';
  83. } elseif ('resource' === $item[0]) {
  84. $formattedValue = '<em>resource</em>';
  85. } else {
  86. $formattedValue = str_replace("\n", '', var_export(htmlspecialchars((string) $item[1], ENT_QUOTES, $this->getCharset()), true));
  87. }
  88. $result[] = \is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
  89. }
  90. return implode(', ', $result);
  91. }
  92. /**
  93. * Returns an excerpt of a code file around the given line number.
  94. *
  95. * @param string $file A file path
  96. * @param int $line The selected line number
  97. *
  98. * @return string An HTML string
  99. */
  100. public function fileExcerpt($file, $line)
  101. {
  102. if (is_readable($file)) {
  103. if (\extension_loaded('fileinfo')) {
  104. $finfo = new \finfo();
  105. // Check if the file is an application/octet-stream (eg. Phar file) because highlight_file cannot parse these files
  106. if ('application/octet-stream' === $finfo->file($file, FILEINFO_MIME_TYPE)) {
  107. return;
  108. }
  109. }
  110. // highlight_file could throw warnings
  111. // see https://bugs.php.net/bug.php?id=25725
  112. $code = @highlight_file($file, true);
  113. // remove main code/span tags
  114. $code = preg_replace('#^<code.*?>\s*<span.*?>(.*)</span>\s*</code>#s', '\\1', $code);
  115. $content = explode('<br />', $code);
  116. $lines = array();
  117. for ($i = max($line - 3, 1), $max = min($line + 3, \count($content)); $i <= $max; ++$i) {
  118. $lines[] = '<li'.($i == $line ? ' class="selected"' : '').'><code>'.self::fixCodeMarkup($content[$i - 1]).'</code></li>';
  119. }
  120. return '<ol start="'.max($line - 3, 1).'">'.implode("\n", $lines).'</ol>';
  121. }
  122. }
  123. /**
  124. * Formats a file path.
  125. *
  126. * @param string $file An absolute file path
  127. * @param int $line The line number
  128. * @param string $text Use this text for the link rather than the file path
  129. *
  130. * @return string
  131. */
  132. public function formatFile($file, $line, $text = null)
  133. {
  134. if (\PHP_VERSION_ID >= 50400) {
  135. $flags = ENT_QUOTES | ENT_SUBSTITUTE;
  136. } else {
  137. $flags = ENT_QUOTES;
  138. }
  139. if (null === $text) {
  140. $file = trim($file);
  141. $fileStr = $file;
  142. if (0 === strpos($fileStr, $this->rootDir)) {
  143. $fileStr = str_replace(array('\\', $this->rootDir), array('/', ''), $fileStr);
  144. $fileStr = htmlspecialchars($fileStr, $flags, $this->charset);
  145. $fileStr = sprintf('<abbr title="%s">kernel.root_dir</abbr>/%s', htmlspecialchars($this->rootDir, $flags, $this->charset), $fileStr);
  146. }
  147. $text = sprintf('%s at line %d', $fileStr, $line);
  148. }
  149. if (false !== $link = $this->getFileLink($file, $line)) {
  150. return sprintf('<a href="%s" title="Click to open this file" class="file_link">%s</a>', htmlspecialchars($link, $flags, $this->charset), $text);
  151. }
  152. return $text;
  153. }
  154. /**
  155. * Returns the link for a given file/line pair.
  156. *
  157. * @param string $file An absolute file path
  158. * @param int $line The line number
  159. *
  160. * @return string A link of false
  161. */
  162. public function getFileLink($file, $line)
  163. {
  164. if ($this->fileLinkFormat && is_file($file)) {
  165. return strtr($this->fileLinkFormat, array('%f' => $file, '%l' => $line));
  166. }
  167. return false;
  168. }
  169. public function formatFileFromText($text)
  170. {
  171. $that = $this;
  172. return preg_replace_callback('/in ("|&quot;)?(.+?)\1(?: +(?:on|at))? +line (\d+)/s', function ($match) use ($that) {
  173. return 'in '.$that->formatFile($match[2], $match[3]);
  174. }, $text);
  175. }
  176. /**
  177. * {@inheritdoc}
  178. */
  179. public function getName()
  180. {
  181. return 'code';
  182. }
  183. protected static function fixCodeMarkup($line)
  184. {
  185. // </span> ending tag from previous line
  186. $opening = strpos($line, '<span');
  187. $closing = strpos($line, '</span>');
  188. if (false !== $closing && (false === $opening || $closing < $opening)) {
  189. $line = substr_replace($line, '', $closing, 7);
  190. }
  191. // missing </span> tag at the end of line
  192. $opening = strpos($line, '<span');
  193. $closing = strpos($line, '</span>');
  194. if (false !== $opening && (false === $closing || $closing > $opening)) {
  195. $line .= '</span>';
  196. }
  197. return $line;
  198. }
  199. }