|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Respect\Relational; |
| 6 | + |
| 7 | +use PHPUnit\Framework\TestCase; |
| 8 | +use Respect\Relational\Database\ConnectionFactory; |
| 9 | +use Respect\Relational\Database\InvalidDriverConfiguration; |
| 10 | + |
| 11 | +use function getenv; |
| 12 | +use function putenv; |
| 13 | + |
| 14 | +class ConnectionFactoryTest extends TestCase |
| 15 | +{ |
| 16 | + /** @var array<string, string|false> */ |
| 17 | + private array $envBackup = []; |
| 18 | + |
| 19 | + protected function setUp(): void |
| 20 | + { |
| 21 | + foreach (['DB_DRIVER', 'DB_DSN', 'DB_USER', 'DB_PASSWORD'] as $name) { |
| 22 | + $this->envBackup[$name] = getenv($name); |
| 23 | + putenv($name); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + public function testDefaultsToSqliteWhenEnvUnset(): void |
| 28 | + { |
| 29 | + $this->assertSame('sqlite', ConnectionFactory::driver()); |
| 30 | + } |
| 31 | + |
| 32 | + public function testHonorsDbDriverEnvVar(): void |
| 33 | + { |
| 34 | + putenv('DB_DRIVER=mysql'); |
| 35 | + $this->assertSame('mysql', ConnectionFactory::driver()); |
| 36 | + } |
| 37 | + |
| 38 | + public function testDsnSchemeIsAuthoritativeWhenDbDriverUnset(): void |
| 39 | + { |
| 40 | + putenv('DB_DSN=pgsql:host=foo;dbname=bar'); |
| 41 | + $this->assertSame('pgsql', ConnectionFactory::driver()); |
| 42 | + } |
| 43 | + |
| 44 | + public function testAcceptsMatchingDbDriverAndDsnScheme(): void |
| 45 | + { |
| 46 | + putenv('DB_DRIVER=mysql'); |
| 47 | + putenv('DB_DSN=mysql:host=foo;dbname=bar'); |
| 48 | + $this->assertSame('mysql', ConnectionFactory::driver()); |
| 49 | + } |
| 50 | + |
| 51 | + public function testThrowsWhenDbDriverAndDsnSchemeDisagree(): void |
| 52 | + { |
| 53 | + putenv('DB_DRIVER=mysql'); |
| 54 | + putenv('DB_DSN=pgsql:host=foo;dbname=bar'); |
| 55 | + $this->expectException(InvalidDriverConfiguration::class); |
| 56 | + $this->expectExceptionMessage('DB_DRIVER (mysql) does not match the scheme of DB_DSN (pgsql)'); |
| 57 | + ConnectionFactory::driver(); |
| 58 | + } |
| 59 | + |
| 60 | + public function testThrowsWhenDsnHasNoScheme(): void |
| 61 | + { |
| 62 | + putenv('DB_DSN=no-colon-here'); |
| 63 | + $this->expectException(InvalidDriverConfiguration::class); |
| 64 | + ConnectionFactory::driver(); |
| 65 | + } |
| 66 | + |
| 67 | + public function testThrowsWhenDsnStartsWithColon(): void |
| 68 | + { |
| 69 | + putenv('DB_DSN=:nothing-before-colon'); |
| 70 | + $this->expectException(InvalidDriverConfiguration::class); |
| 71 | + ConnectionFactory::driver(); |
| 72 | + } |
| 73 | + |
| 74 | + protected function tearDown(): void |
| 75 | + { |
| 76 | + foreach ($this->envBackup as $name => $value) { |
| 77 | + if ($value === false) { |
| 78 | + putenv($name); |
| 79 | + } else { |
| 80 | + putenv($name . '=' . $value); |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | +} |
0 commit comments