From de256989b38e2b88d85dd5938dc698b28155c948 Mon Sep 17 00:00:00 2001 From: Alex <48474870+aon4o@users.noreply.github.com> Date: Wed, 11 Dec 2024 11:37:23 +0200 Subject: [PATCH] Workflow fix and tests update (#173) * added .idea folder into .gitignore * added .phpunit.cache folder into .gitignore * phpunit.xml.dist schema updated * code style * PHPUnit replaced by Pest * Tests refactoring * PHP 8.0 compatibility * github test runner fixed * PHP CS Fixer added and reconfigured * PHP CS Fixer configuration rules fix * PHP CS Fixer configuration rules fixed * Update composer.json * Update composer.json and run-tests.yml * Revert "Update composer.json and run-tests.yml" This reverts commit a3d86826cec5840d9d7bf0459ca5c2104dcd9085. * Update composer.json * removed unused migration * removed constants and comments in test files * removed DOCBlocks form Pest.php * removed declare(strict_types=1); * Fix styling * package ServiceProvider updated with spatie/laravel-package-tools * updated README.md * Fix Laravel 8 compatibility * grammar fix README.md * Translation loading fix * Fix styling * Revert "Fix styling" This reverts commit a43c7b5db58a4ab853926d9e60da504706e4cfdb. * Revert "Translation loading fix" This reverts commit 57e03e4d843ae72d5cf07868bc4e96659882062c. * $this->app['config'] -> config() --------- Co-authored-by: alex Co-authored-by: aon4o --- .github/workflows/php-cs-fixer.yml | 4 +- .github/workflows/run-tests.yml | 98 ++++++------- .gitignore | 4 +- .php_cs => .php-cs-fixer.php | 30 +++- README.md | 55 ++++--- composer.json | 20 ++- .../create_language_lines_table.php.stub | 2 +- phpunit.xml | 29 ++++ phpunit.xml.dist | 29 ---- src/Exceptions/InvalidConfiguration.php | 4 +- src/LanguageLine.php | 63 ++++---- src/TranslationLoaderManager.php | 25 ++-- src/TranslationLoaders/Db.php | 2 +- src/TranslationLoaders/TranslationLoader.php | 4 +- src/TranslationServiceProvider.php | 76 ++++++---- tests/DummyManagerTest.php | 58 -------- tests/{ => Feature}/DummyLoader.php | 4 +- tests/Feature/DummyManagerTest.php | 33 +++++ tests/Feature/JsonTransTest.php | 39 +++++ tests/Feature/LanguageLineTest.php | 37 +++++ tests/Feature/TransTest.php | 68 +++++++++ tests/Feature/TranslationLoaders/DbTest.php | 87 ++++++++++++ tests/Feature/TranslationManagerTest.php | 22 +++ .../TranslationManagers/DummyManager.php | 2 +- tests/{fixtures => Fixtures}/lang/en.json | 0 tests/{fixtures => Fixtures}/lang/en/file.php | 0 tests/{fixtures => Fixtures}/lang/nl.json | 0 tests/{fixtures => Fixtures}/lang/nl/file.php | 0 tests/JsonTransTest.php | 57 -------- tests/LanguageLineTest.php | 52 ------- tests/Pest.php | 16 +++ tests/TestCase.php | 52 ++++--- tests/TransTest.php | 90 ------------ tests/TranslationLoaders/DbTest.php | 134 ------------------ tests/TranslationManagerTest.php | 35 ----- 35 files changed, 579 insertions(+), 652 deletions(-) rename .php_cs => .php-cs-fixer.php (62%) create mode 100644 phpunit.xml delete mode 100644 phpunit.xml.dist delete mode 100644 tests/DummyManagerTest.php rename tests/{ => Feature}/DummyLoader.php (76%) create mode 100644 tests/Feature/DummyManagerTest.php create mode 100644 tests/Feature/JsonTransTest.php create mode 100644 tests/Feature/LanguageLineTest.php create mode 100644 tests/Feature/TransTest.php create mode 100644 tests/Feature/TranslationLoaders/DbTest.php create mode 100644 tests/Feature/TranslationManagerTest.php rename tests/{ => Feature}/TranslationManagers/DummyManager.php (66%) rename tests/{fixtures => Fixtures}/lang/en.json (100%) rename tests/{fixtures => Fixtures}/lang/en/file.php (100%) rename tests/{fixtures => Fixtures}/lang/nl.json (100%) rename tests/{fixtures => Fixtures}/lang/nl/file.php (100%) delete mode 100644 tests/JsonTransTest.php delete mode 100644 tests/LanguageLineTest.php create mode 100644 tests/Pest.php delete mode 100644 tests/TransTest.php delete mode 100644 tests/TranslationLoaders/DbTest.php delete mode 100644 tests/TranslationManagerTest.php diff --git a/.github/workflows/php-cs-fixer.yml b/.github/workflows/php-cs-fixer.yml index 84ab01a..2ba6115 100644 --- a/.github/workflows/php-cs-fixer.yml +++ b/.github/workflows/php-cs-fixer.yml @@ -1,6 +1,6 @@ name: Check & fix styling -on: [push] +on: [ push ] jobs: style: @@ -13,7 +13,7 @@ jobs: - name: Fix style uses: docker://oskarstark/php-cs-fixer-ga with: - args: --config=.php_cs --allow-risky=yes + args: --config=.php-cs-fixer.php --allow-risky=yes - name: Extract branch name shell: bash diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index efc2d64..64993d0 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -1,54 +1,54 @@ name: run-tests on: - - push - - pull_request + - push + - pull_request jobs: - test: - runs-on: ${{ matrix.os }} - - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest] - php: [8.2, 8.1, 8.0] - laravel: ['8.*', '9.*', '10.*', '11.*'] - dependency-version: [prefer-stable] - include: - - laravel: 10.* - testbench: 8.* - - laravel: 9.* - testbench: 7.* - - laravel: 8.* - testbench: 6.* - - laravel: 11.* - testbench: 9.* - exclude: - - laravel: 10.* - php: 8.0 - - laravel: 11.* - php: 8.1 - - laravel: 11.* - php: 8.0 - - name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} - ${{ matrix.os }} - - steps: - - name: Checkout code - uses: actions/checkout@v3 - - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: ${{ matrix.php }} - extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick - coverage: none - - - name: Install dependencies - run: | - composer require "laravel/framework:${{ matrix.laravel }}" "nesbot/carbon:^2.63" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update - composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction - - - name: Execute tests - run: vendor/bin/phpunit + test: + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + matrix: + os: [ ubuntu-latest ] + php: [ 8.2, 8.1, 8.0 ] + laravel: [ '8.*', '9.*', '10.*', '11.*' ] + dependency-version: [ prefer-stable ] + include: + - laravel: 10.* + testbench: 8.* + - laravel: 9.* + testbench: 7.* + - laravel: 8.* + testbench: 6.* + - laravel: 11.* + testbench: 9.* + exclude: + - laravel: 10.* + php: 8.0 + - laravel: 11.* + php: 8.1 + - laravel: 11.* + php: 8.0 + + name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} - ${{ matrix.os }} + + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick + coverage: none + + - name: Install dependencies + run: | + composer require "laravel/framework:${{ matrix.laravel }}" "nesbot/carbon:^2.63" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update + composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction + + - name: Execute tests + run: composer test diff --git a/.gitignore b/.gitignore index d130800..3e6a354 100644 --- a/.gitignore +++ b/.gitignore @@ -2,5 +2,7 @@ build composer.lock docs vendor -.php_cs.cache +.php-cs-fixer.cache +.phpunit.cache .phpunit.result.cache +.idea diff --git a/.php_cs b/.php-cs-fixer.php similarity index 62% rename from .php_cs rename to .php-cs-fixer.php index 9ab6e3d..0615c5f 100644 --- a/.php_cs +++ b/.php-cs-fixer.php @@ -13,30 +13,46 @@ ->ignoreDotFiles(true) ->ignoreVCS(true); -return PhpCsFixer\Config::create() +return (new PhpCsFixer\Config()) ->setRules([ '@PSR2' => true, - 'array_syntax' => ['syntax' => 'short'], - 'ordered_imports' => ['sortAlgorithm' => 'alpha'], + 'array_syntax' => [ + 'syntax' => 'short', + ], + 'ordered_imports' => [ + 'sort_algorithm' => 'alpha', + ], 'no_unused_imports' => true, 'not_operator_with_successor_space' => true, - 'trailing_comma_in_multiline_array' => true, + 'trailing_comma_in_multiline' => [ + 'elements' => [ + 'arrays', + ], + ], 'phpdoc_scalar' => true, 'unary_operator_spaces' => true, 'binary_operator_spaces' => true, 'blank_line_before_statement' => [ - 'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'], + 'statements' => [ + 'break', + 'continue', + 'declare', + 'return', + 'throw', + 'try', + ], ], 'phpdoc_single_line_var_spacing' => true, 'phpdoc_var_without_name' => true, 'class_attributes_separation' => [ 'elements' => [ - 'method', 'property', + 'method' => 'one', + 'property' => 'one', ], ], 'method_argument_space' => [ 'on_multiline' => 'ensure_fully_multiline', 'keep_multiple_spaces_after_comma' => true, - ] + ], ]) ->setFinder($finder); diff --git a/README.md b/README.md index 040d327..dddf412 100644 --- a/README.md +++ b/README.md @@ -5,25 +5,35 @@ ![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/spatie/laravel-translation-loader/run-tests.yml?branch=main&label=Tests&style=flat-square) [![Total Downloads](https://img.shields.io/packagist/dt/spatie/laravel-translation-loader.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-translation-loader) -In a vanilla Laravel or Lumen installation you can use [language files](https://laravel.com/docs/localization) to localize your app. This package will enable the translations to be stored in the database. You can still use all the features of [the `__` helper function](https://laravel.com/docs/localization#retrieving-translation-strings) you know and love. +In a vanilla Laravel or Lumen installation, you can use [language files](https://laravel.com/docs/localization) to +localize your app. This package will enable the translations to be stored in the database. You can still use all the +features of [the `__` helper function](https://laravel.com/docs/localization#retrieving-translation-strings) you know +and love. ```php __('messages.welcome', ['name' => 'dayle']); ``` -You can even mix using language files and the database. If a translation is present in both a file and the database, the database version will be returned. +You can even mix using language files and the database. If a translation is present in both a file and the database, the +database version will be returned. -Want to use a different source for your translations? No problem! The package is [easily extendable](https://github.com/spatie/laravel-translation-loader#creating-your-own-translation-providers). +Want to use a different source for your translations? No problem! The package +is [easily extendable](https://github.com/spatie/laravel-translation-loader#creating-your-own-translation-providers). -Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects [on our website](https://spatie.be/opensource). +Spatie is a web design agency based in Antwerp, Belgium. +You'll find an overview of all our open source +projects [on our website](https://spatie.be/opensource). ## Support us [](https://spatie.be/github-ad-click/laravel-translation-loader) -We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us). +We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can +support us by [buying one of our paid products](https://spatie.be/open-source/support-us). -We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards). +We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. +You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards +on [our virtual postcard wall](https://spatie.be/open-source/postcards). ## Installation @@ -48,14 +58,14 @@ Spatie\TranslationLoader\TranslationServiceProvider::class, You must publish and run the migrations to create the `language_lines` table: ```bash -php artisan vendor:publish --provider="Spatie\TranslationLoader\TranslationServiceProvider" --tag="migrations" +php artisan vendor:publish --provider="Spatie\TranslationLoader\TranslationServiceProvider" --tag="translation-loader-migrations" php artisan migrate ``` -Optionally you could publish the config file using this command. +Optionally, you could publish the config file using this command. ```bash -php artisan vendor:publish --provider="Spatie\TranslationLoader\TranslationServiceProvider" --tag="config" +php artisan vendor:publish --provider="Spatie\TranslationLoader\TranslationServiceProvider" --tag="translation-loader-config" ``` This is the contents of the published config file: @@ -78,18 +88,19 @@ return [ 'model' => Spatie\TranslationLoader\LanguageLine::class, /* - * This is the translation manager which overrides the default Laravel `translation.loader` + * This is the translation manager that overrides the default Laravel `translation.loader` */ 'translation_manager' => Spatie\TranslationLoader\TranslationLoaderManager::class, ]; ``` -> **Note:** publishing assets doesn't work out of the box in Lumen. Instead you have to copy the files from the repo. +> **Note:** publishing assets doesn't work out of the box in Lumen. Instead, you have to copy the files from the repo. ## Usage -You can create a translation in the database by creating and saving an instance of the `Spatie\TranslationLoader\LanguageLine`-model: +You can create a translation in the database by creating and saving an instance of +the `Spatie\TranslationLoader\LanguageLine`-model: ```php use Spatie\TranslationLoader\LanguageLine; @@ -101,7 +112,8 @@ LanguageLine::create([ ]); ``` -You can fetch the translation with [Laravel's default `__` function](https://laravel.com/docs/localization#retrieving-translation-strings): +You can fetch the translation +with [Laravel's default `__` function](https://laravel.com/docs/localization#retrieving-translation-strings): ```php __('validation.required'); // returns 'This is a required field' @@ -111,15 +123,19 @@ app()->setLocale('nl'); __('validation.required'); // returns 'Dit is een verplicht veld' ``` -You can still keep using the default language files as well. If a requested translation is present in both the database and the language files, the database version will be returned. +You can still keep using the default language files as well. If a requested translation is present in both the database +and the language files, the database version will be returned. -If you need to store/override json translation lines, just create a normal LanguageLine with `group => '*'`. +If you need to store/override JSON translation lines, just create a normal LanguageLine with `group => '*'`. ## Creating your own translation providers -This package ships with a translation provider than can fetch translations from the database. If you're storing your translations in a yaml-file, a csv-file, or ... you can easily extend this package by creating your own translation provider. +This package ships with a translation provider that can fetch translations from the database. +If you're storing your translations in a yaml-file, a csv-file, etc., +you can easily extend this package by creating your own translation provider. -A translation provider can be any class that implements the `Spatie\TranslationLoader\TranslationLoaders\TranslationLoader`-interface. It contains only one method: +A translation provider can be any class that implements +the `Spatie\TranslationLoader\TranslationLoaders\TranslationLoader`-interface. It contains only one method: ```php namespace Spatie\TranslationLoader\TranslationLoaders; @@ -137,7 +153,7 @@ Translation providers can be registered in the `translation_loaders` key of the ## Changelog -Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. +Please see [CHANGELOG](CHANGELOG.md) for more information about what has changed recently. ## Testing @@ -151,7 +167,8 @@ Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTI ## Security -If you've found a bug regarding security please mail [security@spatie.be](mailto:security@spatie.be) instead of using the issue tracker. +If you've found a bug regarding security, please mail [security@spatie.be](mailto:security@spatie.be) instead of using +the issue tracker. ## Credits diff --git a/composer.json b/composer.json index 431d978..454b13a 100644 --- a/composer.json +++ b/composer.json @@ -22,12 +22,14 @@ } ], "require": { - "php": "^7.2|^8.0", - "illuminate/translation": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0" + "php": "^8.0", + "illuminate/translation": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "spatie/laravel-package-tools": "^1.12" }, "require-dev": { - "phpunit/phpunit": "^8.0|^9.0|^10.5", - "orchestra/testbench": "^4.0|^5.0|^6.0|^7.0|^8.0|^9.0" + "friendsofphp/php-cs-fixer": "^3.59", + "orchestra/testbench": "^6.0|^7.0|^8.0|^9.0", + "pestphp/pest": "^1.23|^2.0" }, "autoload": { "psr-4": { @@ -36,14 +38,18 @@ }, "autoload-dev": { "psr-4": { - "Spatie\\TranslationLoader\\Test\\": "tests" + "Tests\\": "tests" } }, "scripts": { - "test": "vendor/bin/phpunit" + "test": "vendor/bin/pest", + "lint": "vendor/bin/php-cs-fixer fix" }, "config": { - "sort-packages": true + "sort-packages": true, + "allow-plugins": { + "pestphp/pest-plugin": true + } }, "extra": { "laravel": { diff --git a/database/migrations/create_language_lines_table.php.stub b/database/migrations/create_language_lines_table.php.stub index 2700c96..d24d12a 100644 --- a/database/migrations/create_language_lines_table.php.stub +++ b/database/migrations/create_language_lines_table.php.stub @@ -14,7 +14,7 @@ return new class extends Migration public function up(): void { Schema::create('language_lines', function (Blueprint $table) { - $table->bigIncrements('id'); + $table->id(); $table->string('group')->index(); $table->string('key'); $table->json('text'); diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..e5f973e --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + ./tests + + + + + ./app + ./src + + + diff --git a/phpunit.xml.dist b/phpunit.xml.dist deleted file mode 100644 index de04f36..0000000 --- a/phpunit.xml.dist +++ /dev/null @@ -1,29 +0,0 @@ - - - - - tests - - - - - src/ - - - - - - - - - - diff --git a/src/Exceptions/InvalidConfiguration.php b/src/Exceptions/InvalidConfiguration.php index a4be462..132cbdd 100644 --- a/src/Exceptions/InvalidConfiguration.php +++ b/src/Exceptions/InvalidConfiguration.php @@ -9,7 +9,7 @@ class InvalidConfiguration extends Exception { public static function invalidModel(string $className): self { - return new static("You have configured an invalid class `{$className}`.". - 'A valid class extends '.LanguageLine::class.'.'); + return new static("You have configured an invalid class `{$className}`." . + 'A valid class extends ' . LanguageLine::class . '.'); } } diff --git a/src/LanguageLine.php b/src/LanguageLine.php index 5601563..645222b 100644 --- a/src/LanguageLine.php +++ b/src/LanguageLine.php @@ -9,15 +9,21 @@ class LanguageLine extends Model { /** @var array */ - public $translatable = ['text']; + public array $translatable = [ + 'text', + ]; - /** @var array */ - public $guarded = ['id']; + /** @var array */ + public $guarded = [ + 'id', + ]; /** @var array */ - protected $casts = ['text' => 'array']; + protected $casts = [ + 'text' => 'array', + ]; - public static function boot() + public static function boot(): void { parent::boot(); @@ -33,21 +39,21 @@ public static function getTranslationsForGroup(string $locale, string $group): a { return Cache::rememberForever(static::getCacheKey($group, $locale), function () use ($group, $locale) { return static::query() - ->where('group', $group) - ->get() - ->reduce(function ($lines, self $languageLine) use ($group, $locale) { - $translation = $languageLine->getTranslation($locale); - - if ($translation !== null && $group === '*') { - // Make a flat array when returning json translations - $lines[$languageLine->key] = $translation; - } elseif ($translation !== null && $group !== '*') { - // Make a nested array when returning normal translations - Arr::set($lines, $languageLine->key, $translation); - } - - return $lines; - }) ?? []; + ->where('group', $group) + ->get() + ->reduce(function ($lines, self $languageLine) use ($locale, $group) { + $translation = $languageLine->getTranslation($locale); + + if ($translation !== null && $group === '*') { + // Make a flat array when returning json translations + $lines[$languageLine->key] = $translation; + } elseif ($translation !== null && $group !== '*') { + // Make a nested array when returning normal translations + Arr::set($lines, $languageLine->key, $translation); + } + + return $lines; + }) ?? []; }); } @@ -56,12 +62,7 @@ public static function getCacheKey(string $group, string $locale): string return "spatie.translation-loader.{$group}.{$locale}"; } - /** - * @param string $locale - * - * @return string - */ - public function getTranslation(string $locale): ?string + public function getTranslation(string $locale): string|null { if (! isset($this->text[$locale])) { $fallback = config('app.fallback_locale'); @@ -72,20 +73,14 @@ public function getTranslation(string $locale): ?string return $this->text[$locale]; } - /** - * @param string $locale - * @param string $value - * - * @return $this - */ - public function setTranslation(string $locale, string $value) + public function setTranslation(string $locale, string $value): static { $this->text = array_merge($this->text ?? [], [$locale => $value]); return $this; } - public function flushGroupCache() + public function flushGroupCache(): void { foreach ($this->getTranslatedLocales() as $locale) { Cache::forget(static::getCacheKey($this->group, $locale)); diff --git a/src/TranslationLoaderManager.php b/src/TranslationLoaderManager.php index 6715977..29f2533 100644 --- a/src/TranslationLoaderManager.php +++ b/src/TranslationLoaderManager.php @@ -3,8 +3,8 @@ namespace Spatie\TranslationLoader; use Illuminate\Database\QueryException; -use Illuminate\Translation\FileLoader; use Illuminate\Support\Facades\Schema; +use Illuminate\Translation\FileLoader; use Spatie\TranslationLoader\TranslationLoaders\TranslationLoader; class TranslationLoaderManager extends FileLoader @@ -12,9 +12,9 @@ class TranslationLoaderManager extends FileLoader /** * Load the messages for the given locale. * - * @param string $locale - * @param string $group - * @param string $namespace + * @param string $locale + * @param string $group + * @param string $namespace * * @return array */ @@ -23,30 +23,29 @@ public function load($locale, $group, $namespace = null): array try { $fileTranslations = parent::load($locale, $group, $namespace); - if (!is_null($namespace) && $namespace !== '*') { + if (! is_null($namespace) && $namespace !== '*') { return $fileTranslations; } $loaderTranslations = $this->getTranslationsForTranslationLoaders($locale, $group, $namespace); return array_replace_recursive($fileTranslations, $loaderTranslations); - } catch (QueryException $e) { + } catch (QueryException $exception) { $modelClass = config('translation-loader.model'); - $model = new $modelClass; - if (is_a($model, LanguageLine::class)) { - if (! Schema::hasTable($model->getTable())) { - return parent::load($locale, $group, $namespace); - } + $model = new $modelClass(); + + if (is_a($model, LanguageLine::class) && ! Schema::hasTable($model->getTable())) { + return parent::load($locale, $group, $namespace); } - throw $e; + throw $exception; } } protected function getTranslationsForTranslationLoaders( string $locale, string $group, - ?string $namespace = null + string|null $namespace = null ): array { return collect(config('translation-loader.translation_loaders')) ->map(function (string $className) { diff --git a/src/TranslationLoaders/Db.php b/src/TranslationLoaders/Db.php index 79d9723..cf3ec87 100644 --- a/src/TranslationLoaders/Db.php +++ b/src/TranslationLoaders/Db.php @@ -18,7 +18,7 @@ protected function getConfiguredModelClass(): string { $modelClass = config('translation-loader.model'); - if (! is_a(new $modelClass, LanguageLine::class)) { + if (! is_a(new $modelClass(), LanguageLine::class)) { throw InvalidConfiguration::invalidModel($modelClass); } diff --git a/src/TranslationLoaders/TranslationLoader.php b/src/TranslationLoaders/TranslationLoader.php index 03b6f3f..c10f51c 100644 --- a/src/TranslationLoaders/TranslationLoader.php +++ b/src/TranslationLoaders/TranslationLoader.php @@ -7,8 +7,8 @@ interface TranslationLoader /** * Returns all translations for the given locale and group. * - * @param string $locale - * @param string $group + * @param string $locale + * @param string $group * * @return array */ diff --git a/src/TranslationServiceProvider.php b/src/TranslationServiceProvider.php index b952d20..5a8ee2e 100644 --- a/src/TranslationServiceProvider.php +++ b/src/TranslationServiceProvider.php @@ -2,40 +2,27 @@ namespace Spatie\TranslationLoader; -use Illuminate\Support\Str; -use Illuminate\Translation\FileLoader; -use Illuminate\Translation\TranslationServiceProvider as IlluminateTranslationServiceProvider; +use Illuminate\Contracts\Support\DeferrableProvider; +use Illuminate\Translation\Translator; +use Spatie\LaravelPackageTools\Package; +use Spatie\LaravelPackageTools\PackageServiceProvider; -class TranslationServiceProvider extends IlluminateTranslationServiceProvider +class TranslationServiceProvider extends PackageServiceProvider implements DeferrableProvider { /** - * Register the application services. + * @param Package $package + * + * @return void */ - public function register() + public function configurePackage(Package $package): void { - parent::register(); + $package + ->name('laravel-translation-loader') + ->hasConfigFile() + ->hasMigrations('create_language_lines_table'); - $this->mergeConfigFrom(__DIR__.'/../config/translation-loader.php', 'translation-loader'); - } - - /** - * Bootstrap the application services. - */ - public function boot() - { - if ($this->app->runningInConsole() && ! Str::contains($this->app->version(), 'Lumen')) { - $this->publishes([ - __DIR__.'/../config/translation-loader.php' => config_path('translation-loader.php'), - ], 'config'); - - if (! class_exists('CreateLanguageLinesTable')) { - $timestamp = date('Y_m_d_His', time()); - - $this->publishes([ - __DIR__.'/../database/migrations/create_language_lines_table.php.stub' => database_path('migrations/'.$timestamp.'_create_language_lines_table.php'), - ], 'migrations'); - } - } + $this->registerLoader(); + $this->registerTranslator(); } /** @@ -43,7 +30,7 @@ public function boot() * `TranslationLoaderManager` instead of a simple `FileLoader` as the * applications `translation.loader` instance. */ - protected function registerLoader() + protected function registerLoader(): void { $this->app->singleton('translation.loader', function ($app) { $class = config('translation-loader.translation_manager'); @@ -51,4 +38,35 @@ protected function registerLoader() return new $class($app['files'], $app['path.lang']); }); } + + /** + * @return void + */ + protected function registerTranslator(): void + { + $this->app->singleton('translator', function ($app) { + $loader = $app['translation.loader']; + + // When registering the translator component, we'll need to set the default + // locale as well as the fallback locale. So, we'll grab the application + // configuration so we can easily get both of these values from there. + $locale = $app->getLocale(); + + $trans = new Translator($loader, $locale); + + $trans->setFallback($app->getFallbackLocale()); + + return $trans; + }); + } + + /** + * Get the services provided by the provider. + * + * @return array + */ + public function provides(): array + { + return ['translator', 'translation.loader']; + } } diff --git a/tests/DummyManagerTest.php b/tests/DummyManagerTest.php deleted file mode 100644 index b2d7943..0000000 --- a/tests/DummyManagerTest.php +++ /dev/null @@ -1,58 +0,0 @@ -set('translation-loader.translation_manager', DummyManager::class); - } - - /** @test */ - public function it_allow_to_change_translation_manager() - { - $this->assertInstanceOf(DummyManager::class, $this->app['translation.loader']); - } - - /** @test */ - public function it_can_translate_using_dummy_manager_using_file() - { - $this->assertEquals('en value', trans('file.key')); - } - - /** @test */ - public function it_can_translate_using_dummy_manager_using_db() - { - $this->createLanguageLine('file', 'key', ['en' => 'en value from db']); - $this->assertEquals('en value from db', trans('file.key')); - } - - /** @test */ - public function it_can_translate_using_dummy_manager_using_file_with_incomplete_db() - { - $this->createLanguageLine('file', 'key', ['nl' => 'nl value from db']); - $this->assertEquals('en value', trans('file.key')); - } - - /** @test */ - public function it_can_translate_using_dummy_manager_using_empty_translation_in_db() - { - $this->createLanguageLine('file', 'key', ['en' => '']); - - // Some versions of Laravel changed the behaviour of what an empty "" translation value returns: the key name or an empty value - // @see https://github.com/laravel/framework/issues/34218 - $this->assertTrue(in_array(trans('file.key'), ['', 'file.key'])); - } -} diff --git a/tests/DummyLoader.php b/tests/Feature/DummyLoader.php similarity index 76% rename from tests/DummyLoader.php rename to tests/Feature/DummyLoader.php index 27f71cd..db67338 100644 --- a/tests/DummyLoader.php +++ b/tests/Feature/DummyLoader.php @@ -1,12 +1,12 @@ 'this is dummy']; } diff --git a/tests/Feature/DummyManagerTest.php b/tests/Feature/DummyManagerTest.php new file mode 100644 index 0000000..6d98cd6 --- /dev/null +++ b/tests/Feature/DummyManagerTest.php @@ -0,0 +1,33 @@ +set('translation-loader.translation_manager', DummyManager::class); +}); + +it('allow to change translation manager', function () { + expect($this->app['translation.loader'])->toBeInstanceOf(DummyManager::class); +}); + +it('can translate using dummy manager using file', function () { + expect(trans('file.key'))->toEqual('en value'); +}); + +it('can translate using dummy manager using db', function () { + createLanguageLine('file', 'key', ['en' => 'en value from db']); + expect(trans('file.key'))->toEqual('en value from db'); +}); + +it('can translate using dummy manager using file with incomplete db', function () { + createLanguageLine('file', 'key', ['nl' => 'nl value from db']); + expect(trans('file.key'))->toEqual('en value'); +}); + +it('can translate using dummy manager using empty translation in db', function () { + createLanguageLine('file', 'key', ['en' => '']); + + // Some versions of Laravel changed the behaviour of what an empty "" translation value returns: the key name or an empty value + // @see https://github.com/laravel/framework/issues/34218 + expect(in_array(trans('file.key'), ['', 'file.key']))->toBeTrue(); +}); diff --git a/tests/Feature/JsonTransTest.php b/tests/Feature/JsonTransTest.php new file mode 100644 index 0000000..9d3fae3 --- /dev/null +++ b/tests/Feature/JsonTransTest.php @@ -0,0 +1,39 @@ +term1 = 'file not found'; + $this->term1En = 'File not found'; + $this->term1Nl = 'Bestand niet gevonden'; + $this->term1EnDb = 'File not found from db'; + $this->term2 = 'file not found. it might be in trash.'; + $this->term2En = 'File not found. It might be in trash.'; + $this->term2Nl = 'Bestand niet gevonden. Het bestand is waarschijnlijk verwijderd.'; + $this->term2EnDb = 'File not found from db. It might be in trash.'; +}); + +it('can get translations for language files', function () { + expect(__($this->term1))->toEqual($this->term1En) + ->and(__($this->term2))->toEqual($this->term2En); +}); + +it('can get translations for language files for the current locale', function () { + app()->setLocale('nl'); + + expect(__($this->term1))->toEqual($this->term1Nl) + ->and(__($this->term2))->toEqual($this->term2Nl); +}); + +test('by default it will prefer a db translation over a file translation', function () { + createLanguageLine('*', $this->term1, ['en' => $this->term1EnDb]); + createLanguageLine('*', $this->term2, ['en' => $this->term2EnDb]); + + expect(__($this->term1))->toEqual($this->term1EnDb) + ->and(__($this->term2))->toEqual($this->term2EnDb); +}); + +it('will default to fallback if locale is missing', function () { + app()->setLocale('de'); + createLanguageLine('*', $this->term1, ['en' => $this->term1EnDb]); + + expect(__($this->term1))->toEqual($this->term1EnDb); +}); diff --git a/tests/Feature/LanguageLineTest.php b/tests/Feature/LanguageLineTest.php new file mode 100644 index 0000000..8d68868 --- /dev/null +++ b/tests/Feature/LanguageLineTest.php @@ -0,0 +1,37 @@ + 'english', 'nl' => 'nederlands']); + + expect($languageLine->getTranslation('en'))->toEqual('english') + ->and($languageLine->getTranslation('nl'))->toEqual('nederlands'); +}); + +it('can set a translation', function () { + $languageLine = createLanguageLine('group', 'new', ['en' => 'english']); + + $languageLine->setTranslation('nl', 'nederlands'); + + expect($languageLine->getTranslation('en'))->toEqual('english') + ->and($languageLine->getTranslation('nl'))->toEqual('nederlands'); +}); + +it('can set a translation on a fresh model', function () { + $languageLine = new LanguageLine(); + + $languageLine->setTranslation('nl', 'nederlands'); + + expect($languageLine->getTranslation('nl'))->toEqual('nederlands'); +}); + +it('doesnt show error when getting nonexistent translation', function () { + $languageLine = createLanguageLine('group', 'new', ['nl' => 'nederlands']); + expect($languageLine->getTranslation('en'))->toBeNull(); +}); + +test('get fallback locale if doesnt exists', function () { + $languageLine = createLanguageLine('group', 'new', ['en' => 'English']); + expect($languageLine->getTranslation('es'))->toEqual('English'); +}); diff --git a/tests/Feature/TransTest.php b/tests/Feature/TransTest.php new file mode 100644 index 0000000..79159b2 --- /dev/null +++ b/tests/Feature/TransTest.php @@ -0,0 +1,68 @@ +nested = [ + 'bool' => [ + 1 => 'Yes', + 0 => 'No', + ], + ]; +}); + +it('can get translations for language files', function () { + expect(trans('file.key'))->toEqual('en value') + ->and(trans('file.404.title'))->toEqual('page not found') + ->and(trans('file.404.message'))->toEqual('This page does not exists'); +}); + +it('can get translations for language files for the current locale', function () { + app()->setLocale('nl'); + + expect(trans('file.key'))->toEqual('nl value') + ->and(trans('file.404.title'))->toEqual('pagina niet gevonden') + ->and(trans('file.404.message'))->toEqual('Deze pagina bestaat niet'); +}); + +test('by default it will prefer a db translation over a file translation', function () { + createLanguageLine('file', 'key', ['en' => 'en value from db']); + createLanguageLine('file', '404.title', ['en' => 'page not found from db']); + + expect(trans('file.key'))->toEqual('en value from db') + ->and(trans('file.404.title'))->toEqual('page not found from db') + ->and(trans('file.404.message'))->toEqual('This page does not exists'); +}); + +it('will return array if the given translation is nested', function () { + foreach (Arr::dot($this->nested) as $key => $text) { + createLanguageLine('nested', $key, ['en' => $text]); + } + + expect(trans('nested.bool'))->toEqualCanonicalizing($this->nested['bool'], '$canonicalize = true', $delta = 0.0, $maxDepth = 10, $canonicalize = true); +}); + +it('will return the translation string if max nested level is reached', function () { + foreach (Arr::dot($this->nested) as $key => $text) { + createLanguageLine('nested', $key, ['en' => $text]); + } + + expect(trans('nested.bool.1'))->toEqual($this->nested['bool'][1]); +}); + +it('will return the dotted translation key if no translation found', function () { + $notFoundKey = 'nested.bool.3'; + + foreach (Arr::dot($this->nested) as $key => $text) { + createLanguageLine('nested', $key, ['en' => $text]); + } + + expect(trans($notFoundKey))->toEqual($notFoundKey); +}); + +it('will default to fallback if locale is missing', function () { + app()->setLocale('de'); + createLanguageLine('missing_locale', 'key', ['en' => 'en value from db']); + + expect(trans('missing_locale.key'))->toEqual('en value from db'); +}); diff --git a/tests/Feature/TranslationLoaders/DbTest.php b/tests/Feature/TranslationLoaders/DbTest.php new file mode 100644 index 0000000..576afe6 --- /dev/null +++ b/tests/Feature/TranslationLoaders/DbTest.php @@ -0,0 +1,87 @@ +toEqual('english'); +}); + +it('can get a correct translation after the locale has been changed', function () { + app()->setLocale('nl'); + + expect(trans('group.key'))->toEqual('nederlands'); +}); + +it('can return the group and the key when getting a non existing translation', function () { + app()->setLocale('nl'); + + expect(trans('group.unknown'))->toEqual('group.unknown'); +}); + +it('supports placeholders', function () { + createLanguageLine('group', 'placeholder', ['en' => 'text with :placeholder']); + + expect(trans('group.placeholder', ['placeholder' => 'filled in placeholder']))->toEqual('text with filled in placeholder'); +}); + +it('will cache all translations', function () { + trans('group.key'); + + $queryCount = count(DB::getQueryLog()); + flushIlluminateTranslatorCache(); + + trans('group.key'); + + expect(count(DB::getQueryLog()))->toEqual($queryCount); +}); + +it('flushes the cache when a translation has been created', function () { + expect(trans('group.new'))->toEqual('group.new'); + + createLanguageLine('group', 'new', ['en' => 'created']); + flushIlluminateTranslatorCache(); + + expect(trans('group.new'))->toEqual('created'); +}); + +it('flushes the cache when a translation has been updated', function () { + trans('group.key'); + + $this->languageLine->setTranslation('en', 'updated'); + $this->languageLine->save(); + + flushIlluminateTranslatorCache(); + + expect(trans('group.key'))->toEqual('updated'); +}); + +it('flushes the cache when a translation has been deleted', function () { + expect(trans('group.key'))->toEqual('english'); + + $this->languageLine->delete(); + flushIlluminateTranslatorCache(); + + expect(trans('group.key'))->toEqual('group.key'); +}); + +it('can work with a custom model', function () { + $alternativeModel = new class extends LanguageLine { + public static function getTranslationsForGroup(string $locale, string $group): array + { + return ['key' => 'alternative class']; + } + }; + config()->set('translation-loader.model', get_class($alternativeModel)); + + expect(trans('group.key'))->toEqual('alternative class'); +}); +it('will throw an exception if the configured model does not extend the default one', function () { + $invalidModel = new class {}; + + config()->set('translation-loader.model', get_class($invalidModel)); + + $this->expectException(InvalidConfiguration::class); + + expect(trans('group.key'))->toEqual('alternative class'); +}); diff --git a/tests/Feature/TranslationManagerTest.php b/tests/Feature/TranslationManagerTest.php new file mode 100644 index 0000000..2414d43 --- /dev/null +++ b/tests/Feature/TranslationManagerTest.php @@ -0,0 +1,22 @@ +set('translation-loader.translation_loaders', []); + + expect(trans('group.key'))->toEqual('group.key'); +}); + +it('will merge translation from all providers', function () { + config()->set('translation-loader.translation_loaders', [ + Db::class, + DummyLoader::class, + ]); + + createLanguageLine('db', 'key', ['en' => 'db']); + + expect(trans('db.key'))->toEqual('db') + ->and(trans('dummy.dummy'))->toEqual('this is dummy'); +}); diff --git a/tests/TranslationManagers/DummyManager.php b/tests/Feature/TranslationManagers/DummyManager.php similarity index 66% rename from tests/TranslationManagers/DummyManager.php rename to tests/Feature/TranslationManagers/DummyManager.php index 782490d..1409330 100644 --- a/tests/TranslationManagers/DummyManager.php +++ b/tests/Feature/TranslationManagers/DummyManager.php @@ -1,6 +1,6 @@ assertEquals(self::TERM1_EN, __(self::TERM1)); - $this->assertEquals(self::TERM2_EN, __(self::TERM2)); - } - - /** @test */ - public function it_can_get_translations_for_language_files_for_the_current_locale() - { - app()->setLocale('nl'); - - $this->assertEquals(self::TERM1_NL, __(self::TERM1)); - $this->assertEquals(self::TERM2_NL, __(self::TERM2)); - } - - /** @test */ - public function by_default_it_will_prefer_a_db_translation_over_a_file_translation() - { - $this->createLanguageLine('*', self::TERM1, ['en' => self::TERM1_EN_DB]); - $this->createLanguageLine('*', self::TERM2, ['en' => self::TERM2_EN_DB]); - - $this->assertEquals(self::TERM1_EN_DB, __(self::TERM1)); - $this->assertEquals(self::TERM2_EN_DB, __(self::TERM2)); - } - - /** @test */ - public function it_will_default_to_fallback_if_locale_is_missing() - { - app()->setLocale('de'); - $this->createLanguageLine('*', self::TERM1, ['en' => self::TERM1_EN_DB]); - - $this->assertEquals(self::TERM1_EN_DB, __(self::TERM1)); - } -} diff --git a/tests/LanguageLineTest.php b/tests/LanguageLineTest.php deleted file mode 100644 index 9ab210e..0000000 --- a/tests/LanguageLineTest.php +++ /dev/null @@ -1,52 +0,0 @@ -createLanguageLine('group', 'new', ['en' => 'english', 'nl' => 'nederlands']); - - $this->assertEquals('english', $languageLine->getTranslation('en')); - $this->assertEquals('nederlands', $languageLine->getTranslation('nl')); - } - - /** @test */ - public function it_can_set_a_translation() - { - $languageLine = $this->createLanguageLine('group', 'new', ['en' => 'english']); - - $languageLine->setTranslation('nl', 'nederlands'); - - $this->assertEquals('english', $languageLine->getTranslation('en')); - $this->assertEquals('nederlands', $languageLine->getTranslation('nl')); - } - - /** @test */ - public function it_can_set_a_translation_on_a_fresh_model() - { - $languageLine = new LanguageLine(); - - $languageLine->setTranslation('nl', 'nederlands'); - - $this->assertEquals('nederlands', $languageLine->getTranslation('nl')); - } - - /** @test */ - public function it_doesnt_show_error_when_getting_nonexistent_translation() - { - $languageLine = $this->createLanguageLine('group', 'new', ['nl' => 'nederlands']); - $this->assertSame(null, $languageLine->getTranslation('en')); - } - - /** @test */ - public function get_fallback_locale_if_doesnt_exists() - { - $languageLine = $this->createLanguageLine('group', 'new', ['en' => 'English']); - $this->assertEquals('English', $languageLine->getTranslation('es')); - } -} diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 0000000..6f9e6b0 --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1,16 @@ +in('Feature'); + +function flushIlluminateTranslatorCache(): void +{ + app('translator')->setLoaded([]); +} + +function createLanguageLine(string $group, string $key, array $text): LanguageLine +{ + return LanguageLine::create(compact('group', 'key', 'text')); +} diff --git a/tests/TestCase.php b/tests/TestCase.php index e3d571d..6ff4594 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -1,7 +1,8 @@ up(); - $this->languageLine = $this->createLanguageLine('group', 'key', ['en' => 'english', 'nl' => 'nederlands']); + $this->languageLine = createLanguageLine('group', 'key', ['en' => 'english', 'nl' => 'nederlands']); } /** - * @param \Illuminate\Foundation\Application $app + * @param $app * - * @return array - */ - protected function getPackageProviders($app) - { - return [ - TranslationServiceProvider::class, - ]; - } - - /** - * @param \Illuminate\Foundation\Application $app + * @return void */ - protected function getEnvironmentSetUp($app) + protected function getEnvironmentSetUp($app): void { - $app['path.lang'] = $this->getFixturesDirectory('lang'); + $app['path.lang'] = __DIR__ . '/Fixtures/lang'; $app['config']->set('database.default', 'sqlite'); $app['config']->set('database.connections.sqlite', [ @@ -52,13 +48,15 @@ protected function getEnvironmentSetUp($app) ]); } - public function getFixturesDirectory(string $path): string - { - return __DIR__."/fixtures/{$path}"; - } - - protected function createLanguageLine(string $group, string $key, array $text): LanguageLine + /** + * @param Application $app + * + * @return array + */ + protected function getPackageProviders($app): array { - return LanguageLine::create(compact('group', 'key', 'text')); + return [ + TranslationServiceProvider::class, + ]; } } diff --git a/tests/TransTest.php b/tests/TransTest.php deleted file mode 100644 index 42097c7..0000000 --- a/tests/TransTest.php +++ /dev/null @@ -1,90 +0,0 @@ - [ - 1 => 'Yes', - 0 => 'No', - ], - ]; - - public function setUp(): void - { - parent::setUp(); - } - - /** @test */ - public function it_can_get_translations_for_language_files() - { - $this->assertEquals('en value', trans('file.key')); - $this->assertEquals('page not found', trans('file.404.title')); - $this->assertEquals('This page does not exists', trans('file.404.message')); - } - - /** @test */ - public function it_can_get_translations_for_language_files_for_the_current_locale() - { - app()->setLocale('nl'); - - $this->assertEquals('nl value', trans('file.key')); - $this->assertEquals('pagina niet gevonden', trans('file.404.title')); - $this->assertEquals('Deze pagina bestaat niet', trans('file.404.message')); - } - - /** @test */ - public function by_default_it_will_prefer_a_db_translation_over_a_file_translation() - { - $this->createLanguageLine('file', 'key', ['en' => 'en value from db']); - $this->createLanguageLine('file', '404.title', ['en' => 'page not found from db']); - - $this->assertEquals('en value from db', trans('file.key')); - $this->assertEquals('page not found from db', trans('file.404.title')); - $this->assertEquals('This page does not exists', trans('file.404.message')); - } - - /** @test */ - public function it_will_return_array_if_the_given_translation_is_nested() - { - foreach (Arr::dot($this->nested) as $key => $text) { - $this->createLanguageLine('nested', $key, ['en' => $text]); - } - - $this->assertEqualsCanonicalizing($this->nested['bool'], trans('nested.bool'), '$canonicalize = true', $delta = 0.0, $maxDepth = 10, $canonicalize = true); - } - - /** @test */ - public function it_will_return_the_translation_string_if_max_nested_level_is_reached() - { - foreach (Arr::dot($this->nested) as $key => $text) { - $this->createLanguageLine('nested', $key, ['en' => $text]); - } - - $this->assertEquals($this->nested['bool'][1], trans('nested.bool.1')); - } - - /** @test */ - public function it_will_return_the_dotted_translation_key_if_no_translation_found() - { - $notFoundKey = 'nested.bool.3'; - - foreach (Arr::dot($this->nested) as $key => $text) { - $this->createLanguageLine('nested', $key, ['en' => $text]); - } - - $this->assertEquals($notFoundKey, trans($notFoundKey)); - } - - /** @test */ - public function it_will_default_to_fallback_if_locale_is_missing() - { - app()->setLocale('de'); - $this->createLanguageLine('missing_locale', 'key', ['en' => 'en value from db']); - - $this->assertEquals('en value from db', trans('missing_locale.key')); - } -} diff --git a/tests/TranslationLoaders/DbTest.php b/tests/TranslationLoaders/DbTest.php deleted file mode 100644 index 5525eb6..0000000 --- a/tests/TranslationLoaders/DbTest.php +++ /dev/null @@ -1,134 +0,0 @@ -assertEquals('english', trans('group.key')); - } - - /** @test */ - public function it_can_get_a_correct_translation_after_the_locale_has_been_changed() - { - app()->setLocale('nl'); - - $this->assertEquals('nederlands', trans('group.key')); - } - - /** @test */ - public function it_can_return_the_group_and_the_key_when_getting_a_non_existing_translation() - { - app()->setLocale('nl'); - - $this->assertEquals('group.unknown', trans('group.unknown')); - } - - /** @test */ - public function it_supports_placeholders() - { - $this->createLanguageLine('group', 'placeholder', ['en' => 'text with :placeholder']); - - $this->assertEquals( - 'text with filled in placeholder', - trans('group.placeholder', ['placeholder' => 'filled in placeholder']) - ); - } - - /** @test */ - public function it_will_cache_all_translations() - { - trans('group.key'); - - $queryCount = count(DB::getQueryLog()); - $this->flushIlluminateTranslatorCache(); - - trans('group.key'); - - $this->assertEquals($queryCount, count(DB::getQueryLog())); - } - - /** @test */ - public function it_flushes_the_cache_when_a_translation_has_been_created() - { - $this->assertEquals('group.new', trans('group.new')); - - $this->createLanguageLine('group', 'new', ['en' => 'created']); - $this->flushIlluminateTranslatorCache(); - - $this->assertEquals('created', trans('group.new')); - } - - /** @test */ - public function it_flushes_the_cache_when_a_translation_has_been_updated() - { - trans('group.key'); - - $this->languageLine->setTranslation('en', 'updated'); - $this->languageLine->save(); - - $this->flushIlluminateTranslatorCache(); - - $this->assertEquals('updated', trans('group.key')); - } - - /** @test */ - public function it_flushes_the_cache_when_a_translation_has_been_deleted() - { - $this->assertEquals('english', trans('group.key')); - - $this->languageLine->delete(); - $this->flushIlluminateTranslatorCache(); - - $this->assertEquals('group.key', trans('group.key')); - } - - /** @test */ - public function it_can_work_with_a_custom_model() - { - $alternativeModel = new class extends LanguageLine { - protected $table = 'language_lines'; - public static function getTranslationsForGroup(string $locale, string $group): array - { - return ['key' => 'alternative class']; - } - }; - - $this->app['config']->set('translation-loader.model', get_class($alternativeModel)); - - $this->assertEquals('alternative class', trans('group.key')); - } - - /** @test */ - public function it_will_throw_an_exception_if_the_configured_model_does_not_extend_the_default_one() - { - $invalidModel = new class { - }; - - $this->app['config']->set('translation-loader.model', get_class($invalidModel)); - - $this->expectException(InvalidConfiguration::class); - - $this->assertEquals('alternative class', trans('group.key')); - } - - protected function flushIlluminateTranslatorCache() - { - $this->app['translator']->setLoaded([]); - } -} diff --git a/tests/TranslationManagerTest.php b/tests/TranslationManagerTest.php deleted file mode 100644 index 2221cdc..0000000 --- a/tests/TranslationManagerTest.php +++ /dev/null @@ -1,35 +0,0 @@ -app['config']->set('translation-loader.translation_loaders', []); - - $this->assertEquals('group.key', trans('group.key')); - } - - /** @test */ - public function it_will_merge_translation_from_all_providers() - { - $this->app['config']->set('translation-loader.translation_loaders', [ - Db::class, - DummyLoader::class, - ]); - - $this->createLanguageLine('db', 'key', ['en' => 'db']); - - $this->assertEquals('db', trans('db.key')); - $this->assertEquals('this is dummy', trans('dummy.dummy')); - } -}