Skip to content

Commit

Permalink
Merge pull request #95 from askdkc/add-langswitcher
Browse files Browse the repository at this point in the history
Add Language Switcher / 言語切替機能追加
  • Loading branch information
askdkc authored Jul 8, 2023
2 parents 28e14ab + 568d70a commit 641e40d
Show file tree
Hide file tree
Showing 11 changed files with 297 additions and 35 deletions.
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ php artisan breezejp
- [Laravel Langと何が違うの?](#laravel-langと何が違うの)
- [おまけ](#おまけ)
- [言語切り替えサンプルアプリ](#言語の切り替えサンプルアプリ)
- [言語切替機能のインストール](#言語の切り替え機能のインストール)
- [変更履歴](#変更履歴)
- [貢献について](#貢献について)
- [セキュリティや脆弱性について](#セキュリティや脆弱性について)
Expand Down Expand Up @@ -354,6 +355,37 @@ MAIL_FROM_NAME="${APP_NAME}"

![251501263-d807d110-971e-44c0-a284-9e1b57c73894](https://github.com/askdkc/breezejp/assets/7894265/d52738c5-c6ae-4f92-87ef-0046f8cff4f7)

## 言語の切り替え機能のインストール
サンプルアプリなんて面倒だよ、さっさと言語切り替え使いたいよ!という人のために、言語切り替え機能をインストールする方法をご紹介します🤗

```bash
php artisan breezejp --langswitch
```

後は `/language/{locale}` にアクセスするだけで言語が切り替わるので、そこを叩くリクエストを送ってご利用ください

#### Laravelアプリの起動

```bash
php artisan serve
```

- 日本語に切り替える例

```
http://127.0.0.1:8000/language/ja
```

- 英語に切り替える例

```
http://127.0.0.1:8000/language/ja
```

これでLaravel Breezeの各種メニューの言語が切り替わるのが確認できると思います🤯


簡単でしょ?😁

## 変更履歴

Expand Down
55 changes: 21 additions & 34 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,36 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.0/phpunit.xsd"
backupGlobals="false"
bootstrap="vendor/autoload.php"
colors="true"
processIsolation="false"
stopOnFailure="false"
executionOrder="random"
failOnWarning="true"
failOnRisky="true"
failOnEmptyTestSuite="true"
beStrictAboutOutputDuringTests="true"
cacheDirectory=".phpunit.cache"
backupStaticProperties="false"
>
<testsuites>
<testsuite name="Askdkc Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<coverage>
<include>
<directory suffix=".php">./src</directory>
</include>
<report>
<html outputDirectory="build/coverage"/>
<text outputFile="build/coverage.txt"/>
<clover outputFile="build/logs/clover.xml"/>
</report>
</coverage>
<logging>
<junit outputFile="build/report.junit.xml"/>
</logging>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.2/phpunit.xsd" backupGlobals="false" bootstrap="vendor/autoload.php" colors="true" processIsolation="false" stopOnFailure="false" executionOrder="random" failOnWarning="true" failOnRisky="true" failOnEmptyTestSuite="true" beStrictAboutOutputDuringTests="true" cacheDirectory=".phpunit.cache" backupStaticProperties="false">
<testsuites>
<testsuite name="Askdkc Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<coverage>
<report>
<html outputDirectory="build/coverage"/>
<text outputFile="build/coverage.txt"/>
<clover outputFile="build/logs/clover.xml"/>
</report>
</coverage>
<logging>
<junit outputFile="build/report.junit.xml"/>
</logging>
<source>
<include>
<directory suffix=".php">./src</directory>
</include>
</source>
</phpunit>
9 changes: 8 additions & 1 deletion src/Commands/BreezejpCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,19 @@

class BreezejpCommand extends Command
{
public $signature = 'breezejp';
use InstallLanguageSwitcher;

public $signature = 'breezejp {--langswitch : Install Language Switcher 言語切替機能のインストール}';

public $description = 'Add Japanese Translation files for Laravel Breeze';

public function handle(): int
{
// Install Language Switcher 言語切替機能をインストール
if ($this->option('langswitch')) {
return $this->installLanguageSwitcher();
}

$this->info('Laravel Breeze用に日本語翻訳ファイルを準備します');

(new Filesystem)->ensureDirectoryExists(lang_path());
Expand Down
65 changes: 65 additions & 0 deletions src/Commands/InstallLanguageSwitcher.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

namespace Askdkc\Breezejp\Commands;

use Illuminate\Filesystem\Filesystem;

trait InstallLanguageSwitcher
{
/**
* Install the Language Switcher stack.
*/
public function installLanguageSwitcher(): int
{
$this->info('言語切替用のRoute language/{locale} を準備します');

// 実行済みなら実行しない
$routesFile = file_get_contents(base_path('routes/web.php'));
if (strpos($routesFile, '// Language Switcher Route 言語切替用ルートだよ') !== false) {
$this->info('言語切替用の Route は既に登録済みです');
} else {
file_put_contents(
base_path('routes/web.php'),
file_get_contents(__DIR__.'/../../stubs/default/routes/web.stub'),
FILE_APPEND
);
}

// If Middleware Localization is already installed, skip
if (file_exists(base_path('app/Http/Middleware/Localization.php'))) {
$this->info('言語切替用の Middleware は既に登録済みです');
} else {
$this->info('言語切替用の Middleware を準備します');
copy(__DIR__.'/../../stubs/app/Http/Middleware/Localization.php', base_path('app/Http/Middleware/Localization.php'));
(new Filesystem)->copyDirectory(__DIR__.'/../../stubs/lang/', lang_path());
}

$this->info('Kernel に Middleware を登録します');
// Read the contents of the file into a string
$file = base_path('app/Http/Kernel.php');
$contents = file_get_contents($file);

// 実行済みなら実行しない
if (strpos($contents, '\App\Http\Middleware\Localization::class,') !== false) {
$this->info('言語切替用の Middleware は Kernel に既に登録済みです');

return self::SUCCESS;
}
// Kernel内の既存の \App\Http\Middleware\VerifyCsrfToken::class の位置を取得
$position = strpos($contents, '\App\Http\Middleware\VerifyCsrfToken::class,');
if ($position !== false) {
$appendText = file_get_contents(__DIR__.'/../../stubs/app/Http/Kernel.stub');

$contents = substr_replace($contents, $appendText, $position, 0);
file_put_contents($file, $contents);

$this->info('Language Switherのインストールが完了しました!');

return self::SUCCESS;
}

$this->error('Language Switherのインストールが失敗しました!');

return self::FAILURE;
}
}
1 change: 1 addition & 0 deletions stubs/app/Http/Kernel.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
\App\Http\Middleware\Localization::class,
25 changes: 25 additions & 0 deletions stubs/app/Http/Middleware/Localization.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;

class Localization
{
/**
* Handle an incoming request.
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if (Session::has('locale')) {
App::setLocale(Session::get('locale'));
}

return $next($request);
}
}
8 changes: 8 additions & 0 deletions stubs/default/routes/web.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

// Language Switcher Route 言語切替用ルートだよ
Route::get('language/{locale}', function ($locale) {
app()->setLocale($locale);
session()->put('locale', $locale);

return redirect()->back();
});
68 changes: 68 additions & 0 deletions tests/Kernel.php.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],

'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];

/**
* The application's middleware aliases.
*
* Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
*
* @var array<string, class-string|string>
*/
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
14 changes: 14 additions & 0 deletions tests/LanguageSwitcherInstallTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

test('breezejp language switcher command successfully', closure: function () {
$this->artisan('breezejp --langswitch')
->expectsOutput('言語切替用のRoute language/{locale} を準備します')
->expectsOutput('言語切替用の Middleware を準備します')
->expectsOutput('Kernel に Middleware を登録します')
->expectsOutput('Language Switherのインストールが完了しました!')
->assertExitCode(0);

$this->assertFileExists(base_path('app/Http/Middleware/Localization.php'));
$webfile = file_get_contents(base_path('routes/web.php'));
$this->assertStringContainsString('// Language Switcher Route 言語切替用ルートだよ', $webfile);
});
24 changes: 24 additions & 0 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,26 @@ protected function setUp(): void
{
parent::setUp();

// テスト用のファイルが残ってたら消す(web.php)
if (is_file(__DIR__.'/../vendor/orchestra/testbench-core/laravel/routes/web.php')) {
unlink(__DIR__.'/../vendor/orchestra/testbench-core/laravel/routes/web.php');
}

// テスト用のファイル作成(web.php)
if (! is_file(__DIR__.'/../vendor/orchestra/testbench-core/laravel/routes/web.php')) {
copy(__DIR__.'/web.php.stub', __DIR__.'/../vendor/orchestra/testbench-core/laravel/routes/web.php');
}

// テスト用のファイルが残ってたら消す(Kernel.php)
if (is_file(__DIR__.'/../vendor/orchestra/testbench-core/laravel/app/Http/Kernel.php')) {
unlink(__DIR__.'/../vendor/orchestra/testbench-core/laravel/app/Http/Kernel.php');
}

// テスト用のファイル作成(Kernel.php)
if (! is_file(__DIR__.'/../vendor/orchestra/testbench-core/laravel/app/Http/Kernel.php')) {
copy(__DIR__.'/Kernel.php.stub', __DIR__.'/../vendor/orchestra/testbench-core/laravel/app/Http/Kernel.php');
}

Factory::guessFactoryNamesUsing(
fn (string $modelName) => 'Askdkc\\Breezejp\\Database\\Factories\\'.class_basename($modelName).'Factory'
);
Expand All @@ -26,6 +46,10 @@ protected function setUp(): void
rmdir(__DIR__.'/../vendor/orchestra/testbench-core/laravel/lang/ja');
}

if (is_file(__DIR__.'/../vendor/orchestra/testbench-core/laravel/app/Http/Middleware/Localization.php')) {
unlink(__DIR__.'/../vendor/orchestra/testbench-core/laravel/app/Http/Middleware/Localization.php');
}

// config/app.phpのlocaleをenに戻す
$configfile = file_get_contents(__DIR__.'/../vendor/orchestra/testbench-core/laravel/config/app.php');
$configfile = str_replace("'locale' => 'ja'", "'locale' => 'en'", $configfile);
Expand Down
31 changes: 31 additions & 0 deletions tests/web.php.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
return view('welcome');
});

Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () {
Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

require __DIR__.'/auth.php';

0 comments on commit 641e40d

Please sign in to comment.