Skip to content
Lewis Dyer edited this page Aug 18, 2015 · 13 revisions

Locale Objects

These Objects are used by the Text generating Datatypes think of them like a datasource for text generating. Only included locale is English but you may write your own.

Add Custom Locale

  1. Navigate to project directory open extension/faker/locale
  2. Create the new file xxxxlocale.php (filenames are lowercase)
  3. Fill in the class from quick start below.
  4. Register with factory in bootstrap.php.

Use the following a quick start.

<?php

namespace Faker\Extension\Locale;

use Faker\Text\StringFactoryInterface,
    Faker\Locale\LocaleInterface;

class XXXXLocale implements LocaleInterface
{
    /**
      *  Fetch the consonants from alphabet
      *
      *  @access public
      *  @return \Faker\Test\SimpleTextInterface
      */
    public function getConsonants();
   
    /**
      *  Fetch the vowels from alphabet
      *  
      *  @access public
      *  @return \Faker\Test\SimpleTextInterface
      */
    public function getVowels();
    ;

    /**
      *  Fetch the letters of the alphabet
      *  
      *  @access public
      *  @return \Faker\Test\SimpleTextInterface
      */
    public function getLetters();
    

    /**
      *   Fetch an array of filler text
      *   
      *   @access public
      *   @return array string[]
      */
    public function getFillerText();

    /**
      *  Fetch Hexdecimal alphabet 
      * 
      *  @access public
      *  @return \Faker\Text\SimpleTextInterface
      */
    public function getHex();
    

    /**
      *  Class Constructor
      *
      *  @access public
      *  @param StringFactoryInterface $factory
      *  @return void
      */
    public function __construct(StringFactoryInterface $factory)
    {
        $this->string_factory = $factory;
    }


}
/* End of File */

To register with factory. Open the bootstrap file under project/extension/bootstrap.php and scroll down to the section shown below.

<?php
/*
|--------------------------------------------------------------------------
| Faker Locales
|--------------------------------------------------------------------------
|
| Register a new Locale, which provide locale specific text to the generators.
|
| LocaleFactory::registerExtension('xxx','Faker\\Components\\Extension\\Locale\\XXXXLocale');
|
*/ 

Random Generators

A generator makes pseudo-random numbers PHP includes 2 pseudo-random number generators rand() and mt_rand(). Faker allows multiple generators to be included inside a schema. A default can be set on schema , table and column each datatype can have their own generator too.

Pseudo-random random number generators are seeded with an initial value by running two generators that use the same algorithm with the same seed will will identical values hence pseudo-random.

If you modify a schema and are careful and keep same seed values your tests are less likely to break.

I found that when the Soushin security extension is installed (many repo installs it comes by default) the generators seeded by the extension and can not be changed. I have included a replacement that implements the Mersenne Twiseter algorithm and recommend its use if Soushin is installed

I have include 3 Generators that can be used

1. SimpleRandom Fast but has bad spread of random values, but will accept a seed.

<column name="a_column" generatorSeed="100" randomGenerator="simple" />
$oRandomGenerator = $oProject->getRandomGeneratorFactory()->create('simple',100);
$oTableBuilder->defaultRandom($oRandomGenerator);

2. SrandRandom If you don't care and want to use php random it will accept a seed but if Soushin is installed it won't matter.

<column name="a_column" generatorSeed="100" randomGenerator="srand" />
$oRandomGenerator = $oProject->getRandomGeneratorFactory()->create('srand',100);
$oTableBuilder->defaultRandom($oRandomGenerator);

3. MersenneRandom Will accept a seed and good spread of random values and not affected by Soushin Extension

<column name="a_column" generatorSeed="100" randomGenerator="mersenne" />
$oRandomGenerator = $oProject->getRandomGeneratorFactory()->create('mersenne',100);
$oTableBuilder->defaultRandom($oRandomGenerator);

Database connections

Database connections are used to both write and query data from existing databases.

Adding a new connection can be done by adding a config into the database config file under config/default.php, each connection is an array for example a mysql connection.

array (
    'type' => 'pdo_mysql',
    'schema' => 'myschema',
    'user' => 'root',
    'password' => 'rootpassword',
    'host' => 'localhost',
    'port' => 3306,
    'socket' => false,
    'path' => NULL,
    'memory' => NULL,
    'charset' => false,
    'connectionName' => 'DEVD',
  )

Each connection requires a unique name in the above the 'connectionName' is DEVD. This database connection can be referened in writers and datasources by that name.

