[TwigBridge] Show Twig's loader paths on debug:twig command

This commit is contained in:
Yonel Ceruto 2017-09-01 10:02:44 -04:00 committed by Fabien Potencier
parent 042328dc52
commit 3fdcb40df3
2 changed files with 52 additions and 1 deletions

View File

@ -18,6 +18,7 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
/**
* Lists twig functions, filters, globals and tests present in the current project.
@ -29,11 +30,13 @@ class DebugCommand extends Command
protected static $defaultName = 'debug:twig';
private $twig;
private $projectDir;
/**
* @param Environment $twig
* @param string|null $projectDir
*/
public function __construct($twig = null)
public function __construct($twig = null, $projectDir = null)
{
if (!$twig instanceof Environment) {
@trigger_error(sprintf('Passing a command name as the first argument of "%s" is deprecated since version 3.4 and will be removed in 4.0. If the command was registered by convention, make it a service instead.', __METHOD__), E_USER_DEPRECATED);
@ -46,6 +49,7 @@ class DebugCommand extends Command
parent::__construct();
$this->twig = $twig;
$this->projectDir = $projectDir;
}
public function setTwigEnvironment(Environment $twig)
@ -120,6 +124,7 @@ EOF
}
}
$data['tests'] = array_keys($data['tests']);
$data['loader_paths'] = $this->getLoaderPaths();
$io->writeln(json_encode($data));
return 0;
@ -145,9 +150,54 @@ EOF
$io->listing($items);
}
$rows = array();
foreach ($this->getLoaderPaths() as $namespace => $paths) {
if (count($paths) > 1) {
$rows[] = array('', '');
}
foreach ($paths as $path) {
$rows[] = array($namespace, '- '.$path);
$namespace = '';
}
if (count($paths) > 1) {
$rows[] = array('', '');
}
}
array_pop($rows);
$io->section('Loader Paths');
$io->table(array('Namespace', 'Paths'), $rows);
return 0;
}
private function getLoaderPaths()
{
if (!($loader = $this->twig->getLoader()) instanceof FilesystemLoader) {
return array();
}
$loaderPaths = array();
foreach ($loader->getNamespaces() as $namespace) {
$paths = array_map(function ($path) use ($namespace) {
if (null !== $this->projectDir && 0 === strpos($path, $this->projectDir)) {
$path = ltrim(substr($path, strlen($this->projectDir)), DIRECTORY_SEPARATOR);
}
return $path;
}, $loader->getPaths($namespace));
if (FilesystemLoader::MAIN_NAMESPACE === $namespace) {
$namespace = '(None)';
} else {
$namespace = '@'.$namespace;
}
$loaderPaths[$namespace] = $paths;
}
return $loaderPaths;
}
private function getMetadata($type, $entity)
{
if ($type === 'globals') {

View File

@ -9,6 +9,7 @@
<service id="Symfony\Bridge\Twig\Command\DebugCommand">
<argument type="service" id="twig" />
<argument>%kernel.project_dir%</argument>
<tag name="console.command" command="debug:twig" />
</service>