Created
July 30, 2023 02:29
-
-
Save Rene-Roscher/1b2382b88a468344f32c3d684fe86152 to your computer and use it in GitHub Desktop.
Extract and collect translation keys from various files in a Laravel project. The purpose of this script is to identify strings that are wrapped in translation functions or language helpers like this.__(), __() or trans() within JavaScript, PHP, and Vue files, and then save those keys into a JSON file for further processing or translation manage…
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
| <?php | |
| $vueDirectory = './resources/js'; | |
| $backendDirectory = './app'; | |
| $vendorDirectory = './vendor'; | |
| $pattern = '/(?<!\\\\)(?:this\.__|__|trans)\(\s*(["\'])((?:\\\\.|(?!\1).)*)\1/s'; | |
| $translations = []; | |
| $jsonFile = 'translations.json'; | |
| function collectKeys($directory, $pattern, &$translations): void | |
| { | |
| $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)); | |
| $regex = new RegexIterator($iterator, '/^.+\.(vue|js|php)$/i', RegexIterator::GET_MATCH); | |
| foreach ($regex as $file) { | |
| $content = file_get_contents($file[0]); | |
| if (preg_match_all($pattern, $content, $matches)) { | |
| foreach ($matches[2] as $match) { | |
| $extractedText = str_replace("\\'", "'", $match); | |
| if (!in_array($extractedText, $translations)) { | |
| $translations[$extractedText] = $extractedText; | |
| echo sprintf('[%s] - Added Key: %s', $directory, $extractedText) . PHP_EOL; | |
| } | |
| } | |
| } | |
| } | |
| } | |
| // Collect keys from Vue files | |
| collectKeys($vueDirectory, $pattern, $translations); | |
| // Collect keys from backend files | |
| collectKeys($backendDirectory, $pattern, $translations); | |
| // Collect keys from vendor files | |
| //collectKeys($vendorDirectory, $pattern, $translations); | |
| // Store the collected keys in a JSON file | |
| $translationsJson = json_encode($translations, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); | |
| file_put_contents($jsonFile, $translationsJson); | |
| echo "Translations extracted and saved to $jsonFile" . PHP_EOL; | |
| echo "Total translations: " . count($translations) . PHP_EOL; |
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
| files: | |
| - source: translations.json | |
| translation: /resources/lang/%osx_locale%.json |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment