Search code examples
symfonynelmio-alicealice-fixtures

Alice Faker library choose random from array


I am trying to generate a dummy data using AliceBundle for Symfony Framework. Everything seems to be working fine except I am looking for a way to randomly assign data from an array to a property called type. Looking at the faker library I can see that I can generate that using randomElement($array = array ('a','b','c'))

I am trying to convert that into YML and I think that is equivalent of

<randomElement(['a','b','c'])>

But this produces an error

[Nelmio\Alice\Throwable\Exception\FixtureBuilder\ExpressionLanguage\LexException] Could not lex the value "['a'".

This is my complete yml

AppBundle\Entity\Job:
    job{1..5}:
        title: <jobTitle()>
        description: <paragraph(3)>
        length: "3_months_full_time"
        type: <randomElement(['a','b','c'])>
        bonus: <paragraph(3)>
        expired_at: "2016-12-21"
        job_user: "@emp*"

Solution

  • I ended up creating a custom provider

    namespace AppBundle\DataFixtures\Faker\Provider;
    
        class JobTypeProvider
        {
            public static function jobType()
            {
                $types = array("paid", "unpaid", "contract");
                $typeIndex = array_rand($types);
                return  $types[$typeIndex];
            }
        }
    

    Add that to services.yml

    app.data_fixtures_faker_provider.job_type_provider:
        class: AppBundle\DataFixtures\Faker\Provider\JobTypeProvider
        tags: [ { name: nelmio_alice.faker.provider } ]
    

    And then use it in yml file

    AppBundle\Entity\Job:
        job{1..50}:
            title: <jobTitle()>
            description: <paragraph(3)>
            length: <jobLength()>
            job_industry: "@title*"
            type: <jobType()>
            bonus: <paragraph(3)>
            expired_at: "2016-12-21"
            job_user: "@emp*"
    

    Notice type: , this is being generated from service now.