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

[9.x] Introduce a fake() helper to resolve faker singletons, per locale #42844

Merged
merged 2 commits into from
Jun 21, 2022
Merged
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
21 changes: 21 additions & 0 deletions src/Illuminate/Foundation/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,27 @@ function event(...$args)
}
}

if (! function_exists('fake') && class_exists(\Faker\Factory::class)) {
/**
* Get a faker instance.
*
* @param ?string $locale
* @return \Faker\Generator
*/
function fake($locale = null)
{
$locale ??= app('config')->get('app.faker_locale') ?? 'en_US';

$abstract = \Faker\Generator::class.':'.$locale;

if (! app()->bound($abstract)) {
app()->singleton($abstract, fn () => \Faker\Factory::create($locale));
}

return app()->make($abstract);
}
}

if (! function_exists('info')) {
/**
* Write some information to the log.
Expand Down
30 changes: 30 additions & 0 deletions tests/Foundation/FoundationHelpersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Illuminate\Tests\Foundation;

use Exception;
use Illuminate\Config\Repository as ConfigRepository;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Mix;
Expand Down Expand Up @@ -244,4 +245,33 @@ public function testMixIsSwappableForTests()

$this->assertSame('expected', mix('asset.png'));
}

public function testFakeReturnsSameInstance()
{
app()->instance('config', new ConfigRepository([]));

$this->assertSame(fake(), fake());
$this->assertSame(fake(), fake('en_US'));
$this->assertSame(fake('en_AU'), fake('en_AU'));
$this->assertNotSame(fake('en_US'), fake('en_AU'));

app()->flush();
}

public function testFakeUsesLocale()
{
mt_srand(12345, MT_RAND_PHP);
app()->instance('config', new ConfigRepository([]));

// Should fallback to en_US
$this->assertSame('Arkansas', fake()->state());
$this->assertSame('Australian Capital Territory', fake('en_AU')->state());
$this->assertSame('Guadeloupe', fake('fr_FR')->region());

app()->instance('config', new ConfigRepository(['app' => ['faker_locale' => 'en_AU']]));
mt_srand(4, MT_RAND_PHP);

// Should fallback to en_US
$this->assertSame('Australian Capital Territory', fake()->state());
}
}