Last active
November 7, 2017 11:21
Script (PHP) to extract all translatable strings from Craft CMS templates located in a specific folder
This file contains 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
<?php | |
/** | |
* @author Quentin Delcourt <quentin@delcourt.be> | |
* @date 2017-06-21 | |
* | |
* This script will take a folder path in argument and will extract | |
* all translatable strings from the Craft templates encountered | |
* in the given folder. Each one of these will be | |
* outputted to stdOut in CSV format. | |
* | |
* If no folder path is provided, the script will look | |
* in the current folder. | |
* | |
* Usage: | |
* php extract-translations.php path/to/templates | |
*/ | |
/** | |
* Recursively explore all .html files in a directory | |
* and find every single occurence of a string to be translated. | |
* | |
* @param $folder Relative path to the folder containing the templates | |
* @return array | |
*/ | |
function findTranslations($folder) | |
{ | |
$allMatches = []; | |
$filesPattern = '/\.html$/'; | |
$regex = '/\'((?:[^\\\'\\\\]|\\\\.)*)\'\\|translate/'; | |
$directory = new RecursiveDirectoryIterator($folder); | |
$iterator = new RecursiveIteratorIterator($directory); | |
$files = new RegexIterator($iterator, $filesPattern); | |
foreach ($files as $template) { | |
$content = file_get_contents($template); | |
$matches = []; | |
preg_match_all($regex, $content, $matches); | |
if(count($matches) > 1) { | |
foreach($matches[1] as $match) { | |
$allMatches[] = $match; | |
} | |
} | |
} | |
$allMatches = array_unique($allMatches); | |
asort($allMatches); | |
return $allMatches; | |
} | |
/** | |
* Output a list of strings on stdOut in CSV format. | |
* | |
* @param $matches | |
*/ | |
function outputCsv($matches) | |
{ | |
$stdOut = fopen('php://output', 'w'); | |
foreach($matches as $match) { | |
fputcsv($stdOut, [$match]); | |
} | |
} | |
$folder = (count($argv) > 1) ? $argv[1] : '.'; | |
$translations = outputCsv(findTranslations($folder)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment