Skip to content
This repository was archived by the owner on Aug 7, 2022. It is now read-only.

Commit 596b796

Browse files
authored
Merge pull request #3 from luisprmat/main
Optimize load of [locale].json exluding not required translations
2 parents 5fba20a + 65af63b commit 596b796

24 files changed

+637
-76
lines changed

.editorconfig

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,7 @@ indent_size = 4
99
trim_trailing_whitespace = true
1010

1111
[*.md]
12-
trim_trailing_whitespace = false
12+
trim_trailing_whitespace = false
13+
14+
[*.json]
15+
insert_final_newline = false

README.md

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,16 @@
1-
# Laravel Lang Installer
1+
<h1 align="center">Laravel Lang Installer</h1>
2+
3+
<p align="center">
4+
<a href="https://packagist.org/packages/luisprmat/laravel-lang-installer">
5+
<img src="https://img.shields.io/packagist/dt/luisprmat/laravel-lang-installer" alt="Total Downloads">
6+
</a>
7+
<a href="https://packagist.org/packages/luisprmat/laravel-lang-installer">
8+
<img src="https://img.shields.io/packagist/v/luisprmat/laravel-lang-installer" alt="Latest Stable Version">
9+
</a>
10+
<a href="https://packagist.org/packages/luisprmat/laravel-lang-installer">
11+
<img src="https://img.shields.io/packagist/l/luisprmat/laravel-lang-installer" alt="License">
12+
</a>
13+
</p>
214

315
This package helps us to quickly install the language files in a preferably fresh Laravel application.
416

@@ -12,11 +24,19 @@ composer require luisprmat/laravel-lang-installer --dev
1224

1325
## Usage
1426

15-
After install a new laravel application with `Laravel >= 5.5` the package autodiscover system will register the new command `lang:add`.
27+
### Add new language
28+
After install a new laravel application with `Laravel >= 5.5` the package autodiscover system will register the new command `lang:add` and you can call with
1629

