├── .github └── workflows │ ├── integration.yml │ └── tests.yml ├── .gitignore ├── LICENSE ├── README.md ├── composer.json ├── composer.lock ├── phpcs.xml ├── phpunit.xml ├── src ├── Framework │ ├── LaravelConfigLoader.php │ ├── TranslatorCommand.php │ ├── TranslatorServiceProvider.php │ ├── config.php │ └── helpers.php ├── Infra │ ├── Exception │ │ ├── InvalidTranslationFile.php │ │ ├── TranslationFileDoesNotExistForLanguage.php │ │ └── UnableToSaveTranslationKeyAlreadyExists.php │ └── LaravelJsonTranslationRepository.php └── Translator │ ├── ConfigLoader.php │ ├── Exception │ ├── InvalidDirectoriesConfiguration.php │ ├── InvalidExtensionsConfiguration.php │ └── InvalidFunctionsConfiguration.php │ ├── Translation.php │ ├── TranslationRepository.php │ ├── TranslationScanner.php │ └── TranslationService.php └── tests ├── Fixtures ├── App │ ├── Functions │ │ ├── Lang │ │ │ └── LangTranslation.php │ │ └── UnderscoreUnderscore │ │ │ └── UnderscoreUnderscoreTranslation.php │ └── View │ │ ├── Component.vue │ │ └── index.blade.php ├── Glob │ ├── SubDir │ │ ├── SubDir2 │ │ │ ├── SubDir2file1.txt │ │ │ └── SubDir2file2.txt │ │ ├── SubDirFile1.txt │ │ └── SubDirFile2.txt │ ├── file1.txt │ └── file2.txt └── translations │ ├── bg.json │ ├── de.json │ ├── en.json │ ├── es.json │ ├── fr.json │ ├── pt.json │ └── ru.json ├── Unit ├── Framework │ └── HelperTest.php ├── Infra │ └── LaravelJsonTranslationRepositoryTest.php └── Translator │ ├── TranslationScannerTest.php │ └── TranslationServiceTest.php └── integration.php /.github/workflows/integration.yml: -------------------------------------------------------------------------------- 1 | name: Integration Test 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | 7 | jobs: 8 | integration: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - uses: actions/checkout@v2 13 | 14 | - name: Setup PHP 15 | uses: shivammathur/setup-php@v2 16 | with: 17 | php-version: '7.4' 18 | 19 | - name: Install Laravel 20 | run: composer create-project --prefer-dist laravel/laravel blog 21 | 22 | - name: Require translator package 23 | run: composer require thiagocordeiro/laravel-translator:dev-master -d blog/ 24 | 25 | - name: Copy Fixtures 1 26 | run: cp -R tests/Fixtures/App/Functions blog/app 27 | 28 | - name: Copy Fixtures 2 29 | run: cp -R tests/Fixtures/App/View blog/resources/views 30 | 31 | - name: Remove default english translation folder 32 | run: rm -rf blog/resources/lang/en 33 | 34 | - name: Create empty translation files 35 | run: echo "{}" >> blog/resources/lang/pt-br.json && echo "{}" >> blog/resources/lang/es.json 36 | 37 | - name: Copy integration test file 38 | run: cp tests/integration.php blog/ 39 | 40 | - name: Run translation command 41 | run: cd blog ; php artisan translator:update 42 | 43 | - name: Check created files 44 | run: cd blog ; php integration.php 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Unit Tests 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | tests: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v2 15 | 16 | - name: Setup PHP 17 | uses: shivammathur/setup-php@v2 18 | with: 19 | php-version: '7.4' 20 | 21 | - name: Validate composer.json and composer.lock 22 | run: composer validate 23 | 24 | - name: Cache Composer packages 25 | id: composer-cache 26 | uses: actions/cache@v2 27 | with: 28 | path: vendor 29 | key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} 30 | restore-keys: | 31 | ${{ runner.os }}-php- 32 | 33 | - name: Install dependencies 34 | if: steps.composer-cache.outputs.cache-hit != 'true' 35 | run: composer install --prefer-dist --no-progress --no-suggest 36 | 37 | - name: Check code standards 38 | run: composer run test:cs 39 | 40 | - name: Check static analysis 41 | run: composer run test:stan 42 | 43 | - name: Unit Tests 44 | run: composer run test:unit 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .phpunit.result.cache 2 | /.idea/ 3 | /vendor/ 4 | .DS_Store 5 | /tests/var 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Thiago Cordeiro dos Santos 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel-Translator 2 | 3 | Laravel-translator scans your project `resources/view/` and `app/` folder to find `@lang(...)`, `lang(...)` and `__(...)` 4 | functions, then it create keys based on first parameter value and insert into json translation files. 5 | 6 | ### Installation 7 | 8 | You just have to require the package 9 | 10 | ```bash 11 | composer require thiagocordeiro/laravel-translator 12 | ``` 13 | 14 | This package register the provider automatically, 15 | [See laravel package discover](https://laravel.com/docs/5.5/packages#package-discovery). 16 | 17 | After composer finish installing, you'll be able to update your project translation keys running the following command: 18 | 19 | ```bash 20 | php artisan translator:update 21 | ``` 22 | 23 | if for any reason artisan can't find `translator:update` command, you can register the provider manually on your `config/app.php` file: 24 | 25 | ```php 26 | return [ 27 | ... 28 | 'providers' => [ 29 | ... 30 | Translator\Framework\TranslatorServiceProvider::class, 31 | ... 32 | ] 33 | ] 34 | ``` 35 | 36 | ### Usage 37 | 38 | First you have to create your json translation files: 39 | 40 | ``` 41 | app/ 42 | resources/ 43 | lang/ 44 | pt-br.json 45 | es.json 46 | fr.json 47 | ... 48 | ``` 49 | 50 | Keep working as you are used to, when laravel built-in translation funcion can't find given key, 51 | it'll return itself, so if you create english keys, you don't need to create an english translation. 52 | 53 | ```php-template 54 | blade: 55 | 56 | @lang('Hello World') 57 | {{ lang('Hello World') }} 58 | {{ __('Hello World') }} 59 | 60 | 61 | controllers, models, etc.: 62 | base_path('lang'), 93 | ``` 94 | 95 | ### Customization 96 | 97 | You can change the default path of views to scan and the output of the json translation files. 98 | 99 | First, publish the configuration file. 100 | 101 | ```bash 102 | php artisan vendor:publish --provider="Translator\Framework\TranslatorServiceProvider" 103 | ``` 104 | 105 | On ``config/translator.php`` you can change the default values of `languages`, `default_language`, `use_keys_as_default_value`, `directories`, `functions`, `output` or if you have a different implementation to save/load translations, you can create your own`translation_repository`and replace on`container` config 106 | 107 | ```php 108 | use Translator\Framework\LaravelConfigLoader; 109 | use Translator\Infra\LaravelJsonTranslationRepository; 110 | 111 | return [ 112 | 'languages' => ['pt-br', 'es'], 113 | 'directories' => [ 114 | app_path(), 115 | resource_path('views'), 116 | ], 117 | 'functions' => ['lang', '__'], 118 | 'output' => resource_path('lang'), 119 | 'container' => [ 120 | 'config_loader' => LaravelConfigLoader::class, 121 | 'translation_repository' => LaravelJsonTranslationRepository::class, 122 | ], 123 | ]; 124 | ``` 125 | 126 | ## Using your keys as the default value 127 | 128 | For the default language, most of the time you wish to use the key values as the default translation value. You can enable this by settingd the config option `use_keys_as_default_value` to `true`, and defining a `default_language` to your language. This is by default configured to `en`, but can be overruled by setting the `default_language` key in your config. 129 | 130 | ### Tips 131 | 132 | - Laravel `trans(...)` function doesn't use json files for translation, so you'd better using `__(...)` or it's alias `lang(...)` on php files and `@lang(...)` or `{{ lang(...) }}` on blade files. 133 | - Do not use variables on translation functions, the scanner just get the key if it's a string 134 | 135 | ### Todo 136 | 137 | - View for translate phrases; 138 | - Integration with some translation api (google or deepl) for automatic translations 139 | 140 | 141 | ### Supporting 142 | If you feel like supporting changes then you can send donations to the address below. 143 | 144 | Bitcoin Address: bc1qfyudlcxqnvqzxxgpvsfmadwudg4znk2z3asj9h 145 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "thiagocordeiro/laravel-translator", 3 | "description": "Search translation keys and insert into json to be translated", 4 | "type": "project", 5 | "license": "MIT", 6 | "authors": [ 7 | { 8 | "name": "Thiago Cordeiro", 9 | "email": "thiagoguetten@gmail.com" 10 | } 11 | ], 12 | "require": { 13 | "php": "^7.4|^8.0", 14 | "ext-json": "*", 15 | "laravel/framework": ">=5.4.0" 16 | }, 17 | "require-dev": { 18 | "slevomat/coding-standard": "^6.0", 19 | "phpstan/phpstan": "^0.12", 20 | "phpunit/phpunit": "^9.0" 21 | }, 22 | "scripts": { 23 | "test:cs": "vendor/bin/phpcs --colors -ps", 24 | "test:stan": "vendor/bin/phpstan analyse src --level=max --ansi", 25 | "test:unit": "vendor/bin/phpunit --testdox --color=always", 26 | "tests": [ 27 | "@test:cs", 28 | "@test:stan", 29 | "@test:unit" 30 | ] 31 | }, 32 | "config": { 33 | "platform": { 34 | "php": "7.4.28" 35 | }, 36 | "allow-plugins": { 37 | "dealerdirect/phpcodesniffer-composer-installer": true 38 | } 39 | }, 40 | "autoload": { 41 | "psr-4": { 42 | "Translator\\": "src/" 43 | }, 44 | "files": [ 45 | "src/Framework/helpers.php" 46 | ] 47 | }, 48 | "autoload-dev": { 49 | "psr-4": { 50 | "Translator\\Tests\\": "tests" 51 | } 52 | }, 53 | "extra": { 54 | "laravel": { 55 | "providers": [ 56 | "Translator\\Framework\\TranslatorServiceProvider" 57 | ] 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /phpcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | ./src 4 | ./tests 5 | 6 | 7 | 8 | 9 | error 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | ../tests/* 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 0 63 | 64 | 65 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | src 15 | 16 | src/Framework/config.php 17 | 18 | 19 | 20 | 21 | 22 | 23 | tests 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/Framework/LaravelConfigLoader.php: -------------------------------------------------------------------------------- 1 | loadConfigInArray('languages'); 15 | } 16 | 17 | /** 18 | * @inheritDoc 19 | */ 20 | public function defaultLanguage(): string 21 | { 22 | $defaultLanguage = $this->loadConfigInString('default_language'); 23 | 24 | if ($defaultLanguage === '') { 25 | return 'en'; 26 | } 27 | 28 | return $defaultLanguage; 29 | } 30 | 31 | /** 32 | * @inheritDoc 33 | */ 34 | public function useKeysAsDefaultValue(): bool 35 | { 36 | return !! $this->load('use_keys_as_default_value'); 37 | } 38 | 39 | /** 40 | * @inheritDoc 41 | */ 42 | public function directories(): array 43 | { 44 | return $this->loadConfigInArray('directories'); 45 | } 46 | 47 | /** 48 | * @inheritDoc 49 | */ 50 | public function output(): string 51 | { 52 | return $this->loadConfigInString('output'); 53 | } 54 | 55 | /** 56 | * @inheritDoc 57 | */ 58 | public function extensions(): array 59 | { 60 | return $this->loadConfigInArray('extensions'); 61 | } 62 | 63 | /** 64 | * @inheritDoc 65 | */ 66 | public function functions(): array 67 | { 68 | return $this->loadConfigInArray('functions'); 69 | } 70 | 71 | /** 72 | * @return array 73 | */ 74 | private function loadConfigInArray(string $key): array 75 | { 76 | $values = $this->load($key); 77 | 78 | if (!is_array($values)) { 79 | return []; 80 | } 81 | 82 | return $values; 83 | } 84 | 85 | private function loadConfigInString(string $key): string 86 | { 87 | $value = $this->load($key); 88 | 89 | if (!is_string($value)) { 90 | return ''; 91 | } 92 | 93 | return $value; 94 | } 95 | 96 | /** 97 | * @return string|string[] 98 | */ 99 | private function load(string $key) 100 | { 101 | return config("translator.{$key}"); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/Framework/TranslatorCommand.php: -------------------------------------------------------------------------------- 1 | service = $service; 26 | } 27 | 28 | public function handle(): void 29 | { 30 | $this->service->scanAndSaveNewKeys(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Framework/TranslatorServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->runningInConsole()) { 17 | $this->commands([TranslatorCommand::class]); 18 | } 19 | 20 | $this->setupConfigs(); 21 | $this->setupContainer(); 22 | } 23 | 24 | private function setupConfigs(): void 25 | { 26 | $default = __DIR__."/config.php"; 27 | $custom = base_path("config/translator.php"); 28 | 29 | $this->mergeConfigFrom($default, 'translator'); 30 | $this->publishes([$default => $custom], 'config'); 31 | } 32 | 33 | private function setupContainer(): void 34 | { 35 | $this->app->bind(ConfigLoader::class, config('translator.container.config_loader')); 36 | $this->app->bind(TranslationRepository::class, config('translator.container.translation_repository')); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Framework/config.php: -------------------------------------------------------------------------------- 1 | ['pt-br', 'es'], 8 | 'directories' => [ 9 | app_path(), 10 | resource_path('views'), 11 | ], 12 | 'output' => resource_path('lang'), 13 | 'extensions' => ['php'], 14 | 'functions' => ['lang', '__'], 15 | 'container' => [ 16 | 'config_loader' => LaravelConfigLoader::class, 17 | 'translation_repository' => LaravelJsonTranslationRepository::class, 18 | ], 19 | ]; 20 | -------------------------------------------------------------------------------- /src/Framework/helpers.php: -------------------------------------------------------------------------------- 1 | |null 8 | */ 9 | function lang(string $key, array $replace = [], ?string $locale = null) 10 | { 11 | return __($key, $replace, $locale); 12 | } 13 | } 14 | 15 | if (!function_exists('glob_recursive')) { 16 | /** 17 | * @return string[] 18 | */ 19 | function glob_recursive(string $pattern, int $flags = 0): array 20 | { 21 | $files = glob($pattern, $flags); 22 | 23 | if (!$files) { 24 | $files = []; 25 | } 26 | 27 | $directories = glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) ?? []; 28 | 29 | if (!$directories) { 30 | $directories = []; 31 | } 32 | 33 | return array_reduce($directories, function (array $files, string $dir) use ($pattern, $flags): array { 34 | return array_merge( 35 | $files, 36 | glob_recursive($dir . '/' . basename($pattern), $flags) 37 | ); 38 | }, $files); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Infra/Exception/InvalidTranslationFile.php: -------------------------------------------------------------------------------- 1 | getKey(), 16 | $language 17 | ) 18 | ); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Infra/LaravelJsonTranslationRepository.php: -------------------------------------------------------------------------------- 1 | > */ 17 | private array $fileCache = []; 18 | 19 | public function __construct(ConfigLoader $config) 20 | { 21 | $this->config = $config; 22 | } 23 | 24 | /** 25 | * @throws TranslationFileDoesNotExistForLanguage 26 | * @throws InvalidTranslationFile 27 | */ 28 | public function exists(Translation $translation, string $language): bool 29 | { 30 | $translations = $this->getTranslations($language); 31 | 32 | return isset($translations[$translation->getKey()]); 33 | } 34 | 35 | /** 36 | * @throws InvalidTranslationFile 37 | * @throws TranslationFileDoesNotExistForLanguage 38 | * @throws UnableToSaveTranslationKeyAlreadyExists 39 | */ 40 | public function save(Translation $translation, string $language): void 41 | { 42 | $translations = $this->getTranslations($language); 43 | 44 | if ($this->exists($translation, $language)) { 45 | throw new UnableToSaveTranslationKeyAlreadyExists($translation, $language); 46 | } 47 | 48 | $translations[$translation->getKey()] = $this->useKeyAsDefaultValue($translation, $language) ? 49 | $translation->getKey() : 50 | $translation->getValue(); 51 | 52 | $this->fileCache[$language] = $translations; 53 | 54 | $this->writeFile($language); 55 | } 56 | 57 | /** 58 | * @throws TranslationFileDoesNotExistForLanguage 59 | * @throws InvalidTranslationFile 60 | * @return array 61 | */ 62 | private function getTranslations(string $language): array 63 | { 64 | if (!isset($this->fileCache[$language])) { 65 | $this->fileCache[$language] = $this->readFile($language); 66 | } 67 | 68 | return $this->fileCache[$language]; 69 | } 70 | 71 | private function getFileNameForLanguage(string $language): string 72 | { 73 | $directory = $this->config->output(); 74 | 75 | return $directory . "/{$language}.json"; 76 | } 77 | 78 | /** 79 | * @return string[] 80 | * @throws InvalidTranslationFile 81 | * @throws TranslationFileDoesNotExistForLanguage 82 | */ 83 | private function readFile(string $language): array 84 | { 85 | $filename = $this->getFileNameForLanguage($language); 86 | 87 | if (!file_exists($filename)) { 88 | throw new TranslationFileDoesNotExistForLanguage($language); 89 | } 90 | 91 | $content = file_get_contents($filename); 92 | 93 | if (!$content) { 94 | throw new InvalidTranslationFile($language); 95 | } 96 | 97 | $translations = json_decode($content, true); 98 | 99 | if (json_last_error() !== JSON_ERROR_NONE) { 100 | throw new InvalidTranslationFile($language); 101 | } 102 | 103 | return $translations; 104 | } 105 | 106 | private function writeFile(string $language): void 107 | { 108 | $content = $this->fileCache[$language]; 109 | ksort($content); 110 | 111 | file_put_contents( 112 | $this->getFileNameForLanguage($language), 113 | json_encode($content, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) 114 | ); 115 | } 116 | 117 | private function useKeyAsDefaultValue(Translation $translation, string $language): bool 118 | { 119 | return empty($translation->getValue()) && 120 | $this->config->defaultLanguage() === $language && 121 | $this->config->useKeysAsDefaultValue(); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/Translator/ConfigLoader.php: -------------------------------------------------------------------------------- 1 | 11 | */ 12 | public function languages(): array; 13 | 14 | /** 15 | * Specifies the default language. 16 | */ 17 | public function defaultLanguage(): string; 18 | 19 | /** 20 | * Defines if the keys for the default language should be used as the default value 21 | */ 22 | public function useKeysAsDefaultValue(): bool; 23 | 24 | /** 25 | * Load the list of directories to be scanned 26 | * 27 | * @return array 28 | */ 29 | public function directories(): array; 30 | 31 | /** 32 | * Load the directory where the updated translation file will be written 33 | */ 34 | public function output(): string; 35 | 36 | /** 37 | * Load the list of file extensions to be scanned 38 | * 39 | * @return array 40 | */ 41 | public function extensions(): array; 42 | 43 | /** 44 | * Load the list of functions to be scanned 45 | * 46 | * @return array 47 | */ 48 | public function functions(): array; 49 | } 50 | -------------------------------------------------------------------------------- /src/Translator/Exception/InvalidDirectoriesConfiguration.php: -------------------------------------------------------------------------------- 1 | key = $key; 13 | $this->value = $value; 14 | } 15 | 16 | public function getKey(): string 17 | { 18 | return $this->key; 19 | } 20 | 21 | public function getValue(): string 22 | { 23 | return $this->value; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Translator/TranslationRepository.php: -------------------------------------------------------------------------------- 1 | scanDirectory($directory, $ext, $functions) 42 | ); 43 | }, 44 | [] 45 | ); 46 | } 47 | 48 | /** 49 | * @param string[] $functions 50 | * @return Translation[] 51 | */ 52 | private function scanDirectory(string $path, string $extensions, array $functions): array 53 | { 54 | $files = glob_recursive("{$path}/*.{{$extensions}}", GLOB_BRACE); 55 | 56 | return array_reduce($files, function (array $keys, $file) use ($functions): array { 57 | $content = $this->getFileContent($file); 58 | 59 | $keysFromFunctions = array_reduce( 60 | $functions, 61 | function (array $keys, string $function) use ($content): array { 62 | return array_merge($keys, $this->getKeysFromFunction($function, $content)); 63 | }, 64 | [] 65 | ); 66 | 67 | return array_merge( 68 | $keys, 69 | $keysFromFunctions 70 | ); 71 | }, []); 72 | } 73 | 74 | private function getFileContent(string $filePath): string 75 | { 76 | $content = (string) file_get_contents($filePath) ?? ''; 77 | 78 | return str_replace("\n", ' ', $content); 79 | } 80 | 81 | /** 82 | * @return string[] 83 | */ 84 | private function getKeysFromFunction(string $functionName, string $content): array 85 | { 86 | preg_match_all("#{$functionName} *\( *((['\"])((?:\\\\\\2|.)*?)\\2)#", $content, $matches); 87 | 88 | $matches = $matches[1] ?? []; 89 | 90 | return array_reduce($matches, function (array $keys, string $match) { 91 | $quote = $match[0]; 92 | $match = trim($match, $quote); 93 | $key = ($quote === '"') ? stripcslashes($match) : str_replace(["\\'", "\\\\"], ["'", "\\"], $match); 94 | 95 | return $key ? 96 | array_merge($keys, [$key => new Translation($key, '')]) : 97 | $keys; 98 | }, []); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/Translator/TranslationService.php: -------------------------------------------------------------------------------- 1 | config = $config; 17 | $this->scanner = $scanner; 18 | $this->repository = $repository; 19 | } 20 | 21 | /** 22 | * @throws InvalidDirectoriesConfiguration 23 | * @throws InvalidExtensionsConfiguration 24 | */ 25 | public function scanAndSaveNewKeys(): void 26 | { 27 | $directories = $this->config->directories(); 28 | $extensions = $this->config->extensions(); 29 | $functions = $this->config->functions(); 30 | 31 | $translations = $this->scanner->scan($extensions, $directories, $functions); 32 | 33 | $this->storeTranslations($translations); 34 | } 35 | 36 | /** 37 | * @param Translation[] $translations 38 | */ 39 | private function storeTranslations(array $translations): void 40 | { 41 | array_map(function (Translation $translation): void { 42 | $this->storeTranslation($translation); 43 | }, $translations); 44 | } 45 | 46 | private function storeTranslation(Translation $translation): void 47 | { 48 | $languages = $this->config->languages(); 49 | 50 | array_map(function (string $language) use ($translation): void { 51 | if ($this->repository->exists($translation, $language)) { 52 | return; 53 | } 54 | 55 | $this->repository->save($translation, $language); 56 | }, $languages); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /tests/Fixtures/App/Functions/Lang/LangTranslation.php: -------------------------------------------------------------------------------- 1 | foo = $foo; 13 | $this->bar = $bar; 14 | } 15 | 16 | public function getFoo(): string 17 | { 18 | return $this->foo; 19 | } 20 | 21 | public function getBar(): string 22 | { 23 | return $this->bar; 24 | } 25 | 26 | public function __toString(): string 27 | { 28 | return __("Lang: :foo, :bar", [':foo' => $this->foo, ':bar' => $this->bar]); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /tests/Fixtures/App/Functions/UnderscoreUnderscore/UnderscoreUnderscoreTranslation.php: -------------------------------------------------------------------------------- 1 | foo = $foo; 13 | $this->bar = $bar; 14 | } 15 | 16 | public function getFoo(): string 17 | { 18 | return $this->foo; 19 | } 20 | 21 | public function getBar(): string 22 | { 23 | return $this->bar; 24 | } 25 | 26 | public function __toString(): string 27 | { 28 | return __("Underscore: :foo, :bar", [':foo' => $this->foo, ':bar' => $this->bar]); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /tests/Fixtures/App/View/Component.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 18 | 19 | -------------------------------------------------------------------------------- /tests/Fixtures/App/View/index.blade.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | Laravel Translator 4 | 5 | 6 |
7 | @lang('Welcome, :name', [':name' => 'Arthur Dent']) 8 |
9 | 10 |
11 | {{ lang('Trip to :planet, check-in opens :time', [':place' => 'Argabuthon', ':time' => '9 days']) }} 12 |
13 | 14 |
15 | {{ __('Check offers to :planet', [':place' => 'Damogran']) }} 16 |
17 | 18 |
19 | {{ __("Translations should also work with double quotes.") }} 20 |
21 | 22 |
23 | {{ __('Shouldn\'t escaped quotes within strings also be correctly added?') }} 24 |
25 | 26 |
27 | {{ __("Same goes for \"double quotes\".") }} 28 |
29 | 30 |
31 | {{ __('String using (parentheses).') }} 32 |
33 | 34 |
35 | {{ __("Double quoted string using \"double quotes\", and C-style escape sequences.\n\t\\") }} 36 |
37 | 38 | 39 | -------------------------------------------------------------------------------- /tests/Fixtures/Glob/SubDir/SubDir2/SubDir2file1.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thiagocordeiro/laravel-translator/89aec3e3aa3217800180547472261c7411408d60/tests/Fixtures/Glob/SubDir/SubDir2/SubDir2file1.txt -------------------------------------------------------------------------------- /tests/Fixtures/Glob/SubDir/SubDir2/SubDir2file2.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thiagocordeiro/laravel-translator/89aec3e3aa3217800180547472261c7411408d60/tests/Fixtures/Glob/SubDir/SubDir2/SubDir2file2.txt -------------------------------------------------------------------------------- /tests/Fixtures/Glob/SubDir/SubDirFile1.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thiagocordeiro/laravel-translator/89aec3e3aa3217800180547472261c7411408d60/tests/Fixtures/Glob/SubDir/SubDirFile1.txt -------------------------------------------------------------------------------- /tests/Fixtures/Glob/SubDir/SubDirFile2.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thiagocordeiro/laravel-translator/89aec3e3aa3217800180547472261c7411408d60/tests/Fixtures/Glob/SubDir/SubDirFile2.txt -------------------------------------------------------------------------------- /tests/Fixtures/Glob/file1.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thiagocordeiro/laravel-translator/89aec3e3aa3217800180547472261c7411408d60/tests/Fixtures/Glob/file1.txt -------------------------------------------------------------------------------- /tests/Fixtures/Glob/file2.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thiagocordeiro/laravel-translator/89aec3e3aa3217800180547472261c7411408d60/tests/Fixtures/Glob/file2.txt -------------------------------------------------------------------------------- /tests/Fixtures/translations/bg.json: -------------------------------------------------------------------------------- 1 | { 2 | "I'll be back": "" 3 | } -------------------------------------------------------------------------------- /tests/Fixtures/translations/de.json: -------------------------------------------------------------------------------- 1 | You shall not pass: Du kannst nicht vorbei -------------------------------------------------------------------------------- /tests/Fixtures/translations/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "I'll be back": "I'll be back" 3 | } -------------------------------------------------------------------------------- /tests/Fixtures/translations/es.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /tests/Fixtures/translations/fr.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /tests/Fixtures/translations/pt.json: -------------------------------------------------------------------------------- 1 | { 2 | "You shall not pass": "Não passarás" 3 | } 4 | -------------------------------------------------------------------------------- /tests/Fixtures/translations/ru.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thiagocordeiro/laravel-translator/89aec3e3aa3217800180547472261c7411408d60/tests/Fixtures/translations/ru.json -------------------------------------------------------------------------------- /tests/Unit/Framework/HelperTest.php: -------------------------------------------------------------------------------- 1 | testDir = realpath(__DIR__ . '/../..') ?? ''; 14 | } 15 | 16 | public function testGlobRecursive(): void 17 | { 18 | $fixturesDir = realpath("{$this->testDir}/Fixtures/Glob"); 19 | 20 | $files = glob_recursive("{$fixturesDir}/*.txt", GLOB_BRACE); 21 | 22 | $this->assertEquals([ 23 | '/Fixtures/Glob/file1.txt', 24 | '/Fixtures/Glob/file2.txt', 25 | '/Fixtures/Glob/SubDir/SubDirFile1.txt', 26 | '/Fixtures/Glob/SubDir/SubDirFile2.txt', 27 | '/Fixtures/Glob/SubDir/SubDir2/SubDir2file1.txt', 28 | '/Fixtures/Glob/SubDir/SubDir2/SubDir2file2.txt', 29 | ], $this->replaceDirectorySeparators($this->removeRelativePath($files))); 30 | } 31 | 32 | /** 33 | * @param string[] $files 34 | * @return string[] 35 | */ 36 | private function removeRelativePath(array $files): array 37 | { 38 | return array_map(function (string $file): string { 39 | return str_replace($this->testDir, '', $file); 40 | }, $files); 41 | } 42 | 43 | /** 44 | * @param string[] $files 45 | * @return string[] 46 | */ 47 | private function replaceDirectorySeparators(array $files): array 48 | { 49 | return array_map(function (string $file): string { 50 | return str_replace('\\', '/', $file); 51 | }, $files); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /tests/Unit/Infra/LaravelJsonTranslationRepositoryTest.php: -------------------------------------------------------------------------------- 1 | translationPath = realpath(__DIR__ . '/../../Fixtures/translations'); 21 | 22 | $configLoader = $this->setupConfigLoader(); 23 | 24 | file_put_contents("{$this->translationPath}/fr.json", '{}'); 25 | 26 | $this->repository = new LaravelJsonTranslationRepository($configLoader); 27 | } 28 | 29 | /** 30 | * @return \PHPUnit\Framework\MockObject\MockObject|ConfigLoader 31 | */ 32 | protected function setupConfigLoader() 33 | { 34 | $configLoader = $this->createMock(ConfigLoader::class); 35 | $configLoader 36 | ->method('output') 37 | ->willReturn($this->translationPath); 38 | 39 | return $configLoader; 40 | } 41 | 42 | public function testWhenFileForGivenLanguageDoesNotExistThenThrowException(): void 43 | { 44 | $translation = new Translation('', ''); 45 | $language = 'nl'; 46 | 47 | $this->expectException(TranslationFileDoesNotExistForLanguage::class); 48 | 49 | $this->repository->exists($translation, $language); 50 | } 51 | 52 | public function testWhenFileForGivenLanguageDoesNotContainAValidJsonContentThenThrowException(): void 53 | { 54 | $translation = new Translation('', ''); 55 | $language = 'de'; 56 | 57 | $this->expectException(InvalidTranslationFile::class); 58 | 59 | $this->repository->exists($translation, $language); 60 | } 61 | 62 | public function testWhenGivenANewKeyThenExistsIsFalse(): void 63 | { 64 | $translation = new Translation('You shall not pass', ''); 65 | $language = 'es'; 66 | 67 | $exists = $this->repository->exists($translation, $language); 68 | 69 | $this->assertFalse($exists); 70 | } 71 | 72 | public function testWhenGivenARegisteredKeyThenExistsIsTrue(): void 73 | { 74 | $translation = new Translation('You shall not pass', ''); 75 | $language = 'pt'; 76 | 77 | $exists = $this->repository->exists($translation, $language); 78 | 79 | $this->assertTrue($exists); 80 | } 81 | 82 | public function testWhenTryingToSaveAKeyWhichAlreadyExistsThenThrowException(): void 83 | { 84 | $translation = new Translation("I'll be back", ''); 85 | $this->repository->save($translation, 'fr'); 86 | 87 | $this->expectException(UnableToSaveTranslationKeyAlreadyExists::class); 88 | 89 | $this->repository->save($translation, 'fr'); 90 | } 91 | 92 | public function testSavingATranslationThenUpdateFile(): void 93 | { 94 | $translation = new Translation("I'll be back", ''); 95 | 96 | $this->repository->save($translation, 'fr'); 97 | 98 | $json = json_decode(file_get_contents("$this->translationPath/fr.json"), true); 99 | $this->assertEquals(['I\'ll be back' => ''], $json); 100 | } 101 | 102 | public function testWhenTryingToLoadAnInvalidJsonFileThenThrowException(): void 103 | { 104 | $translation = new Translation("I'll be back", ''); 105 | 106 | $this->expectException(InvalidTranslationFile::class); 107 | 108 | $this->repository->save($translation, 'ru'); 109 | } 110 | 111 | public function testSettingDefaultLanguageKeyAsValue(): void 112 | { 113 | $configLoader = $this->setupConfigLoader(); 114 | $configLoader->method('languages')->willReturn(['en', 'bg']); 115 | $configLoader->method('defaultLanguage')->willReturn('en'); 116 | $configLoader->method('useKeysAsDefaultValue')->willReturn(true); 117 | 118 | file_put_contents("{$this->translationPath}/en.json", '{}'); 119 | file_put_contents("{$this->translationPath}/bg.json", '{}'); 120 | 121 | $repository = new LaravelJsonTranslationRepository($configLoader); 122 | 123 | $translation = new Translation("I'll be back", ''); 124 | $repository->save($translation, 'en'); 125 | 126 | $translation = new Translation("I'll be back", ''); 127 | $repository->save($translation, 'bg'); 128 | 129 | $json = json_decode(file_get_contents("$this->translationPath/en.json"), true); 130 | $this->assertEquals(['I\'ll be back' => 'I\'ll be back'], $json); 131 | 132 | $json = json_decode(file_get_contents("$this->translationPath/bg.json"), true); 133 | $this->assertEquals(['I\'ll be back' => ''], $json); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /tests/Unit/Translator/TranslationScannerTest.php: -------------------------------------------------------------------------------- 1 | fixturesDir = realpath(__DIR__ . '/../../Fixtures'); 19 | $this->scanner = new TranslationScanner(); 20 | } 21 | 22 | public function testWhenDirectoriesToScanAreNotSetThenThrowException(): void 23 | { 24 | $directories = []; 25 | 26 | $this->expectException(InvalidDirectoriesConfiguration::class); 27 | 28 | $this->scanner->scan(['php'], $directories, ['lang', '__']); 29 | } 30 | 31 | public function testWhenFunctionsToScanAreNotSetThenThrowException(): void 32 | { 33 | $functions = []; 34 | 35 | $this->expectException(InvalidFunctionsConfiguration::class); 36 | 37 | $this->scanner->scan(['php'], ['App'], $functions); 38 | } 39 | 40 | public function testShouldFindTranslationsForUnderscoreFunctions(): void 41 | { 42 | $__dir = $this->fixturesDir . '/App/Functions/UnderscoreUnderscore'; 43 | 44 | $translations = $this->scanner->scan(['php'], [$__dir], ['lang', '__']); 45 | 46 | $this->assertEquals( 47 | [ 48 | 'Underscore: :foo, :bar' => new Translation('Underscore: :foo, :bar', ''), 49 | ], 50 | $translations 51 | ); 52 | } 53 | 54 | public function testShouldFindTranslationsForLangFunctions(): void 55 | { 56 | $langDir = $this->fixturesDir . '/App/Functions/Lang'; 57 | 58 | $translations = $this->scanner->scan(['php'], [$langDir], ['lang', '__']); 59 | 60 | $this->assertEquals( 61 | [ 62 | 'Lang: :foo, :bar' => new Translation('Lang: :foo, :bar', ''), 63 | ], 64 | $translations 65 | ); 66 | } 67 | 68 | public function testShouldFindTranslationsForDifferentFileExtensions(): void 69 | { 70 | $langDir = $this->fixturesDir . '/App/View'; 71 | 72 | $translations = $this->scanner->scan(['vue'], [$langDir], ['lang', '__']); 73 | 74 | $this->assertEquals( 75 | [ 76 | 'This is a vue component' => new Translation('This is a vue component', ''), 77 | 'Vue Component Title' => new Translation('Vue Component Title', ''), 78 | ], 79 | $translations 80 | ); 81 | } 82 | 83 | public function testShouldFindTranslationsForBladeTemplates(): void 84 | { 85 | $viewDir = $this->fixturesDir . '/App/View'; 86 | 87 | $translations = $this->scanner->scan(['php'], [$viewDir], ['lang', '__']); 88 | 89 | $this->assertEquals( 90 | [ 91 | 'Welcome, :name' => new Translation('Welcome, :name', ''), 92 | 'Trip to :planet, check-in opens :time' => new Translation('Trip to :planet, check-in opens :time', ''), 93 | 'Check offers to :planet' => new Translation('Check offers to :planet', ''), 94 | 'Translations should also work with double quotes.' => new Translation( 95 | 'Translations should also work with double quotes.', 96 | '' 97 | ), 98 | 'Shouldn\'t escaped quotes within strings also be correctly added?' => new Translation( 99 | 'Shouldn\'t escaped quotes within strings also be correctly added?', 100 | '' 101 | ), 102 | 'Same goes for "double quotes".' => new Translation('Same goes for "double quotes".', ''), 103 | 'String using (parentheses).' => new Translation('String using (parentheses).', ''), 104 | "Double quoted string using \"double quotes\", and C-style escape sequences.\n\t\\" => new Translation( 105 | "Double quoted string using \"double quotes\", and C-style escape sequences.\n\t\\", 106 | '' 107 | ), 108 | ], 109 | $translations 110 | ); 111 | } 112 | 113 | public function testShouldFindMultipleTranslationForDifferentFunctionsAndFiles(): void 114 | { 115 | $appDir = $this->fixturesDir . '/App'; 116 | 117 | $translations = $this->scanner->scan(['php'], [$appDir], ['lang', '__']); 118 | 119 | $this->assertEquals( 120 | [ 121 | 'Welcome, :name' => new Translation('Welcome, :name', ''), 122 | 'Trip to :planet, check-in opens :time' => new Translation('Trip to :planet, check-in opens :time', ''), 123 | 'Check offers to :planet' => new Translation('Check offers to :planet', ''), 124 | 'Translations should also work with double quotes.' => new Translation( 125 | 'Translations should also work with double quotes.', 126 | '' 127 | ), 128 | 'Shouldn\'t escaped quotes within strings also be correctly added?' => new Translation( 129 | 'Shouldn\'t escaped quotes within strings also be correctly added?', 130 | '' 131 | ), 132 | 'Same goes for "double quotes".' => new Translation('Same goes for "double quotes".', ''), 133 | 'String using (parentheses).' => new Translation('String using (parentheses).', ''), 134 | 'Underscore: :foo, :bar' => new Translation('Underscore: :foo, :bar', ''), 135 | 'Lang: :foo, :bar' => new Translation('Lang: :foo, :bar', ''), 136 | "Double quoted string using \"double quotes\", and C-style escape sequences.\n\t\\" => new Translation( 137 | "Double quoted string using \"double quotes\", and C-style escape sequences.\n\t\\", 138 | '' 139 | ), 140 | ], 141 | $translations 142 | ); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /tests/Unit/Translator/TranslationServiceTest.php: -------------------------------------------------------------------------------- 1 | fixturesDir = realpath(__DIR__ . '/../../Fixtures'); 28 | 29 | $this->configLoader = $this->createMock(ConfigLoader::class); 30 | $this->configLoader 31 | ->method('languages') 32 | ->willReturn(['pt']); 33 | 34 | $scanner = new TranslationScanner(); 35 | $this->repository = $this->createMock(TranslationRepository::class); 36 | 37 | $this->service = new TranslationService($this->configLoader, $scanner, $this->repository); 38 | } 39 | 40 | public function testShouldScanAndSaveKeys(): void 41 | { 42 | $this->configLoader 43 | ->method('extensions') 44 | ->willReturn(['php']); 45 | $this->configLoader 46 | ->method('directories') 47 | ->willReturn([$this->fixturesDir . '/App/View']); 48 | $this->configLoader 49 | ->method('functions') 50 | ->willReturn(['lang', '__']); 51 | 52 | $translations = [ 53 | [new Translation('Welcome, :name', '')], 54 | [new Translation('Trip to :planet, check-in opens :time', '')], 55 | [new Translation('Check offers to :planet', '')], 56 | [new Translation('Translations should also work with double quotes.', '')], 57 | [new Translation('Shouldn\'t escaped quotes within strings also be correctly added?', '')], 58 | [new Translation('Same goes for "double quotes".', '')], 59 | [new Translation('String using (parentheses).', '')], 60 | [new Translation("Double quoted string using \"double quotes\", and C-style escape sequences.\n\t\\", '')], 61 | ]; 62 | 63 | $this->repository 64 | ->expects($this->exactly(8)) 65 | ->method('save') 66 | ->withConsecutive(...$translations); 67 | 68 | $this->service->scanAndSaveNewKeys(); 69 | } 70 | 71 | public function testWhenGivenTranslationAlreadyExistsThenDoNotOverride(): void 72 | { 73 | $this->configLoader 74 | ->method('directories') 75 | ->willReturn([$this->fixturesDir . '/App/Functions/Lang']); 76 | $this->configLoader 77 | ->method('functions') 78 | ->willReturn(['lang', '__']); 79 | $this->configLoader 80 | ->method('extensions') 81 | ->willReturn(['php']); 82 | 83 | $this->repository 84 | ->method('exists') 85 | ->with(new Translation('Lang: :foo, :bar', '')) 86 | ->willReturn(true); 87 | 88 | $this->repository 89 | ->expects($this->never()) 90 | ->method('save'); 91 | 92 | $this->service->scanAndSaveNewKeys(); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /tests/integration.php: -------------------------------------------------------------------------------- 1 | '', 13 | 'Lang: :foo, :bar' => '', 14 | 'Welcome, :name' => '', 15 | 'Trip to :planet, check-in opens :time' => '', 16 | 'Check offers to :planet' => '', 17 | 'Translations should also work with double quotes.' => '', 18 | 'Shouldn\'t escaped quotes within strings also be correctly added?' => '', 19 | 'Same goes for "double quotes".' => '', 20 | 'String using (parentheses).' => '', 21 | "Double quoted string using \"double quotes\", and C-style escape sequences.\n\t\\" => '', 22 | ], 23 | json_decode(file_get_contents("resources/lang/pt-br.json"), true) 24 | ); 25 | 26 | if (!empty($diff)) { 27 | throw new Exception( 28 | sprintf("Keys scanned does not match by the diff:\n%s\n", print_r($diff, true)) 29 | ); 30 | } 31 | 32 | echo 'Integration works :)'; 33 | --------------------------------------------------------------------------------