Commit 359ae98f by Qiang Xue

Fixes #4622: Simplified the way of creating a Faker fixture template file

parent ad20aa4b
<?php
/**
* @var $faker \Faker\Generator
* @var $index integer
*/
return [
'username' => 'userName',
'auth_key' => function ($fixture, $faker, $index) {
$fixture['auth_key'] = Yii::$app->getSecurity()->generateRandomString();
return $fixture;
},
'password_hash' => function ($fixture, $faker, $index) {
$fixture['password_hash'] = Yii::$app->getSecurity()->generatePasswordHash('password_' . $index);
return $fixture;
},
'password_reset_token' => function ($fixture, $faker, $index) {
$fixture['password_reset_token'] = Yii::$app->getSecurity()->generateRandomString() . '_' . time();
$security = Yii::$app->getSecurity();
return $fixture;
},
'created_at' => function ($fixture, $faker, $index) {
$fixture['created_at'] = time();
return $fixture;
},
'updated_at' => function ($fixture, $faker, $index) {
$fixture['updated_at'] = time();
return $fixture;
},
'email' => 'email',
return [
'username' => $faker->userName,
'email' => $faker->email,
'auth_key' => $security->generateRandomString(),
'password_hash' => $security->generatePasswordHash('password_' . $index),
'password_reset_token' => $security->generateRandomString() . '_' . time(),
'created_at' => time(),
'updated_at' => time(),
];
<?php
return [
[
[
'username' => 'bayer.hudson',
'auth_key' => 'HP187Mvq7Mmm3CTU80dLkGmni_FUH_lR',
//password_0
......@@ -10,5 +10,5 @@ return [
'created_at' => '1402312317',
'updated_at' => '1402312317',
'email' => 'nicole.paucek@schultz.info',
],
],
];
......@@ -4,10 +4,10 @@ Yii Framework 2 faker extension Change Log
2.0.0-rc under development
--------------------------
- no changes in this release.
- Chg #4622: Simplified the way of creating a Faker fixture template file (qiangxue)
2.0.0-beta April 13, 2014
-------------------------
- Initial release.
\ No newline at end of file
- Initial release.
......@@ -230,11 +230,10 @@ class FixtureController extends \yii\console\controllers\FixtureController
foreach ($files as $templateFile) {
$fixtureFileName = basename($templateFile);
$template = $this->getTemplate($templateFile);
$fixtures = [];
for ($i = 0; $i < $times; $i++) {
$fixtures[$i] = $this->generateFixture($template, $i);
$fixtures[$i] = $this->generateFixture($templateFile, $i);
}
$content = $this->exportFixtures($fixtures);
......@@ -294,23 +293,6 @@ class FixtureController extends \yii\console\controllers\FixtureController
}
/**
* Returns generator template for the given fixture name
* @param string $file template file
* @return array generator template
* @throws \yii\console\Exception if wrong file format
*/
public function getTemplate($file)
{
$template = require($file);
if (!is_array($template)) {
throw new Exception("The template file \"$file\" has wrong format. It should return valid template array");
}
return $template;
}
/**
* Returns exported to the string representation of given fixtures array.
* @param array $fixtures
* @return string exported fixtures format
......@@ -322,23 +304,15 @@ class FixtureController extends \yii\console\controllers\FixtureController
/**
* Generates fixture from given template
* @param array $template fixture template
* @param integer $index current fixture index
* @param string $_template_ the fixture template file
* @param integer $index the current fixture index
* @return array fixture
*/
public function generateFixture($template, $index)
public function generateFixture($_template_, $index)
{
$fixture = [];
foreach ($template as $attribute => $fakerProperty) {
if (!is_string($fakerProperty)) {
$fixture = call_user_func_array($fakerProperty, [$fixture, $this->generator, $index]);
} else {
$fixture[$attribute] = $this->generator->$fakerProperty;
}
}
return $fixture;
// $faker and $index are exposed to the template file
$faker = $this->generator;
return require($_template_);
}
/**
......
......@@ -36,64 +36,46 @@ To use this extension, simply add the following code in your application config
],
],
```
Set valid ```test``` alias in your console config, for example for ```basic``` application template, this should be added
to ```console.php``` config: ```Yii::setAlias('tests', __DIR__ . '/../tests');```
To start using this command you need to be familiar (read guide) for the [Faker](https://github.com/fzaninotto/Faker) library and
generate fixtures template files, according to the given format:
Define a `tests` alias in your console config. For example, for the `basic` application template, this should be added
to the `console.php` configuration: `Yii::setAlias('tests', __DIR__ . '/../tests');`
To start using this command you need to be familiar (read guide) with the [Faker](https://github.com/fzaninotto/Faker) library and
generate fixture template files, according to the given format:
```php
//users.php file under template path (by default @tests/unit/templates/fixtures)
// users.php file under template path (by default @tests/unit/templates/fixtures)
/**
* @var $faker \Faker\Generator
* @var $index integer
*/
return [
[
'table_column0' => 'faker_formatter',
...
'table_columnN' => 'other_faker_formatter'
'body' => function ($fixture, $faker, $index) {
//set needed fixture fields based on different conditions
$fixture['body'] = $faker->sentence(7,true); //generate sentence exact with 7 words.
return $fixture;
}
],
'name' => $faker->firstName,
'phone' => $faker->phoneNumber,
'city' => $faker->city,
'password' => Yii::$app->getSecurity()->generatePasswordHash('password_' . $index),
'auth_key' => Yii::$app->getSecurity()->generateRandomString(),
'intro' => $faker->sentence(7, true), // generate a sentence with 7 words
];
```
If you use callback as a attribute value, then it will be called as shown with three parameters:
As you can see, the template file is just a regular PHP script. The script should return an array of key-value
pairs, where the keys represent the table column names and the values the corresponding value. When you run
the `fixture/generate` command, the script will be executed once for every data row being generated.
In this script, you can use the following two predefined variables:
* ```$fixture``` - current fixture array.
* ```$faker``` - faker generator instance
* ```$index``` - current fixture index. For example if user need to generate 3 fixtures for user table, it will be 0..2.
* `$faker`: the Faker generator instance
* `$index`: the current fixture index. For example if user need to generate 3 fixtures for user table, it will be 0..2.
After you set all needed fields in callback, you need to return $fixture array back from the callback.
With such a template file, you can generate your fixtures using the commands like the following:
Another example of valid template:
```php
return [
'name' => 'firstName',
'phone' => 'phoneNumber',
'city' => 'city',
'password' => function ($fixture, $faker, $index) {
$fixture['password'] = Yii::$app->getSecurity()->generatePasswordHash('password_' . $index);
return $fixture;
},
'auth_key' => function ($fixture, $faker, $index) {
$fixture['auth_key'] = Yii::$app->getSecurity()->generateRandomString();
return $fixture;
},
];
```
After you prepared needed templates for tables you can simply generate your fixtures via command
```php
//generate fixtures for the users table based on users fixture template
# generate fixtures for the users table based on users fixture template
php yii fixture/generate users
//also a short version of this command ("generate" action is default)
# also a short version of this command ("generate" action is default)
php yii fixture users
//to generate several fixtures data files, use "," as a separator, for example:
# to generate several fixtures data files, use "," as a separator, for example:
php yii fixture users,profile,some_other_name
```
......@@ -102,7 +84,7 @@ will be created under the fixtures path (by default ```@tests/unit/fixtures```)
You can generate fixtures for all templates by specifying keyword ```all```. You dont need to worry about if data file
directory already created or not, if not - it will be created by these command.
```php
```
php yii fixture/generate all
```
......@@ -111,19 +93,19 @@ store fixtures under fixtures path with file names same as templates names.
You can specify how many fixtures per file you need by the second parameter. In the code below we generate
all fixtures and in each file there will be 3 rows (fixtures).
```php
```
php yii fixture/generate all 3
```
You can specify different options of this command:
```php
//generate fixtures in russian language
```
# generate fixtures in russian language
php yii fixture/generate users 5 --language='ru_RU'
//read templates from the other path
# read templates from the other path
php yii fixture/generate all --templatePath='@app/path/to/my/custom/templates'
//generate fixtures into other directory.
# generate fixtures into other directory.
php yii fixture/generate all --fixtureDataPath='@tests/acceptance/fixtures/data'
```
......@@ -147,7 +129,7 @@ class Book extends \Faker\Provider\Base
}
```
You can use it by adding it to the ```$providers``` property of the current command. In your console.php config:
You can use it by adding it to the `$providers` property of the current command. In your console.php config:
```php
'controllerMap' => [
......
......@@ -485,6 +485,7 @@ Yii Framework 2 Change Log
- Chg #2955: Changed the signature of ActiveQuery constructors and replaced `ActiveRecord::createQuery()` with `find()` to simplify customizing ActiveQuery classes (qiangxue)
- Chg #2999: Added `findOne()` and `findAll()` to replace the usage of `ActiveRecord::find($condition)`. (samdark, qiangxue)
- Chg #4204: `yii\web\Request::getUserIP()` will return null if it cannot detect user IP address (qiangxue)
- Chg #4622: Simplified the way of creating a Faker fixture template file (qiangxue)
- Chg: Renamed `yii\jui\Widget::clientEventsMap` to `clientEventMap` (qiangxue)
- Chg: Renamed `ActiveRecord::getPopulatedRelations()` to `getRelatedRecords()` (qiangxue)
- Chg: Renamed `attributeName` and `className` to `targetAttribute` and `targetClass` for `UniqueValidator` and `ExistValidator` (qiangxue)
......
......@@ -181,7 +181,7 @@ new ones save the following code as `convert.php` that should be placed in the s
will return `images/logo.png` directly. If you want a relative URL to be prefix with base URL, you should make use
of the alias `@web`. For example, `Url::to('@web/images/logo.png')` will return `/BaseUrl/images/logo.png`.
- The following properties are now taking `false` instead of `null` for "don't use" case:
* The following properties are now taking `false` instead of `null` for "don't use" case:
- `yii\bootstrap\NavBar::$brandLabel`.
- `yii\bootstrap\NavBar::$brandUrl`.
- `yii\bootstrap\Modal::$closeButton`.
......@@ -191,3 +191,6 @@ new ones save the following code as `convert.php` that should be placed in the s
- `yii\widgets\LinkPager::$prevPageLabel`.
- `yii\widgets\LinkPager::$firstPageLabel`.
- `yii\widgets\LinkPager::$lastPageLabel`.
* The format of the Faker fixture template is changed. For an example, please refer to the file
`apps/advanced/common/tests/templates/fixtures/user.php`.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment