| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
namespace Faker\ORM\Mandango;
|
|
|
4 |
|
|
|
5 |
use Mandango\Mandango;
|
|
|
6 |
|
|
|
7 |
/**
|
|
|
8 |
* Service class for populating a database using Mandango.
|
|
|
9 |
* A Populator can populate several tables using ActiveRecord classes.
|
|
|
10 |
*/
|
|
|
11 |
class Populator
|
|
|
12 |
{
|
|
|
13 |
protected $generator;
|
|
|
14 |
protected $mandango;
|
|
|
15 |
protected $entities = [];
|
|
|
16 |
protected $quantities = [];
|
|
|
17 |
|
|
|
18 |
public function __construct(\Faker\Generator $generator, Mandango $mandango)
|
|
|
19 |
{
|
|
|
20 |
$this->generator = $generator;
|
|
|
21 |
$this->mandango = $mandango;
|
|
|
22 |
}
|
|
|
23 |
|
|
|
24 |
/**
|
|
|
25 |
* Add an order for the generation of $number records for $entity.
|
|
|
26 |
*
|
|
|
27 |
* @param mixed $entity A Propel ActiveRecord classname, or a \Faker\ORM\Propel\EntityPopulator instance
|
|
|
28 |
* @param int $number The number of entities to populate
|
|
|
29 |
*/
|
|
|
30 |
public function addEntity($entity, $number, $customColumnFormatters = [])
|
|
|
31 |
{
|
|
|
32 |
if (!$entity instanceof \Faker\ORM\Mandango\EntityPopulator) {
|
|
|
33 |
$entity = new \Faker\ORM\Mandango\EntityPopulator($entity);
|
|
|
34 |
}
|
|
|
35 |
$entity->setColumnFormatters($entity->guessColumnFormatters($this->generator, $this->mandango));
|
|
|
36 |
|
|
|
37 |
if ($customColumnFormatters) {
|
|
|
38 |
$entity->mergeColumnFormattersWith($customColumnFormatters);
|
|
|
39 |
}
|
|
|
40 |
$class = $entity->getClass();
|
|
|
41 |
$this->entities[$class] = $entity;
|
|
|
42 |
$this->quantities[$class] = $number;
|
|
|
43 |
}
|
|
|
44 |
|
|
|
45 |
/**
|
|
|
46 |
* Populate the database using all the Entity classes previously added.
|
|
|
47 |
*
|
|
|
48 |
* @return array A list of the inserted entities.
|
|
|
49 |
*/
|
|
|
50 |
public function execute()
|
|
|
51 |
{
|
|
|
52 |
$insertedEntities = [];
|
|
|
53 |
|
|
|
54 |
foreach ($this->quantities as $class => $number) {
|
|
|
55 |
for ($i = 0; $i < $number; ++$i) {
|
|
|
56 |
$insertedEntities[$class][] = $this->entities[$class]->execute($this->mandango, $insertedEntities);
|
|
|
57 |
}
|
|
|
58 |
}
|
|
|
59 |
$this->mandango->flush();
|
|
|
60 |
|
|
|
61 |
return $insertedEntities;
|
|
|
62 |
}
|
|
|
63 |
}
|