Repository navigation
Overwrite 'i18n extract' to make it able to parse twig templates too. #121
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Antronin
wants to merge
10
commits into
cakephp:2.x
Choose a base branch
from
Antronin:TwigI18nExtract
base: 2.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4cceed9
Overwrite 'i18n extract' to make it able to parse twig templates too.
Antronin 383a348
Fix PHP code style issues based on rector
Antronin 858dd7f
Additional style fixes based on phpcs
Antronin b280622
Increase test coverage
Antronin 2cd3682
Fix phpstan issues
Antronin dacbfb0
Change the order of use statements.
Antronin e7130f8
Correct some additional rector issues not connected to my changes.
Antronin 389efb7
Use FQCN For ProgressHelper as it has an alias
Antronin dfaeaba
remove FQDN from reference
Antronin 45d5444
Update according to received comments
Antronin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,382 @@ | ||
| <?php | ||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) | ||
| * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) | ||
| * | ||
| * Licensed under The MIT License | ||
| * For full copyright and license information, please see the LICENSE.txt | ||
| * Redistributions of files must retain the above copyright notice. | ||
| * | ||
| * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) | ||
| * @link https://cakephp.org CakePHP(tm) Project | ||
| * @since 2.2.0 | ||
| * @license https://opensource.org/licenses/mit-license.php MIT License | ||
| */ | ||
|
|
||
| namespace Cake\TwigView\Command; | ||
|
|
||
| use Cake\Command\I18nExtractCommand; | ||
| use Cake\Console\Arguments; | ||
| use Cake\Console\ConsoleIo; | ||
| use Cake\Console\Helper\ProgressHelper; | ||
| use Cake\Utility\Filesystem; | ||
| use Twig\Environment; | ||
| use Twig\Loader\ArrayLoader; | ||
| use Twig\Source; | ||
| use Twig\Token; | ||
| use function count; | ||
| use function in_array; | ||
| use function is_array; | ||
|
|
||
| /** | ||
| * Language string extractor | ||
| */ | ||
| class TwigExtractCommand extends I18nExtractCommand | ||
| { | ||
| /** | ||
| * @inheritDoc | ||
| */ | ||
| public static function defaultName(): string | ||
| { | ||
| return 'i18n extract'; | ||
| } | ||
|
|
||
| /** | ||
| * @inheritDoc | ||
| */ | ||
| public static function getDescription(): string | ||
| { | ||
| return 'Extract i18n POT files from application files and twig templates.'; | ||
| } | ||
|
|
||
| /** | ||
| * Extract tokens out of all files to be processed | ||
| * | ||
| * @param \Cake\Console\Arguments $args The io instance | ||
| * @param \Cake\Console\ConsoleIo $io The io instance | ||
| * @return void | ||
| */ | ||
| protected function _extractTokens(Arguments $args, ConsoleIo $io): void | ||
| { | ||
| /** | ||
| * @var ProgressHelper $progress | ||
|
Check failure on line 64 in src/Command/TwigExtractCommand.php
|
||
| */ | ||
| $progress = $io->helper('Progress'); | ||
| $progress->init(['total' => count($this->_files)]); | ||
| $isVerbose = $args->getOption('verbose'); | ||
|
|
||
| $functions = [ | ||
| '__' => ['singular'], | ||
| '__n' => ['singular', 'plural'], | ||
| '__d' => ['domain', 'singular'], | ||
| '__dn' => ['domain', 'singular', 'plural'], | ||
| '__x' => ['context', 'singular'], | ||
| '__xn' => ['context', 'singular', 'plural'], | ||
| '__dx' => ['domain', 'context', 'singular'], | ||
| '__dxn' => ['domain', 'context', 'singular', 'plural'], | ||
| ]; | ||
| $pattern = '/(' . implode('|', array_keys($functions)) . ')\s*\(/'; | ||
|
|
||
| foreach ($this->_files as $file) { | ||
| $this->_file = $file; | ||
| if ($isVerbose) { | ||
| $io->verbose(sprintf('Processing %s...', $file)); | ||
| } | ||
| if (pathinfo($file, PATHINFO_EXTENSION) === 'twig') { | ||
| if ($this->_isTwigUsable()) { | ||
| $_parser = 'twig'; | ||
| } else { | ||
| $io->warning('Twig is not installed. Please install Twig to extract translations from twig templates.'); | ||
| continue; | ||
| } | ||
| $_parser = 'twig'; | ||
| } else { | ||
| $_parser = 'php'; | ||
| } | ||
| $code = (string)file_get_contents($file); | ||
|
|
||
| if (preg_match($pattern, $code) === 1) { | ||
| if ($_parser === 'twig') { | ||
| $this->_tokenizeAsTwig($code, $file); | ||
| } else { | ||
| $this->_tokenizeAsPHP($code, $file); | ||
| } | ||
|
|
||
| foreach ($functions as $functionName => $map) { | ||
| if ($_parser === 'twig') { | ||
| $this->_parseAsTwig($io, $functionName, $map); | ||
| } else { | ||
| $this->_parseAsPHP($io, $functionName, $map); | ||
| } | ||
| } | ||
| } | ||
| if ($_parser === 'php') { | ||
| $this->extractFileReflection($file, $code); | ||
| } | ||
|
|
||
| if (!$isVerbose) { | ||
| $progress->increment(1); | ||
| $progress->draw(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Parse tokens | ||
| * | ||
| * @param \Cake\Console\ConsoleIo $io The io instance | ||
| * @param string $functionName Function name that indicates translatable string (e.g: '__') | ||
| * @param array $map Array containing what variables it will find (e.g: domain, singular, plural) | ||
| * @return void | ||
| */ | ||
| protected function _parseAsPHP(ConsoleIo $io, string $functionName, array $map): void | ||
| { | ||
| $count = 0; | ||
| $tokenCount = count($this->_tokens); | ||
|
|
||
| while ($tokenCount - $count > 1) { | ||
| $countToken = $this->_tokens[$count]; | ||
| $firstParenthesis = $this->_tokens[$count + 1]; | ||
| if (!is_array($countToken)) { | ||
| $count++; | ||
| continue; | ||
| } | ||
|
|
||
| [$type, $string, $line] = $countToken; | ||
| if (($type === T_STRING) && ($string === $functionName) && ($firstParenthesis === '(')) { | ||
| $position = $count; | ||
| $depth = 0; | ||
|
|
||
| while (!$depth) { | ||
| if ($this->_tokens[$position] === '(') { | ||
| $depth++; | ||
| } elseif ($this->_tokens[$position] === ')') { | ||
| $depth--; | ||
| } | ||
| $position++; | ||
| } | ||
|
|
||
| $mapCount = count($map); | ||
| $strings = $this->_getStrings($position, $mapCount); | ||
|
|
||
| if ($mapCount === count($strings)) { | ||
| $singular = ''; | ||
| $vars = array_combine($map, $strings); | ||
| extract($vars); | ||
| $domain ??= 'default'; | ||
| $details = [ | ||
| 'file' => $this->_file, | ||
| 'line' => $line, | ||
| ]; | ||
| $details['file'] = '.' . str_replace(ROOT, '', $details['file']); | ||
| if (isset($plural)) { | ||
| $details['msgid_plural'] = $plural; | ||
| } | ||
| if (isset($context)) { | ||
| $details['msgctxt'] = $context; | ||
| } | ||
| $this->_addTranslation($domain, $singular, $details); | ||
| } else { | ||
| $this->_markerError($io, $this->_file, $line, $functionName, $count); | ||
| } | ||
| } | ||
| $count++; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Parse Twig tokens | ||
| * | ||
| * @param \Cake\Console\ConsoleIo $io The io instance | ||
| * @param string $functionName Function name that indicates translatable string (e.g: '__') | ||
| * @param array $map Array containing what variables it will find (e.g: domain, singular, plural) | ||
| * @return void | ||
| */ | ||
| protected function _parseAsTwig(ConsoleIo $io, string $functionName, array $map): void | ||
| { | ||
| /** @var \Twig\Token $token */ | ||
| foreach ($this->_tokens as $count => $token) { | ||
| if ($token->test(Token::NAME_TYPE, $functionName)) { | ||
| $singular = ''; | ||
| switch ($functionName) { | ||
| case '__': | ||
| $singular = $this->_getStringFromToken($count, 2); | ||
| break; | ||
| case '__n': | ||
| $singular = $this->_getStringFromToken($count, 2); | ||
| $plural = $this->_getStringFromToken($count, 4); | ||
| break; | ||
| case '__d': | ||
| $domain = $this->_getStringFromToken($count, 2); | ||
| $singular = $this->_getStringFromToken($count, 4); | ||
| break; | ||
| case '__dn': | ||
| $domain = $this->_getStringFromToken($count, 2); | ||
| $singular = $this->_getStringFromToken($count, 4); | ||
| $plural = $this->_getStringFromToken($count, 6); | ||
| break; | ||
| case '__x': | ||
| $context = $this->_getStringFromToken($count, 2); | ||
| $singular = $this->_getStringFromToken($count, 4); | ||
| break; | ||
| case '__xn': | ||
| $context = $this->_getStringFromToken($count, 2); | ||
| $singular = $this->_getStringFromToken($count, 4); | ||
| $plural = $this->_getStringFromToken($count, 6); | ||
| break; | ||
| case '__dx': | ||
| $domain = $this->_getStringFromToken($count, 2); | ||
| $context = $this->_getStringFromToken($count, 4); | ||
| $singular = $this->_getStringFromToken($count, 6); | ||
| break; | ||
| case '__dxn': | ||
| $domain = $this->_getStringFromToken($count, 2); | ||
| $context = $this->_getStringFromToken($count, 4); | ||
| $singular = $this->_getStringFromToken($count, 6); | ||
| $plural = $this->_getStringFromToken($count, 8); | ||
| break; | ||
| } | ||
| $domain ??= 'default'; | ||
| $details = [ | ||
| 'file' => $this->_file, | ||
| 'line' => $token->getLine(), | ||
| ]; | ||
| $details['file'] = '.' . str_replace(ROOT, '', $details['file']); | ||
| if (in_array('plural', $map)) { | ||
| if (isset($plural)) { | ||
| $details['msgid_plural'] = $plural; | ||
| } else { | ||
| $this->_markerError($io, $this->_file, $token->getLine(), $functionName, $token->getOffset() ?? 0); | ||
| continue; | ||
| } | ||
| } | ||
|
|
||
| if (in_array('context', $map)) { | ||
| if (isset($context)) { | ||
| $details['msgctxt'] = $context; | ||
| } else { | ||
| $this->_markerError($io, $this->_file, $token->getLine(), $functionName, $token->getOffset() ?? 0); | ||
| continue; | ||
| } | ||
| } | ||
| $this->_addTranslation($domain, $singular, $details); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Search files that may contain translatable strings | ||
| * | ||
| * @return void | ||
| */ | ||
| protected function _searchFiles(): void | ||
| { | ||
| $pattern = false; | ||
| if ($this->_exclude) { | ||
| $exclude = []; | ||
| foreach ($this->_exclude as $e) { | ||
| if (DIRECTORY_SEPARATOR !== '\\' && !str_starts_with($e, DIRECTORY_SEPARATOR)) { | ||
| $e = DIRECTORY_SEPARATOR . $e; | ||
| } | ||
| $exclude[] = preg_quote($e, '/'); | ||
| } | ||
| $pattern = '/' . implode('|', $exclude) . '/'; | ||
| } | ||
|
|
||
| foreach ($this->_paths as $path) { | ||
| $path = realpath($path); | ||
| if ($path === false) { | ||
| continue; | ||
| } | ||
| $path .= DIRECTORY_SEPARATOR; | ||
| $fs = new Filesystem(); | ||
| $files = $fs->findRecursive($path, '/\.php$|\.twig$/'); | ||
| $files = array_keys(iterator_to_array($files)); | ||
| sort($files); | ||
| if ($pattern) { | ||
| $files = preg_grep($pattern, $files, PREG_GREP_INVERT) ?: []; | ||
| $files = array_values($files); | ||
| } | ||
| $this->_files = array_merge($this->_files, $files); | ||
| } | ||
| $this->_files = array_unique($this->_files); | ||
| } | ||
|
|
||
| /** | ||
| * Checks whether the Twig templating system is available. | ||
| * | ||
| * @return bool true if Twig is autoloadable and usable, false otherwise | ||
| */ | ||
| protected function _isTwigUsable(): bool | ||
| { | ||
| return class_exists(Environment::class); | ||
| } | ||
|
|
||
| /** | ||
| * Parses the given PHP source code for tokens, filtering out whitespace and inline HTML. | ||
| * | ||
| * @param string $code Source code of the file to parse | ||
| * @param string $file File name and path of the file to parse | ||
| * @return void | ||
| */ | ||
| protected function _tokenizeAsPHP(string $code, string $file): void | ||
| { | ||
| $allTokens = token_get_all($code); | ||
| $this->_tokens = []; | ||
| foreach ($allTokens as $token) { | ||
| if (!is_array($token) || ($token[0] !== T_WHITESPACE && $token[0] !== T_INLINE_HTML)) { | ||
| $this->_tokens[] = $token; | ||
| } | ||
| } | ||
| unset($allTokens); | ||
| } | ||
|
|
||
| /** | ||
| * Parses the given Twig source code for tokens. | ||
| * | ||
| * @param string $code Source code of the file to parse | ||
| * @param string $file File name and path of the file to parse | ||
| * @return void | ||
| */ | ||
| protected function _tokenizeAsTwig(string $code, string $file): void | ||
| { | ||
| $twig = new Environment(new ArrayLoader()); | ||
| $stream = $twig->tokenize(new Source(code: $code, name: $file, path: $file)); | ||
| $this->_tokens = []; | ||
| while (!$stream->isEOF()) { | ||
| $token = $stream->next(); | ||
| if (! $token->test(Token::TEXT_TYPE) && ! $token->test(Token::BLOCK_END_TYPE)) { | ||
| $this->_tokens[] = $token; | ||
| } | ||
| } | ||
| unset($stream); | ||
| } | ||
|
|
||
| /** | ||
| * Return the string represented by a token and offset | ||
| * | ||
| * It also escapes double quotes with backslash: " -> \" | ||
| * | ||
| * @param int $position The position of the token in $this->_tokens | ||
| * @param int $offset The offset from that position. | ||
| * @return string The escaped string | ||
| */ | ||
| protected function _getStringFromToken(int $position, int $offset): string | ||
| { | ||
| $string = $this->_tokens[$position + $offset]->getValue(); | ||
|
|
||
| return str_replace('"', '\"', $string); | ||
| } | ||
|
|
||
| /** | ||
| * Adding this here to fix a PHP 8.2 error in the tests | ||
| * | ||
| * @return void | ||
| */ | ||
| protected function extractFileReflection(string $file, string $code): void | ||
| { | ||
| parent::extractFileReflection($file, $code); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Extending the core command class could make this brittle in the future. We don't provide any backward compatibility promises on protected APIs (which you're using quite a bit here).
What if we had a separate command that only processed twig files, and left the core
i18n extractcommand alone?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would not do it. When you have Twig in your project, you can still have PHP files containing translatable strings. So this must be an enhancement to the I18nExtractCommand, not a separate solution.
And using two separate commands (one for Twig and one for all PHP files) will not work, because the second one running won't know about the first's findings.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe the solution is to update I18nExtractCommand to support additional parsers for different file types; what I did is a step in that direction.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, ideally the core
I18nExtractCommandneeds to be made flexible so that it can be configured to use custom parses and storage types.My use case is that I want to store the message in the database instead of the pot files. I too have extended and overwritten parts of core's
I18nExtractto achieve that which isn't very nice https://github.com/ADmad/cakephp-i18n/blob/master/src/Command/I18nExtractCommand.php