pdo-document/tests/integration/sqlite/ThrowawayDb.php
2024-06-12 17:43:17 -04:00

54 lines
1.9 KiB
PHP

<?php
namespace Test\Integration\SQLite;
use BitBadger\PDODocument\{AutoId, Configuration, Definition, Document, DocumentException, Mode};
use Random\RandomException;
use Test\Integration\{SubDocument, TestDocument};
/**
* Utilities to create and destroy a throwaway SQLite database to use for testing
*/
class ThrowawayDb
{
/** @var string The table used for document manipulation */
public const TABLE = "test_table";
/**
* Create a throwaway SQLite database
*
* @param bool $withData Whether to initialize this database with data (optional; defaults to `true`)
* @return string The name of the database (use to pass to `destroy` function at end of test)
* @throws DocumentException|RandomException If any is encountered
*/
public static function create(bool $withData = true): string
{
$fileName = sprintf('throwaway-%s.db', AutoId::generateRandom(10));
Configuration::$pdoDSN = "sqlite:./$fileName";
Configuration::$mode = Mode::SQLite;
Configuration::resetPDO();
if ($withData) {
Definition::ensureTable(self::TABLE);
Document::insert(self::TABLE, new TestDocument('one', 'FIRST!', 0));
Document::insert(self::TABLE, new TestDocument('two', 'another', 10, new SubDocument('green', 'blue')));
Document::insert(self::TABLE, new TestDocument('three', '', 4));
Document::insert(self::TABLE, new TestDocument('four', 'purple', 17, new SubDocument('green', 'red')));
Document::insert(self::TABLE, new TestDocument('five', 'purple', 18));
}
return $fileName;
}
/**
* Destroy a throwaway SQLite database
*
* @param string $fileName The name of the SQLite database to be deleted
*/
public static function destroy(string $fileName): void
{
Configuration::resetPDO();
if (file_exists("./$fileName")) unlink("./$fileName");
}
}