jueves, 4 de noviembre de 2010

Creating Random Data for Fixtures

A couple a days a go I heard a sales man raving about the capabilities of Toad (a Quest Software software) of populating tables with random data. The problem I saw with this feature is that it filled the table with incomprehensible gibberish.

Symonfy allows you to load data to your tables, but to create random data you need to rely a little on php.
Lets use a basic client table like this one (on config/doctrine/schema.yml):

Client:
columns:
id:
type: integer(4)
primary: true
autoincrement: true
firstname:
type: string(30)
notnull: true
middlename:
type: string(30)
notnull: false
lastname:
type: string(30)
notnull: true
dateOfBirth:
type: date
notnull: true
nationalId:
type: string(13)
notnull: true
gender:
type: enum
length: 1
values: ['M', 'F']

To create random clients will combine PHP code inside the fixtures YaML (data/fixtures/fixtures.yml)file like this:

<?php $names = array('Juan', 'Pedro', 'Perenceo', 'Aquileo', 'Ramiro', 'Esteban',
'John', 'Rabindranath', 'Pablo', 'Judas', 'Akira', NULL); ?>
<?php $lastnames = array('De Urriola', 'Escobedo', 'Einstein', 'Escobar','Gonzalez',
'Luna', 'Martinez', 'Obama', 'Perez',
'Ramirez','Hawkins', 'Marquez', 'Jaramillo',
'Lopez', 'Vergara', NULL); ?>
Client:
<?php for ($i = 1; $i <= 10; $i++): ?>
client_<?php echo $i ?>:
firstname: <?php echo $names[rand(0,count($names)-2)] ."\n" ?>
middlename: <?php echo $names[rand(0,count($names)-1)] ."\n"?>
lastname: <?php echo $lastnames[rand(0,count($lastnames)-2)] ."\n" ?>
nationalId: <?php echo rand(1,9) . '-'.rand(25,999).'-'.rand(1500,9859). "\n" ?>
dateOfBirth: <?php echo "'". rand(1956,1971).'-'.rand(1,12). '-'.rand(1,28) ."'\n" ?>
gender: M
<?php endfor ?>

After running doctrine:data-load the fixtures will create ten cliens records based on the $names and $lastname arrays.

No hay comentarios:

Publicar un comentario