MigrationDirectory.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace Michel\PaperORM\Migration;
  3. final class MigrationDirectory
  4. {
  5. private string $dir;
  6. public function __construct(string $dir)
  7. {
  8. if (!is_dir($dir)) {
  9. if (!mkdir($dir, 0777, true)) {
  10. throw new \InvalidArgumentException("Cannot create directory '$dir', check permissions.");
  11. }
  12. }
  13. if (!is_writable($dir)) {
  14. throw new \RuntimeException("Directory '$dir' is not writable.");
  15. }
  16. $this->dir = $dir;
  17. }
  18. public function getMigrations(): array
  19. {
  20. $migrations = [];
  21. foreach (new \DirectoryIterator($this->dir) as $file) {
  22. if ($file->getExtension() !== 'sql') {
  23. continue;
  24. }
  25. $version = pathinfo($file->getBasename(), PATHINFO_FILENAME);
  26. $migrations[$version] = $file->getPathname();
  27. }
  28. ksort($migrations);
  29. return $migrations;
  30. }
  31. public function getMigration(string $version): string
  32. {
  33. $migrations = $this->getMigrations();
  34. if (!array_key_exists($version, $migrations)) {
  35. throw new \InvalidArgumentException("Version '$version' does not exist.");
  36. }
  37. return $migrations[$version];
  38. }
  39. /**
  40. * @return string
  41. */
  42. public function getDir(): string
  43. {
  44. return $this->dir;
  45. }
  46. }