17-
This command can take a unique argument (or none) that will be the short name of the language according to **ISO 15897**.
30+
```bash
31+
php artisan lang:add <locale>
32+
```
33+
where `<locale>` refers to the short name of any of the [supported languages](README.md#supported-languages)
34+
> ### *Warnings*
35+
> - **Add lang** action overwrites the language files so that you already had custom translations you could lose them.
36+
> - When adding a language this package first consults the `composer.json` file to copy only the translations of the supported packages that are installed ([Laravel Breeze](https://laravel.com/docs/8.x/starter-kits#laravel-breeze), [Laravel Cashier](https://laravel.com/docs/8.x/billing), [Laravel Fortify](https://laravel.com/docs/8.x/fortify) and [Laravel Jetstream](https://jetstream.laravel.com/2.x/introduction.html) are supported) `resources/lang/<locale>.json`. So it is good that you first install the supported packages that you will use and then run the command `php artisan lang:add <locale>`
37+
> - If this command does not receive arguments, the Spanish language [`es`] will be installed by default.
1838
19-
If this command does not receive arguments, the Spanish language [`es`] will be installed by default.
39+
This command can take a unique argument (or none) that will be the short name of the language according to **ISO 15897**.
2040

2141
This command also modifies the key `locale` in the `config/app.php` file to set the default language as passed through the parameter.
2242

@@ -51,12 +71,24 @@ php artisan lang:add pt_BR --no-default
5171
php artisan lang:add ar --inline
5272
```
5373

54-
74+
## Supported languages
75+
`af`, `ar`, `az`, `be`, `bg`, `bn`, `bs`, `ca`, `cs`, `cy`, `da`, `de`, `de_CH`
76+
, `el`, `es`, `et`, `eu`, `fa`, `fi`, `fil`, `fr`, `gl`, `he`, `hi`, `hr`, `hu`,
77+
`hy`, `id`, `is`, `it`, `ja`, `ka`, `kk`, `km`, `kn`, `ko`, `lt`, `lv`, `mk`, `
78+
mn`, `mr`, `ms`, `nb`, `ne`, `nl`, `nn`, `oc`, `pl`, `ps`, `pt`, `pt_BR`, `ro`,
79+
`ru`, `sc`, `si`, `sk`, `sl`, `sq`, `sr_Cyrl`, `sr_Latn`, `sr_Latn_ME`, `sv`, `s
80+
w`, `tg`, `th`, `tk`, `tl`, `tr`, `ug`, `uk`, `ur`, `uz_Cyrl`, `uz_Latn`, `vi`,
81+
`zh_CN`, `zh_HK`, `zh_TW`
5582

5683
## Contributing
5784
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
5885

59-
This package does not modify the translations, only copies them of [`laravel-lang/lang`](https://github.com/Laravel-Lang/lang/). So if you want to suggest changes in the translations you can make a PR to the [`laravel-lang/lang` package](https://github.com/Laravel-Lang/lang/blob/master/docs/contributing-to-dev.md)
86+
This package does not modify the translations, only copies them from [`laravel-lang/lang`](https://github.com/Laravel-Lang/lang/). So if you want to suggest changes in the translations you can make a PR to the [`laravel-lang/lang` package](https://github.com/Laravel-Lang/lang/blob/master/docs/contributing-to-dev.md)
6087

6188
## License
6289
[MIT](LICENSE.md)
90+
91+
## Todo
92+
93+
- [ ] Allow merge translations instead of overwrite them.
94+
- [ ] Add Command `lang:update` to update translations and detect new installed packages to update their translations.

src/Console/InstallCommand.php

Lines changed: 75 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
use Illuminate\Console\Command;
66
use Illuminate\Filesystem\Filesystem;
7+
use Illuminate\Support\Facades\File;
8+
use Illuminate\Support\Str;
79

810
class InstallCommand extends Command
911
{
@@ -13,15 +15,27 @@ class InstallCommand extends Command
1315

1416
protected $description = "Install translations for language 'locale' (default 'es')";
1517

18+
private array $supportedPackages = [
19+
'breeze' => 'laravel/breeze',
20+
'fortify' => 'laravel/fortify',
21+
'cashier' => 'laravel/cashier',
22+
'jetstream' => 'laravel/jetstream'
23+
];
24+
1625
public function handle()
1726
{
1827
$locale = (string)$this->argument('locale');
1928

20-
if (!in_array($locale, $this->getLocales())) {
29+
if (!in_array($locale, $this->getLocales(base_path('vendor/laravel-lang/lang/locales')))) {
2130
$this->error("Language [{$locale}] is not supported!");
2231
return;
2332
}
2433

34+
if (!File::exists(base_path('composer.json'))) {
35+
$this->error('composer.json not found!');
36+
return;
37+
}
38+
2539
(new Filesystem)->ensureDirectoryExists(resource_path("lang/{$locale}"));
2640

2741
copy(base_path("vendor/laravel-lang/lang/locales/{$locale}/auth.php"), resource_path("lang/{$locale}/auth.php"));
@@ -34,7 +48,14 @@ public function handle()
3448
copy(base_path("vendor/laravel-lang/lang/locales/{$locale}/validation.php"), resource_path("lang/{$locale}/validation.php"));
3549
}
3650

37-
$this->loadJsonFile($locale);
51+
$discoveredPackages = $this->discoveredPackages();
52+
53+
// Add 'fortify' translations if 'jetstream' is installed
54+
if (in_array('jetstream', $discoveredPackages)) {
55+
array_push($discoveredPackages, 'fortify');
56+
}
57+
58+
$this->loadJsonFile($locale, $discoveredPackages);
3859

3960
if (!$this->option('no-default')) {
4061
// Set config('app.locale')
@@ -43,6 +64,13 @@ public function handle()
4364
} else {
4465
$this->info("Language [{$locale}] installed successfully, but it isn't the default language.");
4566
}
67+
68+
if (!empty($discoveredPackages)) {
69+
$this->info(
70+
'Translations for ['. implode(', ', $discoveredPackages) .'] '
71+
. Str::plural('package', count($discoveredPackages)) .' merged!'
72+
);
73+
}
4674
}
4775

4876
/**
@@ -58,19 +86,40 @@ protected function pregReplaceInFile($search, $replace, $path)
5886
file_put_contents($path, preg_replace($search, $replace, file_get_contents($path)));
5987
}
6088

61-
private function loadJsonFile($locale)
89+
private function loadJsonFile($locale, $packages = [])
6290
{
63-
copy(base_path("vendor/laravel-lang/lang/locales/{$locale}/{$locale}.json"), resource_path("lang/{$locale}.json"));
91+
$baseSource = json_decode(File::get(base_path('vendor/laravel-lang/lang/source/en.json')));
92+
$jsonLocale = json_decode(File::get(base_path("vendor/laravel-lang/lang/locales/{$locale}/{$locale}.json")), true);
93+
94+
$showTags = $baseSource;
95+
96+
foreach ($packages as $package) {
97+
$showTags = array_merge(
98+
$showTags,
99+
json_decode(File::get(base_path("vendor/laravel-lang/lang/source/packages/{$package}.json")))
100+
);
101+
}
102+
103+
$showTags = array_unique($showTags);
104+
sort($showTags);
105+
106+
$modify = array_filter($jsonLocale, function ($item) use ($showTags) {
107+
return in_array($item, $showTags);
108+
}, ARRAY_FILTER_USE_KEY);
109+
110+
$modifiedJson = json_encode($modify, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
111+
112+
File::put(resource_path("lang/{$locale}.json"), $modifiedJson);
64113
}
65114

66115
/**
116+
* @param string $path
67117
* @return array
68118
*/
69-
protected function getLocales(): array
119+
protected function getLocales(string $path): array
70120
{
71121
$filesystem = new Filesystem;
72122

73-
$path = base_path("vendor/laravel-lang/lang/locales");
74123
$directories = $filesystem->directories($path);
75124

76125
$locales = [];
@@ -80,4 +129,24 @@ protected function getLocales(): array
80129
}
81130
return $locales;
82131
}
132+
133+
/**
134+
* Returns list of installed packages that are supported according to composer.json
135+
*
136+
* @return array
137+
*/
138+
protected function discoveredPackages(): array
139+
{
140+
$composer = json_decode(File::get(base_path('composer.json')), true);
141+
142+
$jsonToCreate = array_keys(array_merge($composer['require'], $composer['require-dev']));
143+
144+
$packagesToInstall = array_filter($jsonToCreate, function ($package) {
145+
return in_array($package, $this->supportedPackages);
146+
});
147+
148+
return array_keys(array_filter($this->supportedPackages, function ($package) use ($packagesToInstall) {
149+
return in_array($package, $packagesToInstall);
150+
}));
151+
}
83152
}
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
<?php
2+
3+
namespace Luisprmat\LaravelLangInstaller\Tests\Feature;
4+
5+
use Illuminate\Support\Facades\File;
6+
use Luisprmat\LaravelLangInstaller\Tests\TestCase;
7+
8+
class DiscoverPackagesTest extends TestCase
9+
{
10+
protected function setUp(): void
11+
{
12+
parent::setUp();
13+
$this->app->setBasePath(__DIR__ . '/../fixtures');
14+
15+
File::ensureDirectoryExists(config_path());
16+
File::copy(__DIR__ . '/../stubs/config/app.php', config_path('app.php'));
17+
}
18+
19+
protected function tearDown(): void
20+
{
21+
parent::tearDown();
22+
File::deleteDirectory(config_path());
23+
File::deleteDirectory(resource_path());
24+
File::delete(base_path('composer.json'));
25+
}
26+
27+
/** @test */
28+
function it_doesnt_execute_if_composer_json_doesnt_exist()
29+
{
30+
$this->artisan('lang:add')
31+
->expectsOutput('composer.json not found!')
32+
->assertExitCode(0);
33+
}
34+
35+
/** @test */
36+
function it_discovers_several_supported_packages_installed_from_composer_json()
37+
{
38+
File::put(base_path('composer.json'), $this->buildComposerWithDependencies(
39+
['"laravel/cashier": "^13.5"', '"package/other": "^2.0"'],
40+
['"laravel/breeze": "^1.4"', '"laravel/no-supported": "^1.0"']
41+
));
42+
43+
$command = $this->artisan('lang:add');
44+
$command->expectsOutput('Translations for [breeze, cashier] packages merged!');
45+
}
46+
47+
/** @test */
48+
function it_discovers_one_supported_package_installed_from_composer_json_require_dev()
49+
{
50+
File::put(base_path('composer.json'), $this->buildComposerWithDependencies(
51+
['"package/other": "^2.0"'],
52+
['"laravel/breeze": "^1.4"', '"laravel/no-supported": "^1.0"']
53+
));
54+
55+
$command = $this->artisan('lang:add');
56+
$command->expectsOutput('Translations for [breeze] package merged!');
57+
}
58+
59+
/** @test */
60+
function it_discovers_one_supported_package_installed_from_composer_json_require()
61+
{
62+
File::put(base_path('composer.json'), $this->buildComposerWithDependencies(
63+
['"laravel/cashier": "^13.5"']
64+
));
65+
66+
$command = $this->artisan('lang:add');
67+
$command->expectsOutput('Translations for [cashier] package merged!');
68+
}
69+
}

0 commit comments

Comments
 (0)