pdo-document/tests/Integration/SQLite/ThrowawayDb.php

71 lines
2.2 KiB
PHP
Raw Permalink Normal View History

<?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';
2024-11-17 21:30:53 +00:00
/**
* Load data into the test table
*
* @throws DocumentException If any is encountered
*/
public static function loadData(): void
{
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));
}
/**
* 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();
2024-11-17 21:30:53 +00:00
Definition::ensureTable(self::TABLE);
if ($withData) {
2024-11-17 21:30:53 +00:00
self::loadData();
}
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");
}
}