Jacobo
Jacobo

Reputation: 1391

Laravel generator gives: Cannot redeclare generatorFunction()

I have the following code, but when I run my factory I got the following exception:

Cannot redeclare questionIndex() (previously declared in /Users/user/Desktop/my-app/database/factories/QuestionFactory.php:42) in /Users/user/Desktop/my-app/database/factories/QuestionFactory.php on line 46

This occurs when I run my unit tests, and this specific factory is not on the test right now. I have other factory that has a generator but the name of the function is completely different. Is called autoIncrement().

<?php

use Faker\Generator as Faker;

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/

$questionIndex = questionIndex();

$factory->define(App\Models\Question::class, function (Faker $faker, $overrides) use ($questionIndex) {

    $question = [
        'How is 2 + 2?',
        'Choose, what is the possibility to win the lottery?',
        'According to the Big Brother, is 2 + 2 = 5?'
    ];

    $questionType = [
        'numeric',
        'multiple-choice',
        'true-or-false'
    ];

    $index = $questionIndex->current();
    $questionIndex->next();
    return [
        'title' => $question[$index],
        'type' => $questionType[$index],
        'category_id' => $overrides['category_id']
    ];

});

function questionIndex() {
    for ($i = 0; $i < 100000; $i++) {
        yield $i%3;
    }
}

Upvotes: 2

Views: 1271

Answers (2)

Jigar Shah
Jigar Shah

Reputation: 6223

You can check your defined function exists or not using function_exists, it will not allow to re declare

if (!function_exists('questionIndex')) {
    function questionIndex() {
        for ($i = 0; $i < 100000; $i++) {
            yield $i%3;
        }
    }
}

Upvotes: 2

Wreigh
Wreigh

Reputation: 3297

Try to use a function declaration shield/protection just in case that the file was included twice, then the function won't be redeclared.

if (!function_exists('questionIndex')) {
    function questionIndex() {
        for ($i = 0; $i < 100000; $i++) {
            yield $i%3;
        }
    }
}

Upvotes: 6

Related Questions