CodeIgniter4/system/Test/Fabricator.php

645 lines
14 KiB
PHP
Raw Normal View History

2020-05-05 19:50:06 +00:00
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014-2019 British Columbia Institute of Technology
* Copyright (c) 2019-2020 CodeIgniter Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author CodeIgniter Dev Team
* @copyright 2019-2020 CodeIgniter Foundation
* @license https://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 4.0.0
* @filesource
*/
namespace CodeIgniter\Test;
use CodeIgniter\Model;
use Faker\Factory;
use Faker\Generator;
2020-10-04 00:27:56 +07:00
use InvalidArgumentException;
use RuntimeException;
2020-05-05 19:50:06 +00:00
/**
* Fabricator
*
* Bridge class for using Faker to create example data based on
* model specifications.
*/
class Fabricator
{
2020-07-03 18:54:17 +00:00
/**
* Array of counts for fabricated items
*
* @var array
*/
protected static $tableCounts = [];
2020-05-05 19:50:06 +00:00
/**
* Locale-specific Faker instance
*
2020-08-18 22:16:06 +07:00
* @var Generator
2020-05-05 19:50:06 +00:00
*/
protected $faker;
/**
* Model instance (can be non-framework if it follows framework design)
2020-05-05 19:50:06 +00:00
*
* @var CodeIgniter\Model|object
2020-05-05 19:50:06 +00:00
*/
protected $model;
2020-05-06 20:02:17 +00:00
/**
* Locale used to initialize Faker
*
* @var string
*/
protected $locale;
2020-05-05 19:50:06 +00:00
/**
* Map of properties and their formatter to use
*
2020-08-21 01:15:30 +07:00
* @var array|null
2020-05-05 19:50:06 +00:00
*/
protected $formatters;
/**
* Date fields present in the model
*
* @var array
*/
protected $dateFields = [];
2020-05-07 19:39:46 +00:00
/**
* Array of data to add or override faked versions
*
* @var array
*/
protected $overrides = [];
/**
* Array of single-use data to override faked versions
*
* @var array|null
*/
2020-05-16 16:24:33 +00:00
protected $tempOverrides;
2020-05-07 19:39:46 +00:00
2020-05-05 19:50:06 +00:00
/**
* Default formatter to use when nothing is detected
*
* @var string
*/
public $defaultFormatter = 'word';
//--------------------------------------------------------------------
/**
* Store the model instance and initialize Faker to the locale.
*
* @param string|object $model Instance or classname of the model to use
* @param array|null $formatters Array of property => formatter
* @param string|null $locale Locale for Faker provider
2020-05-05 19:50:06 +00:00
*
2020-10-04 00:27:56 +07:00
* @throws InvalidArgumentException
2020-05-05 19:50:06 +00:00
*/
2020-05-06 20:02:17 +00:00
public function __construct($model, array $formatters = null, string $locale = null)
2020-05-05 19:50:06 +00:00
{
if (is_string($model))
{
// Create a new model instance
$model = model($model, false);
2020-05-05 19:50:06 +00:00
}
2020-07-08 19:58:13 +00:00
if (! is_object($model))
{
2020-10-04 00:27:56 +07:00
throw new InvalidArgumentException(lang('Fabricator.invalidModel'));
2020-07-08 19:58:13 +00:00
}
2020-05-06 20:02:17 +00:00
$this->model = $model;
2020-05-05 19:50:06 +00:00
// If no locale was specified then use the App default
if (is_null($locale))
{
$locale = config('App')->defaultLocale;
}
2020-05-06 20:02:17 +00:00
// There is no easy way to retrieve the locale from Faker so we will store it
$this->locale = $locale;
// Create the locale-specific Generator
$this->faker = Factory::create($this->locale);
2020-05-05 19:50:06 +00:00
// Determine eligible date fields
foreach (['createdField', 'updatedField', 'deletedField'] as $field)
{
if (! empty($this->model->$field))
{
$this->dateFields[] = $this->model->$field;
}
}
2020-05-05 19:50:06 +00:00
// Set the formatters
$this->setFormatters($formatters);
}
2020-07-03 18:54:17 +00:00
//--------------------------------------------------------------------
/**
* Reset internal counts
*/
public static function resetCounts()
{
self::$tableCounts = [];
}
2020-05-07 19:39:46 +00:00
/**
2020-07-03 18:54:17 +00:00
* Get the count for a specific table
2020-05-07 19:39:46 +00:00
*
2020-07-03 18:54:17 +00:00
* @param string $table Name of the target table
*
* @return integer
*/
public static function getCount(string $table): int
{
return empty(self::$tableCounts[$table]) ? 0 : self::$tableCounts[$table];
}
/**
* Set the count for a specific table
*
* @param string $table Name of the target table
* @param integer $count Count value
*
* @return integer The new count value
2020-05-07 19:39:46 +00:00
*/
2020-07-03 18:54:17 +00:00
public static function setCount(string $table, int $count): int
2020-05-07 19:39:46 +00:00
{
2020-07-03 18:54:17 +00:00
self::$tableCounts[$table] = $count;
return $count;
}
2020-05-07 19:39:46 +00:00
2020-07-03 18:54:17 +00:00
/**
* Increment the count for a table
*
* @param string $table Name of the target table
*
* @return integer The new count value
*/
public static function upCount(string $table): int
{
return self::setCount($table, self::getCount($table) + 1);
}
2020-05-07 19:39:46 +00:00
2020-07-03 18:54:17 +00:00
/**
* Decrement the count for a table
*
* @param string $table Name of the target table
*
* @return integer The new count value
*/
public static function downCount(string $table): int
{
return self::setCount($table, self::getCount($table) - 1);
2020-05-07 19:39:46 +00:00
}
2020-05-05 19:50:06 +00:00
//--------------------------------------------------------------------
/**
* Returns the model instance
*
* @return object Framework or compatible model
2020-05-05 19:50:06 +00:00
*/
public function getModel()
2020-05-05 19:50:06 +00:00
{
return $this->model;
}
2020-05-06 20:02:17 +00:00
/**
* Returns the locale
*
* @return string
*/
public function getLocale(): string
{
return $this->locale;
}
2020-05-05 19:50:06 +00:00
/**
* Returns the Faker generator
*
2020-08-18 22:16:06 +07:00
* @return Generator
2020-05-05 19:50:06 +00:00
*/
2020-05-06 20:02:17 +00:00
public function getFaker(): Generator
2020-05-05 19:50:06 +00:00
{
return $this->faker;
}
//--------------------------------------------------------------------
2020-05-07 19:39:46 +00:00
/**
2020-05-16 16:24:33 +00:00
* Return and reset tempOverrides
2020-05-07 19:39:46 +00:00
*
* @return array
*/
public function getOverrides(): array
{
2020-05-16 16:24:33 +00:00
$overrides = $this->tempOverrides ?? $this->overrides;
2020-05-07 19:39:46 +00:00
2020-05-16 16:24:33 +00:00
$this->tempOverrides = $this->overrides;
2020-05-07 19:39:46 +00:00
return $overrides;
}
/**
* Set the overrides, once or persistent
*
* @param array $overrides Array of [field => value]
* @param boolean $persist Whether these overrides should persist through the next operation
*
* @return $this
*/
public function setOverrides(array $overrides = [], $persist = true): self
{
if ($persist)
{
$this->overrides = $overrides;
}
2020-05-16 16:24:33 +00:00
$this->tempOverrides = $overrides;
2020-05-07 19:39:46 +00:00
return $this;
}
//--------------------------------------------------------------------
2020-05-05 19:50:06 +00:00
/**
* Returns the current formatters
*
* @return array|null
*/
public function getFormatters(): ?array
{
return $this->formatters;
}
/**
* Set the formatters to use. Will attempt to autodetect if none are available.
*
2020-05-07 19:39:46 +00:00
* @param array|null $formatters Array of [field => formatter], or null to detect
*
2020-05-05 19:50:06 +00:00
* @return $this
*/
public function setFormatters(array $formatters = null): self
{
if (! is_null($formatters))
{
$this->formatters = $formatters;
}
elseif (method_exists($this->model, 'fake'))
{
$this->formatters = null;
}
else
{
$formatters = $this->detectFormatters();
}
2020-05-06 20:02:17 +00:00
return $this;
2020-05-05 19:50:06 +00:00
}
/**
* Try to identify the appropriate Faker formatter for each field.
*
* @return $this
*/
protected function detectFormatters(): self
{
$this->formatters = [];
if (! empty($this->model->allowedFields))
2020-05-05 19:50:06 +00:00
{
foreach ($this->model->allowedFields as $field)
{
$this->formatters[$field] = $this->guessFormatter($field);
}
2020-05-05 19:50:06 +00:00
}
return $this;
}
/**
* Guess at the correct formatter to match a field name.
*
2020-08-18 22:16:06 +07:00
* @param string $field Name of the field
2020-05-05 19:50:06 +00:00
*
* @return string Name of the formatter
*/
2020-05-06 20:02:17 +00:00
protected function guessFormatter($field): string
2020-05-05 19:50:06 +00:00
{
// First check for a Faker formatter of the same name - covers things like "email"
try
{
$this->faker->getFormatter($field);
return $field;
}
2020-10-04 00:27:56 +07:00
catch (InvalidArgumentException $e)
2020-05-05 19:50:06 +00:00
{
// No match, keep going
}
2020-05-06 20:02:17 +00:00
// Next look for known model fields
if (in_array($field, $this->dateFields, true))
2020-05-06 20:02:17 +00:00
{
2020-05-08 02:07:20 +00:00
switch ($this->model->dateFormat)
{
case 'datetime':
2020-05-08 16:22:56 +00:00
return 'date';
2020-05-08 02:07:20 +00:00
case 'date':
return 'date';
case 'int':
return 'unixTime';
}
2020-05-06 20:02:17 +00:00
}
elseif ($field === $this->model->primaryKey)
{
return 'numberBetween';
}
2020-05-05 19:50:06 +00:00
// Check some common partials
foreach (['email', 'name', 'title', 'text', 'date', 'url'] as $term)
{
if (stripos($field, $term) !== false)
{
2020-05-07 17:01:29 +00:00
return $term;
2020-05-05 19:50:06 +00:00
}
}
if (stripos($field, 'phone') !== false)
{
return 'phoneNumber';
}
// Nothing left, use the default
return $this->defaultFormatter;
}
//--------------------------------------------------------------------
/**
* Generate new entities with faked data
*
2020-05-07 19:39:46 +00:00
* @param integer|null $count Optional number to create a collection
2020-05-05 19:50:06 +00:00
*
* @return array|object An array or object (based on returnType), or an array of returnTypes
*/
2020-05-07 19:39:46 +00:00
public function make(int $count = null)
2020-05-05 19:50:06 +00:00
{
// If a singleton was requested then go straight to it
if (is_null($count))
{
2020-05-07 20:21:11 +00:00
return $this->model->returnType === 'array'
? $this->makeArray()
: $this->makeObject();
2020-05-05 19:50:06 +00:00
}
$return = [];
2020-05-05 19:50:37 +00:00
2020-05-05 19:50:06 +00:00
for ($i = 0; $i < $count; $i++)
{
2020-05-07 20:21:11 +00:00
$return[] = $this->model->returnType === 'array'
? $this->makeArray()
: $this->makeObject();
2020-05-05 19:50:06 +00:00
}
return $return;
}
/**
* Generate an array of faked data
*
* @return array An array of faked data
*
2020-10-04 00:27:56 +07:00
* @throws RuntimeException
2020-05-05 19:50:06 +00:00
*/
2020-05-07 20:21:11 +00:00
public function makeArray()
2020-05-05 19:50:06 +00:00
{
if (! is_null($this->formatters))
{
$result = [];
foreach ($this->formatters as $field => $formatter)
{
$result[$field] = $this->faker->{$formatter};
}
}
// If no formatters were defined then look for a model fake() method
elseif (method_exists($this->model, 'fake'))
{
2020-05-07 17:01:29 +00:00
$result = $this->model->fake($this->faker);
2020-05-05 19:50:06 +00:00
// This should cover entities
if (method_exists($result, 'toArray'))
{
$result = $result->toArray();
}
// Try to cast it
else
{
$result = (array) $result;
}
}
// Nothing left to do but give up
else
{
2020-10-04 00:27:56 +07:00
throw new RuntimeException(lang('Fabricator.missingFormatters'));
2020-05-05 19:50:06 +00:00
}
// Replace overridden fields
2020-05-07 19:39:46 +00:00
return array_merge($result, $this->getOverrides());
2020-05-05 19:50:06 +00:00
}
/**
* Generate an object of faked data
*
2020-05-07 20:21:11 +00:00
* @param string|null $className Class name of the object to create; null to use model default
*
* @return object An instance of the class with faked data
2020-05-05 19:50:06 +00:00
*
2020-10-04 00:27:56 +07:00
* @throws RuntimeException
2020-05-05 19:50:06 +00:00
*/
2020-05-07 20:21:11 +00:00
public function makeObject(string $className = null): object
2020-05-05 19:50:06 +00:00
{
2020-05-07 20:21:11 +00:00
if (is_null($className))
{
if ($this->model->returnType === 'object' || $this->model->returnType === 'array')
{
$className = 'stdClass';
}
else
{
$className = $this->model->returnType;
}
}
2020-05-05 19:50:06 +00:00
// If using the model's fake() method then check it for the correct return type
if (is_null($this->formatters) && method_exists($this->model, 'fake'))
{
2020-05-07 17:01:29 +00:00
$result = $this->model->fake($this->faker);
2020-05-05 19:50:37 +00:00
2020-05-07 20:21:11 +00:00
if ($result instanceof $className)
2020-05-05 19:50:06 +00:00
{
// Set overrides manually
2020-05-07 19:39:46 +00:00
foreach ($this->getOverrides() as $key => $value)
2020-05-05 19:50:06 +00:00
{
$result->{$key} = $value;
}
return $result;
}
}
2020-05-07 20:21:11 +00:00
// Get the array values and apply them to the object
2020-05-07 19:39:46 +00:00
$array = $this->makeArray();
2020-05-07 20:21:11 +00:00
$object = new $className();
2020-05-05 19:50:06 +00:00
// Check for the entity method
if (method_exists($object, 'fill'))
{
$object->fill($array);
}
else
{
2020-05-06 20:02:17 +00:00
foreach ($array as $key => $value)
2020-05-05 19:50:06 +00:00
{
$object->{$key} = $value;
}
}
return $object;
}
2020-05-06 16:21:05 +00:00
//--------------------------------------------------------------------
/**
* Generate new entities from the database
*
2020-08-18 22:16:06 +07:00
* @param integer|null $count Optional number to create a collection
* @param boolean $mock Whether to execute or mock the insertion
2020-05-06 16:21:05 +00:00
*
* @return array|object An array or object (based on returnType), or an array of returnTypes
*/
2020-05-07 23:34:00 +00:00
public function create(int $count = null, bool $mock = false)
2020-05-06 16:21:05 +00:00
{
// Intercept mock requests
if ($mock)
{
2020-05-07 23:34:00 +00:00
return $this->createMock($count);
2020-05-06 16:21:05 +00:00
}
$ids = [];
// Iterate over new entities and insert each one, storing insert IDs
2020-05-07 23:34:00 +00:00
foreach ($this->make($count ?? 1) as $result)
2020-05-06 16:21:05 +00:00
{
2020-07-03 18:54:17 +00:00
if ($id = $this->model->insert($result, true))
{
$ids[] = $id;
self::upCount($this->model->table);
}
2020-05-06 16:21:05 +00:00
}
// If the model defines a "withDeleted" method for handling soft deletes then use it
if (method_exists($this->model, 'withDeleted'))
{
$this->model->withDeleted();
}
return $this->model->find(is_null($count) ? reset($ids) : $ids);
2020-05-06 16:21:05 +00:00
}
/**
* Generate new database entities without actually inserting them
*
2020-05-08 16:22:56 +00:00
* @param integer|null $count Optional number to create a collection
2020-05-06 16:21:05 +00:00
*
* @return array|object An array or object (based on returnType), or an array of returnTypes
*/
2020-05-08 16:22:56 +00:00
protected function createMock(int $count = null)
2020-05-06 16:21:05 +00:00
{
2020-05-08 16:22:56 +00:00
switch ($this->model->dateFormat)
{
case 'datetime':
$datetime = date('Y-m-d H:i:s');
case 'date':
$datetime = date('Y-m-d');
default:
$datetime = time();
}
2020-05-06 16:21:05 +00:00
// Determine which fields we will need
$fields = [];
if (! empty($this->model->useTimestamps))
2020-05-06 16:21:05 +00:00
{
2020-08-18 22:16:06 +07:00
$fields[$this->model->createdField] = $datetime; // @phpstan-ignore-line
$fields[$this->model->updatedField] = $datetime; // @phpstan-ignore-line
2020-05-06 16:21:05 +00:00
}
if (! empty($this->model->useSoftDeletes))
2020-05-06 16:21:05 +00:00
{
2020-08-18 22:16:06 +07:00
$fields[$this->model->deletedField] = null; // @phpstan-ignore-line
2020-05-06 16:21:05 +00:00
}
// Iterate over new entities and add the necessary fields
$return = [];
2020-05-07 23:34:00 +00:00
foreach ($this->make($count ?? 1) as $i => $result)
2020-05-06 16:21:05 +00:00
{
// Set the ID
$fields[$this->model->primaryKey] = $i;
// Merge fields
if (is_array($result))
{
$result = array_merge($result, $fields);
}
else
{
foreach ($fields as $key => $value)
{
$result->{$key} = $value;
}
}
$return[] = $result;
}
return is_null($count) ? reset($return) : $return;
}
2020-05-05 19:50:06 +00:00
}