To create the config file you can run the faker:config command.

Writers (Formatters)

Writters lisen to content created by the generator and will push to ouput database or write a output file in the chosen format.

Faker currently has two built in Writers.

  1. SQLFormatter
  2. PHPUnitFormatter.

SQLFormatter

This formatter can write output to a series of files in SQL format to write each statement to a database defined in your config file.

Using the FluientEngine the formatter supports the following options.

public function writeToDatabase($connName);
public function singleFileMode();
public function maxLines($lines);
public function splitOnNewTable($yes = true);
public function outputEncoding($method);
public function outFileFormat($format);
public function usePlatform($name);

If writeToDatase is set the formatter will write the sql statement to the database specified. The $connName is the value given to the 'connectionName' param in the config.php file. If you use this option you should ensure that the value given to usePlatform matches the target database.

The value given to usePlatform is the short name of the platform registred with the PlatformFactory. Current mapped platforms include.

array(
   'db2'           => 'Doctrine\\DBAL\\Platforms\\DB2Platform',
   'mysql'         => 'Doctrine\\DBAL\\Platforms\\MySqlPlatform',
   'oracle'        => 'Doctrine\\DBAL\\Platforms\\OraclePlatform',
   'postgresql'    => 'Doctrine\\DBAL\\Platforms\\PostgreSqlPlatform',
   'sqlite'        => 'Doctrine\\DBAL\\Platforms\\SqlitePlatform',
   'sqlserver2005' => 'Doctrine\\DBAL\\Platforms\\SQLServer2005Platform',
   'sqlserver2008' => 'Doctrine\\DBAL\\Platforms\\SQLServer2008Platform',
   'sqlserver'     => 'Doctrine\\DBAL\\Platforms\\SQLServerPlatform'
);

You can write your own plaforms and register them with the factory in the extension/bootstrap.php file.

The value passed to outputEncoding should be a supported value for 'mb_convert_encoding'.

The value for outFileFormat determines the name of the output file, the following options are supported {prefix},{body},{suffix},{ext}. For example the fromat '{prefix}{body}{suffix}.{ext}' will render a name like '1_schemaname_tablename_mysql.sql'. This param is not used if your writing to a database.

By default when a new table is reached the current file will be closed and a new one started setting splitOnNewTable to false will keep the writer running.

To avoid oversised sql files this formtter will generate x number of statements changing maxLines will move this split to ealier to later. Though if singleFileMode is enabled this option is ignored.

To generate the entire schema in a single file enable the singleFileMode option, this is used in PHPUnitFormatter.

Using XMLEngine:

<writer platform="mysql" format="sql" singleFileMode="true" maxLines="500" splitOnTable="false" outFileFormat="{prefix}_{body}_{suffix}.{ext}" outEncoding="utf-8" />

Using FluentEngine:

$schemaBuilder->addWriter()
                    ->sqlWriter()
                        ->maxLines(100)
                        ->outputEncoding('utf8')
                        ->outFileFormat('{prefix}_{body}_{suffix}.{ext}')
                    ->end()
              ->end()

PHPUnitFormatter.

This Writer will produce an xml file that is compatible with PHPUnit DbUnit extension. This writer by default produces a single file with an xml extension.

Using XMLEngine:

<schema>
   <writer platform="mysql" format="phpunit" outFileFormat="{prefix}_{body}_{suffix}.{ext}" />
</schema>

Using FluentEngine:

$schemaBuilder->addWriter()
                    ->phpUnitWriter()
                        ->outputEncoding('utf8')
                        ->outFileFormat('{prefix}_{body}_{suffix}.{ext}')
                    ->end()
              ->end()

Datasources

Accessing Existing data is done through creating a datasource, faker provides both generic data source and SQL sources. Using the Generic source allows you to embed values or load values externally.

Datasources are currently only implemented using the FluientEngine.

###Generic Datasource To use the generic datasource interface you may use a closure or implement the interface in a extension class.

Method 1 Using A closure

$schemaBuilder->addDatasource()
                    ->createPHPSource()
                         ->setDataFromClosure(function(){
                             return new \ArrayIterator(array('a','b','c'));
                         })
                         ->setDatasourceName('examplesourceA')
                    ->end()
                ->end();

The Closure must return an Iterator and each source must have a unique name.

**Method 2 Using Custom Class **

DataTypes

Distributions

Engines XML,PHP,Entity,Seed

Generator Composite

Builder Build events

Seed Classes

Writing your own Datatypes

Writing your own DBAL Column Types