Skip to content
This repository has been archived by the owner on Dec 11, 2020. It is now read-only.

Add Spot ORM #796

Merged
merged 1 commit into from
Feb 1, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ You can check available Faker locales in the source code, [under the `Provider`

## Populating Entities Using an ORM or an ODM

Faker provides adapters for Object-Relational and Object-Document Mappers (currently, [Propel](http://www.propelorm.org), [Doctrine2](http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/), [CakePHP](http://cakephp.org) and [Mandango](https://github.com/mandango/mandango) are supported). These adapters ease the population of databases through the Entity classes provided by an ORM library (or the population of document stores using Document classes provided by an ODM library).
Faker provides adapters for Object-Relational and Object-Document Mappers (currently, [Propel](http://www.propelorm.org), [Doctrine2](http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/), [CakePHP](http://cakephp.org), [Spot2](https://github.com/vlucas/spot2) and [Mandango](https://github.com/mandango/mandango) are supported). These adapters ease the population of databases through the Entity classes provided by an ORM library (or the population of document stores using Document classes provided by an ODM library).

To populate entities, create a new populator class (using a generator instance as parameter), then list the class and number of all the entities that must be generated. To launch the actual data population, call the `execute()` method.

Expand Down
77 changes: 77 additions & 0 deletions src/Faker/ORM/Spot/ColumnTypeGuesser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

namespace Faker\ORM\Spot;

use Faker\Generator;

class ColumnTypeGuesser
{
protected $generator;


/**
* ColumnTypeGuesser constructor.
* @param Generator $generator
*/
public function __construct(Generator $generator)
{
$this->generator = $generator;
}

/**
* @param array $field
* @return \Closure|null
*/
public function guessFormat(array $field)
{
$generator = $this->generator;
$type = $field['type'];
switch ($type) {
case 'boolean':
return function () use ($generator) {
return $generator->boolean;
};
case 'decimal':
$size = isset($field['precision']) ? $field['precision'] : 2;

return function () use ($generator, $size) {
return $generator->randomNumber($size + 2) / 100;
};
case 'smallint':
return function () {
return mt_rand(0, 65535);
};
case 'integer':
return function () {
return mt_rand(0, intval('2147483647'));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why don't you use $generator->numberBetween() here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copied it from Doctrine column type guesser. Will fix both today.

I think $generator->randomNumber(10); is even more correct solution here...

};
case 'bigint':
return function () {
return mt_rand(0, intval('18446744073709551615'));
};
case 'float':
return function () {
return mt_rand(0, intval('4294967295'))/mt_rand(1, intval('4294967295'));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$generator->randomFloat(). In fact I am not entirely sure whether your current method generates a uniform distribution (I suspect not).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above. Thanks for noticing!

};
case 'string':
$size = isset($field['length']) ? $field['length'] : 255;

return function () use ($generator, $size) {
return $generator->text($size);
};
case 'text':
return function () use ($generator) {
return $generator->text;
};
case 'datetime':
case 'date':
case 'time':
return function () use ($generator) {
return $generator->datetime;
};
default:
// no smart way to guess what the user expects here
return null;
}
}
}
222 changes: 222 additions & 0 deletions src/Faker/ORM/Spot/EntityPopulator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
<?php

namespace Faker\ORM\Spot;

use Faker\Generator;
use Faker\Guesser\Name;
use Spot\Locator;
use Spot\Mapper;
use Spot\Relation\BelongsTo;

/**
* Service class for populating a table through a Spot Entity class.
*/
class EntityPopulator
{
/**
* When fetching existing data - fetch only few first rows.
*/
const RELATED_FETCH_COUNT = 10;

/**
* @var Mapper
*/
protected $mapper;

/**
* @var Locator
*/
protected $locator;

/**
* @var array
*/
protected $columnFormatters = array();
/**
* @var array
*/
protected $modifiers = array();

/**
* @var bool
*/
protected $useExistingData = false;

/**
* Class constructor.
*
* @param Mapper $mapper
* @param Locator $locator
* @param $useExistingData
*/
public function __construct(Mapper $mapper, Locator $locator, $useExistingData = false)
{
$this->mapper = $mapper;
$this->locator = $locator;
$this->useExistingData = $useExistingData;
}

/**
* @return string
*/
public function getMapper()
{
return $this->mapper;
}

/**
* @param $columnFormatters
*/
public function setColumnFormatters($columnFormatters)
{
$this->columnFormatters = $columnFormatters;
}

/**
* @return array
*/
public function getColumnFormatters()
{
return $this->columnFormatters;
}

/**
* @param $columnFormatters
*/
public function mergeColumnFormattersWith($columnFormatters)
{
$this->columnFormatters = array_merge($this->columnFormatters, $columnFormatters);
}

/**
* @param array $modifiers
*/
public function setModifiers(array $modifiers)
{
$this->modifiers = $modifiers;
}

/**
* @return array
*/
public function getModifiers()
{
return $this->modifiers;
}

/**
* @param array $modifiers
*/
public function mergeModifiersWith(array $modifiers)
{
$this->modifiers = array_merge($this->modifiers, $modifiers);
}

/**
* @param Generator $generator
* @return array
*/
public function guessColumnFormatters(Generator $generator)
{
$formatters = array();
$nameGuesser = new Name($generator);
$columnTypeGuesser = new ColumnTypeGuesser($generator);
$fields = $this->mapper->fields();
foreach ($fields as $fieldName => $field) {
if ($field['primary'] == true) {
continue;
}
if ($formatter = $nameGuesser->guessFormat($fieldName)) {
$formatters[$fieldName] = $formatter;
continue;
}
if ($formatter = $columnTypeGuesser->guessFormat($field)) {
$formatters[$fieldName] = $formatter;
continue;
}
}
$entityName = $this->mapper->entity();
$entity = $this->mapper->build([]);
$relations = $entityName::relations($this->mapper, $entity);
foreach ($relations as $relation) {
// We don't need any other relation here.
if ($relation instanceof BelongsTo) {

$fieldName = $relation->localKey();
$entityName = $relation->entityName();
$field = $fields[$fieldName];
$required = $field['required'];

$locator = $this->locator;

$formatters[$fieldName] = function ($inserted) use ($required, $entityName, $locator) {
if (!empty($inserted[$entityName])) {
return $inserted[$entityName][mt_rand(0, count($inserted[$entityName]) - 1)]->getId();
} else {
if ($required && $this->useExistingData) {
// We did not add anything like this, but it's required,
// So let's find something existing in DB.
$mapper = $this->locator->mapper($entityName);
$records = $mapper->all()->limit(self::RELATED_FETCH_COUNT)->toArray();
if (empty($records)) {
return null;
}
$id = $records[mt_rand(0, count($records) - 1)]['id'];

return $id;
} else {
return null;
}
}
};

}
}

return $formatters;
}

/**
* Insert one new record using the Entity class.
*
* @param $insertedEntities
* @return string
*/
public function execute($insertedEntities)
{
$obj = $this->mapper->build([]);

$this->fillColumns($obj, $insertedEntities);
$this->callMethods($obj, $insertedEntities);

$this->mapper->insert($obj);


return $obj;
}

/**
* @param $obj
* @param $insertedEntities
*/
private function fillColumns($obj, $insertedEntities)
{
foreach ($this->columnFormatters as $field => $format) {
if (null !== $format) {
$value = is_callable($format) ? $format($insertedEntities, $obj) : $format;
$obj->set($field, $value);
}
}
}

/**
* @param $obj
* @param $insertedEntities
*/
private function callMethods($obj, $insertedEntities)
{
foreach ($this->getModifiers() as $modifier) {
$modifier($obj, $insertedEntities);
}
}
}
88 changes: 88 additions & 0 deletions src/Faker/ORM/Spot/Populator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php


namespace Faker\ORM\Spot;

use Spot\Locator;

/**
* Service class for populating a database using the Spot ORM.
*/
class Populator
{
protected $generator;
protected $locator;
protected $entities = array();
protected $quantities = array();

/**
* Populator constructor.
* @param \Faker\Generator $generator
* @param Locator|null $locator
*/
public function __construct(\Faker\Generator $generator, Locator $locator = null)
{
$this->generator = $generator;
$this->locator = $locator;
}

/**
* Add an order for the generation of $number records for $entity.
*
* @param $entityName string Name of Entity object to generate
* @param $number int The number of entities to populate
* @param $customColumnFormatters array
* @param $customModifiers array
* @param $useExistingData bool Should we use existing rows (e.g. roles) to populate relations?
*/
public function addEntity(
$entityName,
$number,
$customColumnFormatters = array(),
$customModifiers = array(),
$useExistingData = false
) {
$mapper = $this->locator->mapper($entityName);
if (null === $mapper) {
throw new \InvalidArgumentException("No mapper can be found for entity " . $entityName);
}
$entity = new EntityPopulator($mapper, $this->locator, $useExistingData);

$entity->setColumnFormatters($entity->guessColumnFormatters($this->generator));
if ($customColumnFormatters) {
$entity->mergeColumnFormattersWith($customColumnFormatters);
}
$entity->mergeModifiersWith($customModifiers);

$this->entities[$entityName] = $entity;
$this->quantities[$entityName] = $number;
}

/**
* Populate the database using all the Entity classes previously added.
*
* @param Locator $locator A Spot locator
*
* @return array A list of the inserted PKs
*/
public function execute($locator = null)
{
if (null === $locator) {
$locator = $this->locator;
}
if (null === $locator) {
throw new \InvalidArgumentException("No entity manager passed to Spot Populator.");
}

$insertedEntities = array();
foreach ($this->quantities as $entityName => $number) {
for ($i = 0; $i < $number; $i++) {
$insertedEntities[$entityName][] = $this->entities[$entityName]->execute(
$insertedEntities
);
}
}

return $insertedEntities;
}
}