This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Bundle/FrameworkBundle/Command/TranslationDebugCommand.php

370 lines
13 KiB
PHP
Raw Normal View History

2014-01-19 23:09:51 +00:00
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Command;
use Symfony\Component\Console\Style\SymfonyStyle;
2014-01-19 23:09:51 +00:00
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Translation\Catalogue\MergeOperation;
use Symfony\Component\Translation\Extractor\ExtractorInterface;
2014-01-19 23:09:51 +00:00
use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Reader\TranslationReaderInterface;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\DataCollectorTranslator;
use Symfony\Component\Translation\LoggingTranslator;
use Symfony\Component\Translation\TranslatorInterface;
2014-01-19 23:09:51 +00:00
/**
* Helps finding unused or missing translation messages in a given locale
* and comparing them with the fallback ones.
*
* @author Florian Voutzinos <florian@voutzinos.com>
*
* @final since version 3.4
2014-01-19 23:09:51 +00:00
*/
class TranslationDebugCommand extends ContainerAwareCommand
{
const MESSAGE_MISSING = 0;
const MESSAGE_UNUSED = 1;
const MESSAGE_EQUALS_FALLBACK = 2;
protected static $defaultName = 'debug:translation';
2017-08-06 11:59:30 +01:00
private $translator;
private $reader;
2017-08-06 11:59:30 +01:00
private $extractor;
/**
* @param TranslatorInterface $translator
* @param TranslationReaderInterface $reader
* @param ExtractorInterface $extractor
*/
public function __construct($translator = null, TranslationReaderInterface $reader = null, ExtractorInterface $extractor = null)
{
if (!$translator instanceof TranslatorInterface) {
@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);
2017-08-06 11:59:30 +01:00
parent::__construct($translator);
return;
}
2017-08-06 11:59:30 +01:00
parent::__construct();
$this->translator = $translator;
$this->reader = $reader;
$this->extractor = $extractor;
}
2014-01-19 23:09:51 +00:00
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setDefinition(array(
new InputArgument('locale', InputArgument::REQUIRED, 'The locale'),
new InputArgument('bundle', InputArgument::OPTIONAL, 'The bundle name or directory where to load the messages, defaults to app/Resources folder'),
2014-01-19 23:09:51 +00:00
new InputOption('domain', null, InputOption::VALUE_OPTIONAL, 'The messages domain'),
new InputOption('only-missing', null, InputOption::VALUE_NONE, 'Displays only missing messages'),
new InputOption('only-unused', null, InputOption::VALUE_NONE, 'Displays only unused messages'),
new InputOption('all', null, InputOption::VALUE_NONE, 'Load messages from all registered bundles'),
2014-01-19 23:09:51 +00:00
))
->setDescription('Displays translation messages information')
2016-10-30 09:34:06 +00:00
->setHelp(<<<'EOF'
The <info>%command.name%</info> command helps finding unused or missing translation
messages and comparing them with the fallback ones by inspecting the
templates and translation files of a given bundle or the app folder.
2014-01-19 23:09:51 +00:00
You can display information about bundle translations in a specific locale:
2014-01-19 23:09:51 +00:00
2015-01-04 09:52:37 +00:00
<info>php %command.full_name% en AcmeDemoBundle</info>
2014-01-19 23:09:51 +00:00
You can also specify a translation domain for the search:
2015-01-04 09:52:37 +00:00
<info>php %command.full_name% --domain=messages en AcmeDemoBundle</info>
2014-01-19 23:09:51 +00:00
You can only display missing messages:
2015-01-04 09:52:37 +00:00
<info>php %command.full_name% --only-missing en AcmeDemoBundle</info>
2014-01-19 23:09:51 +00:00
You can only display unused messages:
2015-01-04 09:52:37 +00:00
<info>php %command.full_name% --only-unused en AcmeDemoBundle</info>
You can display information about app translations in a specific locale:
<info>php %command.full_name% en</info>
You can display information about translations in all registered bundles in a specific locale:
<info>php %command.full_name% --all en</info>
2014-01-19 23:09:51 +00:00
EOF
)
;
}
/**
* {@inheritdoc}
*
* BC to be removed in 4.0
*/
public function isEnabled()
{
if (null !== $this->translator) {
return parent::isEnabled();
}
if (!class_exists('Symfony\Component\Translation\Translator')) {
return false;
}
return parent::isEnabled();
}
2014-01-19 23:09:51 +00:00
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
// BC to be removed in 4.0
if (null === $this->translator) {
$this->translator = $this->getContainer()->get('translator');
$this->reader = $this->getContainer()->get('translation.reader');
$this->extractor = $this->getContainer()->get('translation.extractor');
}
$io = new SymfonyStyle($input, $output);
2014-01-19 23:09:51 +00:00
$locale = $input->getArgument('locale');
$domain = $input->getOption('domain');
/** @var KernelInterface $kernel */
$kernel = $this->getApplication()->getKernel();
// Define Root Path to App folder
$transPaths = array($kernel->getRootDir().'/Resources/');
// Override with provided Bundle info
if (null !== $input->getArgument('bundle')) {
try {
$bundle = $kernel->getBundle($input->getArgument('bundle'));
$transPaths = array(
$bundle->getPath().'/Resources/',
sprintf('%s/Resources/%s/', $kernel->getRootDir(), $bundle->getName()),
);
} catch (\InvalidArgumentException $e) {
// such a bundle does not exist, so treat the argument as path
$transPaths = array($input->getArgument('bundle').'/Resources/');
if (!is_dir($transPaths[0])) {
throw new \InvalidArgumentException(sprintf('"%s" is neither an enabled bundle nor a directory.', $transPaths[0]));
}
}
} elseif ($input->getOption('all')) {
foreach ($kernel->getBundles() as $bundle) {
$transPaths[] = $bundle->getPath().'/Resources/';
$transPaths[] = sprintf('%s/Resources/%s/', $kernel->getRootDir(), $bundle->getName());
}
}
2014-01-19 23:09:51 +00:00
// Extract used messages
$extractedCatalogue = $this->extractMessages($locale, $transPaths);
2014-01-19 23:09:51 +00:00
// Load defined messages
$currentCatalogue = $this->loadCurrentMessages($locale, $transPaths);
2014-01-19 23:09:51 +00:00
// Merge defined and extracted messages to get all message ids
$mergeOperation = new MergeOperation($extractedCatalogue, $currentCatalogue);
$allMessages = $mergeOperation->getResult()->all($domain);
if (null !== $domain) {
$allMessages = array($domain => $allMessages);
}
// No defined or extracted messages
if (empty($allMessages) || null !== $domain && empty($allMessages[$domain])) {
$outputMessage = sprintf('No defined or extracted messages for locale "%s"', $locale);
2014-01-19 23:09:51 +00:00
if (null !== $domain) {
$outputMessage .= sprintf(' and domain "%s"', $domain);
}
2014-01-19 23:09:51 +00:00
$io->getErrorStyle()->warning($outputMessage);
2014-01-19 23:09:51 +00:00
return;
}
2014-01-19 23:09:51 +00:00
// Load the fallback catalogues
$fallbackCatalogues = $this->loadFallbackCatalogues($locale, $transPaths);
2014-01-19 23:09:51 +00:00
// Display header line
$headers = array('State', 'Domain', 'Id', sprintf('Message Preview (%s)', $locale));
2014-01-19 23:09:51 +00:00
foreach ($fallbackCatalogues as $fallbackCatalogue) {
$headers[] = sprintf('Fallback Message Preview (%s)', $fallbackCatalogue->getLocale());
}
$rows = array();
2014-01-19 23:09:51 +00:00
// Iterate all message ids and determine their state
foreach ($allMessages as $domain => $messages) {
foreach (array_keys($messages) as $messageId) {
$value = $currentCatalogue->get($messageId, $domain);
$states = array();
if ($extractedCatalogue->defines($messageId, $domain)) {
if (!$currentCatalogue->defines($messageId, $domain)) {
$states[] = self::MESSAGE_MISSING;
}
} elseif ($currentCatalogue->defines($messageId, $domain)) {
$states[] = self::MESSAGE_UNUSED;
}
if (!in_array(self::MESSAGE_UNUSED, $states) && true === $input->getOption('only-unused')
|| !in_array(self::MESSAGE_MISSING, $states) && true === $input->getOption('only-missing')) {
continue;
}
foreach ($fallbackCatalogues as $fallbackCatalogue) {
if ($fallbackCatalogue->defines($messageId, $domain) && $value === $fallbackCatalogue->get($messageId, $domain)) {
2014-01-19 23:09:51 +00:00
$states[] = self::MESSAGE_EQUALS_FALLBACK;
2014-01-19 23:09:51 +00:00
break;
}
}
$row = array($this->formatStates($states), $domain, $this->formatId($messageId), $this->sanitizeString($value));
2014-01-19 23:09:51 +00:00
foreach ($fallbackCatalogues as $fallbackCatalogue) {
$row[] = $this->sanitizeString($fallbackCatalogue->get($messageId, $domain));
}
$rows[] = $row;
2014-01-19 23:09:51 +00:00
}
}
2014-01-19 23:09:51 +00:00
$io->table($headers, $rows);
2014-01-19 23:09:51 +00:00
}
private function formatState($state)
{
if (self::MESSAGE_MISSING === $state) {
return '<error> missing </error>';
2014-01-19 23:09:51 +00:00
}
if (self::MESSAGE_UNUSED === $state) {
return '<comment> unused </comment>';
2014-01-19 23:09:51 +00:00
}
if (self::MESSAGE_EQUALS_FALLBACK === $state) {
return '<info> fallback </info>';
2014-01-19 23:09:51 +00:00
}
return $state;
}
private function formatStates(array $states)
{
$result = array();
foreach ($states as $state) {
$result[] = $this->formatState($state);
}
return implode(' ', $result);
}
private function formatId($id)
{
return sprintf('<fg=cyan;options=bold>%s</>', $id);
2014-01-19 23:09:51 +00:00
}
private function sanitizeString($string, $length = 40)
2014-01-19 23:09:51 +00:00
{
$string = trim(preg_replace('/\s+/', ' ', $string));
2015-10-14 15:40:43 +01:00
if (false !== $encoding = mb_detect_encoding($string, null, true)) {
if (mb_strlen($string, $encoding) > $length) {
return mb_substr($string, 0, $length - 3, $encoding).'...';
2014-01-19 23:09:51 +00:00
}
} elseif (strlen($string) > $length) {
return substr($string, 0, $length - 3).'...';
2014-01-19 23:09:51 +00:00
}
return $string;
}
/**
* @param string $locale
* @param array $transPaths
*
* @return MessageCatalogue
*/
private function extractMessages($locale, $transPaths)
{
$extractedCatalogue = new MessageCatalogue($locale);
foreach ($transPaths as $path) {
$path = $path.'views';
if (is_dir($path)) {
$this->extractor->extract($path, $extractedCatalogue);
}
}
return $extractedCatalogue;
}
/**
* @param string $locale
* @param array $transPaths
*
* @return MessageCatalogue
*/
private function loadCurrentMessages($locale, $transPaths)
{
$currentCatalogue = new MessageCatalogue($locale);
foreach ($transPaths as $path) {
$path = $path.'translations';
if (is_dir($path)) {
$this->reader->read($path, $currentCatalogue);
}
}
return $currentCatalogue;
}
/**
* @param string $locale
* @param array $transPaths
*
* @return MessageCatalogue[]
*/
private function loadFallbackCatalogues($locale, $transPaths)
{
$fallbackCatalogues = array();
if ($this->translator instanceof Translator || $this->translator instanceof DataCollectorTranslator || $this->translator instanceof LoggingTranslator) {
foreach ($this->translator->getFallbackLocales() as $fallbackLocale) {
if ($fallbackLocale === $locale) {
continue;
}
$fallbackCatalogue = new MessageCatalogue($fallbackLocale);
foreach ($transPaths as $path) {
$path = $path.'translations';
if (is_dir($path)) {
$this->reader->read($path, $fallbackCatalogue);
}
}
$fallbackCatalogues[] = $fallbackCatalogue;
}
}
return $fallbackCatalogues;
}
2014-01-19 23:09:51 +00:00
}