ConfigurationFile.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\Migrations\Configuration\Connection;
  4. use Doctrine\DBAL\Connection;
  5. use Doctrine\DBAL\DriverManager;
  6. use Doctrine\Migrations\Configuration\Connection\Exception\FileNotFound;
  7. use Doctrine\Migrations\Configuration\Connection\Exception\InvalidConfiguration;
  8. use InvalidArgumentException;
  9. use function file_exists;
  10. use function is_array;
  11. /**
  12. * This class will return a Connection instance, loaded from a configuration file provided as argument.
  13. */
  14. final class ConfigurationFile implements ConnectionLoader
  15. {
  16. /** @var string */
  17. private $filename;
  18. public function __construct(string $filename)
  19. {
  20. $this->filename = $filename;
  21. }
  22. public function getConnection(?string $name = null): Connection
  23. {
  24. if ($name !== null) {
  25. throw new InvalidArgumentException('Only one connection is supported');
  26. }
  27. if (! file_exists($this->filename)) {
  28. throw FileNotFound::new($this->filename);
  29. }
  30. $params = include $this->filename;
  31. if ($params instanceof Connection) {
  32. return $params;
  33. }
  34. if ($params instanceof ConnectionLoader) {
  35. return $params->getConnection();
  36. }
  37. if (is_array($params)) {
  38. return DriverManager::getConnection($params);
  39. }
  40. throw InvalidConfiguration::invalidArrayConfiguration();
  41. }
  42. }