implement RFC 0001

This commit is contained in:
Pig Fang 2020-07-02 12:20:05 +08:00
parent cf40ca01ea
commit e9f8be1653
No known key found for this signature in database
GPG Key ID: A8198F548DADA9E2
4 changed files with 75 additions and 0 deletions

View File

@ -0,0 +1,35 @@
<?php
namespace App\Listeners;
use App\Models\User;
use Illuminate\Http\Request;
class SetAppLocale
{
/** @var Request */
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function handle($event)
{
/** @var User */
$user = $event->user;
if ($this->request->has('lang')) {
$user->locale = $this->request->input('lang');
$user->save();
return;
}
$locale = $user->locale;
if ($locale) {
app()->setLocale($locale);
}
}
}

View File

@ -33,5 +33,8 @@ class EventServiceProvider extends ServiceProvider
'closet.removed' => [
Listeners\ResetPlayerForRemovedClosetItem::class,
],
'Illuminate\Auth\Events\Authenticated' => [
Listeners\SetAppLocale::class,
],
];
}

View File

@ -8,6 +8,7 @@ $factory->define(User::class, function (Faker\Generator $faker) {
return [
'email' => $faker->email,
'nickname' => $faker->name,
'locale' => null,
'score' => 1000,
'avatar' => 0,
'password' => app('cipher')->hash(Str::random(10), config('secure.salt')),

View File

@ -0,0 +1,36 @@
<?php
namespace Tests;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class SetAppLocaleTest extends TestCase
{
use DatabaseTransactions;
public function testUpdateUserLocale()
{
$user = factory(User::class)->create();
// This is a hacky way.
// We must call `get` first before set authentication,
// since this let Laravel update the `Request` instance,
// otherwise the event handler will be called first and
// it won't be able to retrieve request information.
$this->get('/?lang=en');
$this->actingAs($user);
$this->assertEquals('en', $user->fresh()->locale);
}
public function testSetAppLocale()
{
$user = factory(User::class)->create(['locale' => 'zh_CN']);
event(new \Illuminate\Auth\Events\Authenticated('web', $user));
$this->assertEquals('zh_CN', app()->getLocale());
app()->setLocale('en');
}
}