<?php
/**
 * Do database migrations
 *
 * This file is part of Zoph.
 *
 * Zoph is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Zoph is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with Zoph; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @package Zoph
 * @author Jeroen Roos
 */

namespace upgrade;

use settings;
/**
 * Database migrations
 *
 * @package Zoph
 * @author Jeroen Roos
 */
class migrations {
    private $todo = array();
    private $down = array();
    private $dir = "";
    private $migrations = array();

    /**
     * Create migrations class and load migrations
     * @param string directory to load from
     * @codeCoverageIgnore - run in test setup
     */
    public function __construct(string $dir = "migrations/") {
        $this->dir = settings::$php_loc . "/" . $dir;
        if (!defined("MIGRATIONS")) {
            define("MIGRATIONS", 1);
            $migrations = glob($this->dir . "/*.migration.php");
            foreach ($migrations as $migration) {
                $this->register(require_once($migration));
            }
        }
    }

    /**
     * Register a migration
     * @param migration migration to register
     */
    public function register(migration $migration) {
        $this->migrations[]=$migration;
    }

    /**
     * Check whether there are any migrations pending
     * @param string current version
     * @return bool whether there are any pending migrations
     */
    public function check(string $version) {
        $this->todo=array();
        $this->down=array();
        foreach ($this->migrations as $migration) {
            if ($migration->isRequired($version)) {
                $this->todo[] = $migration;
            }
            if ($migration->isCurrent($version)) {
                $this->down[] = $migration;
            }
        }
        return !empty($this->todo);
    }

    /**
     * Get pending migrations
     * @return array pending migrations
     */
    public function get() {
        return $this->todo;
    }

    /**
     * Get 'down' migration
     * Get migrations available to migrate down - at this moment this is always one, the last, migration
     * @return array down migrations
     */
    public function getDown() {
        return $this->down;
    }
}
