master

laravel/framework

Last updated at: 29/12/2023 09:23

WithFaker.php

TLDR

The WithFaker trait in the Illuminate\Foundation\Testing namespace provides methods for creating and using a Faker instance for generating fake data during testing.

Methods

setUpFaker

This method is called to set up the Faker instance. It initializes the $faker property with the result of calling makeFaker().

faker

This method returns the default Faker instance for a given locale. If a locale is provided, it returns a new Faker instance for that locale by calling makeFaker($locale).

makeFaker

This method creates a new Faker instance for the given locale. If the application instance ($this->app) is set, it uses the configured faker locale from the application's configuration. Otherwise, it creates a new Faker instance using the default locale.

If the application instance has a binding for the Generator class, it uses that binding to create the Faker instance. Otherwise, it uses the Factory::create() method to create a new Faker instance.

Classes

None

<?php

namespace Illuminate\Foundation\Testing;

use Faker\Factory;
use Faker\Generator;

trait WithFaker
{
    /**
     * The Faker instance.
     *
     * @var \Faker\Generator
     */
    protected $faker;

    /**
     * Setup up the Faker instance.
     *
     * @return void
     */
    protected function setUpFaker()
    {
        $this->faker = $this->makeFaker();
    }

    /**
     * Get the default Faker instance for a given locale.
     *
     * @param  string|null  $locale
     * @return \Faker\Generator
     */
    protected function faker($locale = null)
    {
        return is_null($locale) ? $this->faker : $this->makeFaker($locale);
    }

    /**
     * Create a Faker instance for the given locale.
     *
     * @param  string|null  $locale
     * @return \Faker\Generator
     */
    protected function makeFaker($locale = null)
    {
        if (isset($this->app)) {
            $locale ??= $this->app->make('config')->get('app.faker_locale', Factory::DEFAULT_LOCALE);

            if ($this->app->bound(Generator::class)) {
                return $this->app->make(Generator::class, ['locale' => $locale]);
            }
        }

        return Factory::create($locale ?? Factory::DEFAULT_LOCALE);
    }
}