pdo-document/tests/integration/sqlite/ThrowawayDb.php
Daniel J. Summers d8330d828a Derive mode from DSN function
- Add headers in all files
- Minor field name changes
2024-07-20 21:47:21 -04:00

60 lines
2.0 KiB
PHP

<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
* @see https://github.com/Zaid-Ajaj/ThrowawayDb The origin concept
*/
declare(strict_types=1);
namespace Test\Integration\SQLite;
use BitBadger\PDODocument\{AutoId, Configuration, Definition, Document, DocumentException};
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::useDSN("sqlite:./$fileName");
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");
}
}