diff --git a/src/Illuminate/Foundation/helpers.php b/src/Illuminate/Foundation/helpers.php index 90a78ae0d76e..b948c55d2b51 100644 --- a/src/Illuminate/Foundation/helpers.php +++ b/src/Illuminate/Foundation/helpers.php @@ -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. diff --git a/tests/Foundation/FoundationHelpersTest.php b/tests/Foundation/FoundationHelpersTest.php index ddf06f83988e..126f0c058b78 100644 --- a/tests/Foundation/FoundationHelpersTest.php +++ b/tests/Foundation/FoundationHelpersTest.php @@ -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; @@ -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()); + } }