ConfigurationFileWithFallback.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\Migrations\Configuration\Migration;
  4. use Doctrine\Migrations\Configuration\Configuration;
  5. use Doctrine\Migrations\Configuration\Migration\Exception\MissingConfigurationFile;
  6. use Doctrine\Migrations\Tools\Console\Exception\FileTypeNotSupported;
  7. use function file_exists;
  8. /**
  9. * This class creates a configuration instance from a configuration file passed as argument.
  10. * If no arguments are provided, will try to load one of migrations.{xml, yml, yaml, json, php} files.
  11. *
  12. * @internal
  13. */
  14. final class ConfigurationFileWithFallback implements ConfigurationLoader
  15. {
  16. /** @var string|null */
  17. private $file;
  18. public function __construct(?string $file = null)
  19. {
  20. $this->file = $file;
  21. }
  22. public function getConfiguration(): Configuration
  23. {
  24. if ($this->file !== null) {
  25. return $this->loadConfiguration($this->file);
  26. }
  27. /**
  28. * If no config has been provided, look for default config file in the path.
  29. */
  30. $defaultFiles = [
  31. 'migrations.xml',
  32. 'migrations.yml',
  33. 'migrations.yaml',
  34. 'migrations.json',
  35. 'migrations.php',
  36. ];
  37. foreach ($defaultFiles as $file) {
  38. if ($this->configurationFileExists($file)) {
  39. return $this->loadConfiguration($file);
  40. }
  41. }
  42. throw MissingConfigurationFile::new();
  43. }
  44. private function configurationFileExists(string $config): bool
  45. {
  46. return file_exists($config);
  47. }
  48. /**
  49. * @throws FileTypeNotSupported
  50. */
  51. private function loadConfiguration(string $file): Configuration
  52. {
  53. return (new FormattedFile($file))->getConfiguration();
  54. }
  55. }