Migrations.php

<?php

namespace Tlf\BigDb;

/**
 * Provides methods for running migrations.
 */
trait Migrations {

    /**
     * Migrate up or down between the library's database versions
     *
     * @param $version_from the current database version - pass `0` (zero) if database has not been created.
     * @return void
     *
     * @override to use a different migration scheme than LilDb's LilMigrations class
     */
    public function migrate(int $version_from, int $version_to){
        if (!isset($this->sql)){
            $this->init_sql();
        }

        $lm = new \Tlf\LilMigrations($this->pdo, $this->get_migration_dir());
        $lm->migration_vars = $this->get_migration_vars();

        $lm->migrate($version_from, $version_to);
    }

    /**
     * Get available migration versions
     *
     * @param $version_from the current database version - pass `0` (zero) if database has not been created.
     * @return array<string migration_dir_path, array migration> & migration is array<version,up,down> with file basename with extension of the up & down file.
     *
     * @override to use a different migration scheme than LilDb's LilMigrations class
     */
    public function get_migrations(){
        if (!isset($this->sql)){
            $this->init_sql();
        }


        $migrations = [];

        $migration_dir = $this->get_migration_dir();
        foreach (scandir($migration_dir) as $dir){
            if (substr($dir,0,1)!='v'||!is_numeric($version = substr($dir,1)))continue;
            $path = $migration_dir.'/'.$dir;
            if (!is_dir($path))continue;



            $migration = ['version'=>$version];

            $files = scandir($path);
            foreach ($files as $f){
                if (substr($f,0,3)=='up.')$migration['up'] = $f;
                else if (substr($f,0,5)=='down.')$migration['down'] = $f;
            }

            $migrations[$dir] = $migration;
        }

        return $migrations;
    }


    /**
     * Get the full path to a directory containing migrations. See LilDb's LilMigrations at https://gitlab.com/taeluf/php/lildb
     * @return string directory path, which should contain sub-directories like `v1`, `v2`, and so on.
     *
     * @override if your migration dir is not at your `root_dir/migrate/`
     */
    public function get_migration_dir(): string {
        return $this->get_root_dir().'/migrate/';
    }

    /**
     * Get an array of variables that should be made available to migrations php files.
     *
     * @return array<string, object> containing `['db'=>$this]`
     *
     * @override to make additional vars available to your library's migrations
     */
    public function get_migration_vars(): array {

        return ['db'=>$this];
    }

}