Populator.php
110 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Faker\ORM\CakePHP; |
| 4 | |
| 5 | class Populator |
| 6 | { |
| 7 | |
| 8 | protected $generator; |
| 9 | protected $entities = []; |
| 10 | protected $quantities = []; |
| 11 | protected $guessers = []; |
| 12 | |
| 13 | /** |
| 14 | * @param \Faker\Generator $generator |
| 15 | */ |
| 16 | public function __construct(\Faker\Generator $generator) |
| 17 | { |
| 18 | $this->generator = $generator; |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * @return \Faker\Generator |
| 23 | */ |
| 24 | public function getGenerator() |
| 25 | { |
| 26 | return $this->generator; |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * @return array |
| 31 | */ |
| 32 | public function getGuessers() |
| 33 | { |
| 34 | return $this->guessers; |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * @return $this |
| 39 | */ |
| 40 | public function removeGuesser($name) |
| 41 | { |
| 42 | if ($this->guessers[$name]) { |
| 43 | unset($this->guessers[$name]); |
| 44 | } |
| 45 | return $this; |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * @return $this |
| 50 | * @throws \Exception |
| 51 | */ |
| 52 | public function addGuesser($class) |
| 53 | { |
| 54 | if (!is_object($class)) { |
| 55 | $class = new $class($this->generator); |
| 56 | } |
| 57 | |
| 58 | if (!method_exists($class, 'guessFormat')) { |
| 59 | throw new \Exception('Missing required custom guesser method: ' . get_class($class) . '::guessFormat()'); |
| 60 | } |
| 61 | |
| 62 | $this->guessers[get_class($class)] = $class; |
| 63 | return $this; |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * @param array $customColumnFormatters |
| 68 | * @param array $customModifiers |
| 69 | * @return $this |
| 70 | */ |
| 71 | public function addEntity($entity, $number, $customColumnFormatters = [], $customModifiers = []) |
| 72 | { |
| 73 | if (!$entity instanceof EntityPopulator) { |
| 74 | $entity = new EntityPopulator($entity); |
| 75 | } |
| 76 | |
| 77 | $entity->columnFormatters = $entity->guessColumnFormatters($this); |
| 78 | if ($customColumnFormatters) { |
| 79 | $entity->mergeColumnFormattersWith($customColumnFormatters); |
| 80 | } |
| 81 | |
| 82 | $entity->modifiers = $entity->guessModifiers($this); |
| 83 | if ($customModifiers) { |
| 84 | $entity->mergeModifiersWith($customModifiers); |
| 85 | } |
| 86 | |
| 87 | $class = $entity->class; |
| 88 | $this->entities[$class] = $entity; |
| 89 | $this->quantities[$class] = $number; |
| 90 | return $this; |
| 91 | } |
| 92 | |
| 93 | /** |
| 94 | * @param array $options |
| 95 | * @return array |
| 96 | */ |
| 97 | public function execute($options = []) |
| 98 | { |
| 99 | $insertedEntities = []; |
| 100 | |
| 101 | foreach ($this->quantities as $class => $number) { |
| 102 | for ($i = 0; $i < $number; $i++) { |
| 103 | $insertedEntities[$class][] = $this->entities[$class]->execute($class, $insertedEntities, $options); |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | return $insertedEntities; |
| 108 | } |
| 109 | } |
| 110 |