Skip to content

Instantly share code, notes, and snippets.

@bshaffer
Created June 22, 2010 16:24
Show Gist options
  • Save bshaffer/448698 to your computer and use it in GitHub Desktop.
Save bshaffer/448698 to your computer and use it in GitHub Desktop.
<?php
/**
*
*/
class sfFactory
{
protected static
$lastRandom = array(),
$lastIncrement = array();
const
DEFAULT_PASSWORD = 'password';
/**
* creates a randomly generated string and appends it or
* substitutes it (using sprintf) into the $format variable
*
* @param string $format
* @param string $length
* @return void
* @author Brent Shaffer
*/
public static function generate($format = '', $length=8)
{
$rand = self::random($length);
if ($format)
{
self::$lastRandom[$format] = self::format($format, $rand);
return self::$lastRandom[$format];
}
self::$lastRandom[] = self::random($length);
return end(self::$lastRandom);
}
/**
* returns the most recent unique string returned by generate() function
*
* @return unique string
* @author Brent Shaffer
*/
public static function last($format = null)
{
if ($format)
{
if (!isset(self::$lastRandom[$format]))
{
throw new sfException('No previously generated random available for "'.$format.'"');
}
return self::$lastRandom[$format];
}
if (!self::$lastRandom)
{
throw new sfException('No previously generated random available');
}
return end(self::$lastRandom);
}
public static function format($format, $fragment)
{
$count = substr_count($format, '%s');
if (!$count)
{
return rtrim($format). ' ' . $fragment;
}
$params = explode(',', str_repeat($fragment.',', $count-1) . $fragment);
$string = call_user_func_array('sprintf', array_merge(array($format), $params));
return $string;
}
public static function increment($format = '')
{
if ($format)
{
$i = isset(self::$lastIncrement[$format]) ? self::$lastIncrement[$format] : 0;
$i++;
self::$lastIncrement[$format] = $i;
return self::format($format, $i);
}
if(!$i = end(self::$lastIncrement))
{
$i = 0;
}
$i++;
self::$lastIncrement[] = $i;
return $i;
}
/**
* returns the most recent increment returned by increment() function
*
* @return unique string
* @author Brent Shaffer
*/
public static function lastIncrement($format = '')
{
if ($format)
{
if (!isset(self::$lastIncrement[$format]))
{
throw new sfException('No previously generated increment for "'.$format.'"');
}
return self::format($format, self::$lastIncrement[$format]);
}
if (!self::$lastIncrement)
{
throw new sfException('No previously generated increment available');
}
return end(self::$lastIncrement);
}
public static function create($model, $options = array())
{
$object = new $model;
$object->fromArray($options);
return $object;
}
/**
* generate a random string of characters and numbers
*
* @param string $len
* @return void
* @author Brent Shaffer
*/
public static function random($len = 16)
{
$base = 'ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz123456789';
$max = strlen($base) - 1;
$rand = '';
mt_srand((double) microtime() * 1000000);
while (strlen($rand) < $len)
{
$rand .= $base{mt_rand(0, $max)};
}
return $rand;
}
public static function generateObject($model, $options = array())
{
$fields = Doctrine::getTable($model)->getColumns();
$relations = Doctrine::getTable($model)->getRelations();
$tableOptions = Doctrine::getTable($model)->getOptions();
$generatedOptions = array();
foreach ($relations as $name => $relation)
{
if ($relation['local'] == 'id') continue;
if (isset($fields[$relation['local']]['notnull']) && $fields[$relation['local']]['notnull'])
{
$generatedOptions[$relation['local']] = self::selectRandomId($relation['class']);
}
unset($fields[$relation['local']]);
}
foreach ($fields as $field => $definition)
{
$val = null;
if (!isset($definition['default']))
{
if (isset($tableOptions['inheritanceMap'][$field]))
{
$val = $tableOptions['inheritanceMap'][$field];
}
elseif (isset($definition['notnull']) && $definition['notnull'])
{
switch ($definition['type'])
{
case 'string':
$val = self::generate($field);
break;
case 'integer':
$val = self::generateNumber();
break;
case 'timestamp':
$val = self::selectRandomDate();
break;
case 'boolean':
$val = rand(0, 1);
break;
case 'enum':
$val = self::selectRandom($definition['values']);
break;
}
}
}
else
{
$val = $definition['default'];
}
$generatedOptions[$field] = $val;
}
$object = new $model;
$object->fromArray(array_merge($generatedOptions, $options));
$object->save();
return $object;
}
public static function generateNumber($min = null, $max = null)
{
return rand($min, $max);
}
/**
* select a random value from an array
*
* @param string $array
* @return void
* @author Brent Shaffer
*/
public static function selectRandom($array)
{
$array = array_values($array);
return $array[rand(0, count($array)-1)];
}
/**
* filters an array at random, returns an array of filtered values
*
* @param string $possibleValues
* @return void
* @author Brent Shaffer
*/
public static function generateRandomArray($possibleValues)
{
$rand = array();
foreach ($possibleValues as $key => $value)
{
if(rand(0, 1)) {
$rand[$key] = $value;
}
}
return $rand;
}
/**
* returns the random id for an object in table $table
*
* @param string $table
* @return void
* @author Brent Shaffer
*/
public static function selectRandomId($table, $where = array(), $notIn = array())
{
return self::selectRandomObject($table, $where, $notIn)->getId();
}
/**
* returns a random object from table $table
*
* @param string $table
* @param string $where
* @param string $notIn
* @return void
* @author Brent Shaffer
*/
public static function selectRandomObject($table, $where = array(), $notIn = array())
{
$q = Doctrine::getTable($table)->createQuery()->orderBy('RAND()');
if ($notIn)
{
$q->whereNotIn('id', (array) $notIn);
}
foreach ($where as $field => $value)
{
$q->andWhere($q->getRootAlias().".$field = ?", $value);
}
return $q->fetchOne();
}
public static function selectRandomDate($start_date = null, $end_date = null, $format = 'Y-m-d H:i:s')
{
if (!$start_date)
{
$start_date = date('Y-m-d', strtotime('-1 year'));
}
if (!$end_date)
{
$end_date = date('Y-m-d');
}
$diff = abs(strtotime($end_date) - strtotime($start_date));
$rand = rand(0, $diff);
return date($format, strtotime($start_date) + $rand);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment