|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Webfactory\Slimdump\Database; |
| 4 | + |
| 5 | +use Doctrine\DBAL\Connection; |
| 6 | +use Generator; |
| 7 | +use PHPUnit\Framework\Attributes\DataProvider; |
| 8 | +use PHPUnit\Framework\Attributes\Test; |
| 9 | +use PHPUnit\Framework\TestCase; |
| 10 | +use SimpleXMLElement; |
| 11 | +use Webfactory\Slimdump\Config\Table; |
| 12 | + |
| 13 | +final class CsvOutputFormatDriverTest extends TestCase |
| 14 | +{ |
| 15 | + private const OUTPUT_DIRECTORY = __DIR__.'/../../../../tmp'; |
| 16 | + |
| 17 | + private CsvOutputFormatDriver $driver; |
| 18 | + |
| 19 | + protected function setUp(): void |
| 20 | + { |
| 21 | + parent::setUp(); |
| 22 | + |
| 23 | + $this->driver = new CsvOutputFormatDriver(self::OUTPUT_DIRECTORY, $this->createMock(Connection::class)); |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * @param array<string, string> $tableRow |
| 28 | + */ |
| 29 | + #[Test] |
| 30 | + #[DataProvider('provideDataFor_dumpTableRow')] |
| 31 | + public function dumpTableRow(string $tableConfigAsXml, array $tableRow, string $expectedValue): void |
| 32 | + { |
| 33 | + $csvData = $this->dumpTableAsCsv($tableConfigAsXml, $tableRow); |
| 34 | + |
| 35 | + $this->assertSame($expectedValue, $csvData[1][0]); |
| 36 | + } |
| 37 | + |
| 38 | + public static function provideDataFor_dumpTableRow(): Generator |
| 39 | + { |
| 40 | + yield 'can dump row as is' => [ |
| 41 | + '<table dump="full" />', |
| 42 | + ['my-column' => 'my-original-value'], |
| 43 | + 'my-original-value', |
| 44 | + ]; |
| 45 | + |
| 46 | + yield 'can dump with configured replacement' => [ |
| 47 | + '<table dump="full"><column name="my-column" dump="replace" replacement="my-replacing-value"/></table>', |
| 48 | + ['my-column' => 'my-original-value'], |
| 49 | + 'my-replacing-value', |
| 50 | + ]; |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * @param array<string, string> $tableRow |
| 55 | + * |
| 56 | + * @return array<int, array<string>> the dumped CSV data as array of rows, each row being an array of columns |
| 57 | + */ |
| 58 | + private function dumpTableAsCsv(string $tableConfigAsXml, array $tableRow): array |
| 59 | + { |
| 60 | + $tableSchema = new \Doctrine\DBAL\Schema\Table('my-table'); |
| 61 | + $tableConfig = new Table( |
| 62 | + new SimpleXMLElement($tableConfigAsXml) |
| 63 | + ); |
| 64 | + |
| 65 | + $this->driver->beginTableDataDump($tableSchema, $tableConfig); |
| 66 | + $this->driver->dumpTableRow($tableRow, $tableSchema, $tableConfig); |
| 67 | + $this->driver->endTableDataDump($tableSchema, $tableConfig); |
| 68 | + |
| 69 | + $outputFile = self::OUTPUT_DIRECTORY.'/my-table.csv'; |
| 70 | + $this->assertFileExists($outputFile); |
| 71 | + |
| 72 | + return array_map('str_getcsv', file($outputFile)); |
| 73 | + } |
| 74 | +} |
0 commit comments