You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
105 lines
2.6 KiB
105 lines
2.6 KiB
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* @author Robert Strutts
|
|
* @copyright Copyright (c) 2022, Robert Strutts.
|
|
* @license MIT
|
|
*/
|
|
|
|
namespace IOcornerstone\Framework\Database;
|
|
|
|
use IOcornerstone\Framework\{
|
|
RandomEngine,
|
|
Common,
|
|
};
|
|
|
|
final class DummyData {
|
|
|
|
private $pdo;
|
|
private $randomEngine;
|
|
|
|
public function __construct(\PDO $pdo) {
|
|
$this->pdo = $pdo;
|
|
$this->randomEngine = new RandomEngine();
|
|
}
|
|
|
|
/*
|
|
* Helper for add_dummy_data and get_dummy_data.
|
|
* Purpose: To return ONE ROW of junk/dummy data from input data.
|
|
* @param array $data
|
|
* @retval array of random dummy data AKA one row worth of it.
|
|
*/
|
|
|
|
private function useDummyData(array $data): array {
|
|
$ret = [];
|
|
foreach ($data as $field => $array_values) {
|
|
$array_count = Common::getCount($array_values);
|
|
if ($array_count) {
|
|
$ret[$field] = $array_values[$this->randomEngine->getInt(0, $array_count - 1)];
|
|
}
|
|
}
|
|
return $ret;
|
|
}
|
|
|
|
/**
|
|
* Inserts Dummy Data to DB
|
|
* @param int $num_rows to add/make
|
|
* @param array $data sample data EX: array('fname'=>array('bob','kim','lisa', ect...), ...)
|
|
* @retval bool true
|
|
*/
|
|
public function addDummyData(string $table, int $num_rows, array $data): bool {
|
|
for ($i = 0; $i < $num_rows; $i++) {
|
|
$bind_data = $this->useDummyData($data);
|
|
$fields = [];
|
|
foreach ($data as $field => $array_values) {
|
|
$fields[] = $field;
|
|
}
|
|
|
|
$sql = "INSERT INTO `{$table}` "
|
|
. "(" . implode(", ", $fields) . ") "
|
|
. "VALUES (:" . implode(", :", $fields) . ");";
|
|
|
|
$bind = [];
|
|
foreach ($fields as $field) {
|
|
$bind[":$field"] = $bind_data[$field];
|
|
}
|
|
unset($bind_data);
|
|
unset($fields);
|
|
|
|
$pdo_stmt = $this->pdo->prepare($sql);
|
|
$exec = $pdo_stmt->execute($bind);
|
|
unset($bind);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Make an array of fields for a fake row of dummy data out of input data.
|
|
* @param int $num_rows to make
|
|
* @param array $data sample data
|
|
* @retval array of rows with dummy data in it.
|
|
*/
|
|
public function getDummyData(int $num_rows, array $data): array {
|
|
if ($num_rows > 100) {
|
|
throw new \LengthException("Generating too much dummy data via \$num_rows!");
|
|
}
|
|
$ret = [];
|
|
for ($i = 0; $i < $num_rows; $i++) {
|
|
$ret[] = $this->useDummyData($data);
|
|
}
|
|
return $ret;
|
|
}
|
|
|
|
public function getDummyDataGenerator(
|
|
int $num_rows,
|
|
array $data
|
|
): \Generator {
|
|
for ($i = 0; $i < $num_rows; $i++) {
|
|
yield $this->useDummyData($data);
|
|
}
|
|
}
|
|
|
|
|
|
}
|
|
|