Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add localization #362

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions app/Actions/Jetstream/UserProfile.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public function __invoke(Request $request, array $data): array
{
$providers = collect(config('auth.login_providers'))->filter(fn ($provider) => ! empty($provider));
$providersName = $providers->mapWithKeys(function ($provider) {
return [$provider => config("services.$provider.name") ?? __("auth.login_provider_{$provider}")];
return [$provider => config("services.$provider.name") ?? trans_ignore("auth.login_provider_{$provider}")];
});

$webauthnKeys = $request->user()->webauthnKeys()
Expand All @@ -37,10 +37,10 @@ public function __invoke(Request $request, array $data): array
$data['userTokens'] = $request->user()->userTokens()->get();
$data['webauthnKeys'] = $webauthnKeys;

$data['locales'] = collect(config('lang-detector.languages'))->map(fn ($locale) => [
$data['locales'] = collect(config('localizer.supported_locales'))->map(fn ($locale) => [
'id' => $locale,
'name' => __('auth.lang', [], $locale),
]);
])->sortByCollator(fn ($locale) => $locale['name']);

return $data;
}
Expand Down
86 changes: 86 additions & 0 deletions app/Console/Commands/Local/MonicaLocalize.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

namespace App\Console\Commands\Local;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use Stichoza\GoogleTranslate\GoogleTranslate;
use Symfony\Component\Finder\Finder;

use function Safe\json_decode;
use function Safe\json_encode;

class MonicaLocalize extends Command
{
private GoogleTranslate $googleTranslate;

/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'monica:localize';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate locale files.';

/**
* Execute the console command.
*/
public function handle(): void
{
$locales = config('localizer.supported_locales');
array_shift($locales);
$this->call('localize', ['lang' => implode(',', $locales)]);

$this->loadTranslations(['en'] + $locales);
}

/**
* Heavily inspired by https://stevensteel.com/blog/automatically-find-translate-and-save-missing-translation-keys.
*/
private function loadTranslations(array $locales): void
{
$path = lang_path();
$finder = new Finder();
$finder->in($path)->name(['*.json'])->files();
$this->googleTranslate = new GoogleTranslate();

foreach ($finder as $file) {
$locale = $file->getFilenameWithoutExtension();

if (! in_array($locale, $locales)) {
continue;
}

$this->info('loading locale: '.$locale);
$jsonString = $file->getContents();
$strings = json_decode($jsonString, true);

$this->translateStrings($locale, $strings);
}
}

private function translateStrings(string $locale, array $strings)
{
if ($locale !== 'en') {
foreach ($strings as $index => $value) {
if ($value === '') {
$this->googleTranslate->setTarget($locale);
$translated = $this->googleTranslate->translate($index);
$this->info('translating: `'.$index.'` to `'.$translated.'`');

// we store the translated string in the array
$strings[$index] = $translated;
}
}
}

// now we need to save the array back to the file
Storage::disk('lang')->put($locale.'.json', json_encode($strings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
}
1 change: 1 addition & 0 deletions app/Console/Commands/Setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public function handle(): void
}

$this->artisan('✓ Performing migrations', 'migrate', ['--force' => true]);
$this->artisan('✓ Seed database with records', 'db:seed', ['--force' => true]);

// Cache config
if ($this->getLaravel()->environment() == 'production'
Expand Down
5 changes: 5 additions & 0 deletions app/Console/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\App;

class Kernel extends ConsoleKernel
{
Expand All @@ -26,6 +27,10 @@ protected function commands()
{
$this->load(__DIR__.'/Commands');

if (! App::environment('production')) {
$this->load(__DIR__.'/Commands/Local');
}

require base_path('routes/console.php');
}
}
79 changes: 79 additions & 0 deletions app/Helpers/CollectionHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

namespace App\Helpers;

use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;

class CollectionHelper
{
/**
* Sort the collection using the given callback.
*/
public static function sortByCollator(Collection $collect, callable|string $callback, int $options = \Collator::SORT_STRING, bool $descending = false): Collection
{
$results = [];

$callback = static::valueRetriever($callback);

// First we will loop through the items and get the comparator from a callback
// function which we were given. Then, we will sort the returned values and
// and grab the corresponding values for the sorted keys from this array.
foreach ($collect->all() as $key => $value) {
$results[$key] = $callback($value, $key);
}

// Using Collator to sort the array, with locale-sensitive sort ordering support.
static::getCollator()->asort($results, $options);
if ($descending) {
$results = array_reverse($results);
}

// Once we have sorted all of the keys in the array, we will loop through them
// and grab the corresponding model so we can set the underlying items list
// to the sorted version. Then we'll just return the collection instance.
foreach (array_keys($results) as $key) {
$results[$key] = $collect->get($key);
}

return new Collection(array_values($results));
}

/**
* Get a Collator object for the locale or current locale.
*/
public static function getCollator(string $locale = null): \Collator
{
static $collators = [];

if (! $locale) {
$locale = App::getLocale();
}
if (! Arr::has($collators, $locale)) {
$collator = new \Collator($locale);

if (currentLang($locale) === 'fr') {
$collator->setAttribute(\Collator::FRENCH_COLLATION, \Collator::ON);
}

$collators[$locale] = $collator;

return $collator;
}

return $collators[$locale];
}

/**
* Get a value retrieving callback.
*/
protected static function valueRetriever(callable|string $value): callable
{
if (! is_string($value) && is_callable($value)) {
return $value;
}

return fn ($item) => data_get($item, $value);
}
}
72 changes: 72 additions & 0 deletions app/Helpers/helpers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

use Illuminate\Support\Facades\App;

use function Safe\preg_match;
use function Safe\preg_split;

if (! function_exists('trans_key')) {
/**
* Extract the message.
*/
function trans_key(string $key = null): ?string
{
return $key;
}
}

if (! function_exists('trans_ignore')) {
/**
* Translate the given message. It won't be extracted by monica:localize command.
*/
function trans_ignore(string $key = null, array $replace = [], string $locale = null): string
{
return __($key, $replace, $locale);
}
}

if (! function_exists('currentLang')) {
/**
* Get the current language from locale.
*/
function currentLang(string $locale = null): string
{
if ($locale === null) {
$locale = App::getLocale();
}

if (preg_match('/(-|_)/', $locale)) {
$locale = preg_split('/(-|_)/', $locale, 2)[0];
}

return mb_strtolower($locale);
}
}

if (! function_exists('htmldir')) {
/**
* Get the direction: left to right/right to left.
*/
function htmldir()
{
$lang = currentLang();
switch ($lang) {
// Source: https://meta.wikimedia.org/wiki/Template:List_of_language_names_ordered_by_code
case 'ar':
case 'arc':
case 'dv':
case 'fa':
case 'ha':
case 'he':
case 'khw':
case 'ks':
case 'ku':
case 'ps':
case 'ur':
case 'yi':
return 'rtl';
default:
return 'ltr';
}
}
}
4 changes: 2 additions & 2 deletions app/Http/Controllers/AdministrationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ public function show(Request $request, User $user)
'plan' => [
'id' => $licence->plan->id,
'product' => $licence->plan->product,
'friendly_name' => $licence->plan->friendly_name,
'description' => $licence->plan->description,
'friendly_name' => __($licence->plan->translation_key),
'description' => __($licence->plan->description_key),
'plan_name' => $licence->plan->plan_name,
'price' => $price['price'],
'frequency' => $price['frequency_name'],
Expand Down
2 changes: 1 addition & 1 deletion app/Http/Controllers/Auth/LoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function __invoke(Request $request): Response
{
$providers = collect(config('auth.login_providers'))->filter(fn ($provider) => ! empty($provider));
$providersName = $providers->mapWithKeys(function ($provider) {
return [$provider => config("services.$provider.name") ?? __("auth.login_provider_{$provider}")];
return [$provider => config("services.$provider.name") ?? trans_ignore("auth.login_provider_{$provider}")];
});

$webauthnRemember = $request->cookie('webauthn_remember');
Expand Down
4 changes: 2 additions & 2 deletions app/Http/Controllers/MonicaController.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ public function index(Request $request): InertiaResponse

return [
'id' => $plan->id,
'friendly_name' => $plan->friendly_name,
'description' => $plan->description,
'friendly_name' => __($plan->translation_key),
'description' => __($plan->description_key),
'plan_name' => $plan->plan_name,
'price' => $price['price'],
'frequency' => $price['frequency_name'],
Expand Down
4 changes: 2 additions & 2 deletions app/Http/Controllers/OfficeLifeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ public function index(Request $request): InertiaResponse

return [
'id' => $plan->id,
'friendly_name' => $plan->friendly_name,
'description' => $plan->description,
'friendly_name' => __($plan->translation_key),
'description' => __($plan->description_key),
'plan_name' => $plan->plan_name,
'single_price' => $price['price'],
'price' => $price['price'],
Expand Down
4 changes: 2 additions & 2 deletions app/Models/Plan.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ class Plan extends Model
protected $fillable = [
'id',
'product',
'friendly_name',
'description',
'translation_key',
'description_key',
'plan_name',
'plan_id_on_paddle',
];
Expand Down
20 changes: 20 additions & 0 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

namespace App\Providers;

use App\Helpers\CollectionHelper;
use App\Http\Controllers\Profile\WebauthnDestroyResponse;
use App\Http\Controllers\Profile\WebauthnUpdateResponse;
use App\Models\Receipt;
use App\Models\Subscription;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
Expand Down Expand Up @@ -52,6 +54,24 @@ public function register()

return $result;
});

if (! Collection::hasMacro('sortByCollator')) {
Collection::macro('sortByCollator', function (callable|string $callback) {
/** @var Collection */
$collect = $this;

return CollectionHelper::sortByCollator($collect, $callback);
});
}

if (! Collection::hasMacro('sortByCollatorDesc')) {
Collection::macro('sortByCollatorDesc', function (callable|string $callback) {
/** @var Collection */
$collect = $this;

return CollectionHelper::sortByCollator($collect, $callback, descending: true);
});
}
}

/**
Expand Down
Loading
Loading