<?php

namespace Velis\Model;

use Velis\App;

/**
 * Base class for all models
 * @author Olek Procki <olo@velis.pl>
 *
 * \section sec_intro Introduction
 *
 * Zend Framework doesn't have any base class for models
 * to keep maximum flexibility. There are two kinds of base models in stylio project.
 * BaseModel is one of them. It contains static $_db PostgreSQL database handle.
 * Simply use <code>self::$_db</code> when accessing database. It is also a base class for another
 * type of model - DataObject.
 *
 * Two important things about models
 *
 */
abstract class BaseModel extends \ArrayObject
{
    /**
     * Database handle
     * @var \Velis\Db\Postgres
     */
    protected static $_db;


    /**
     * Returns db handle depending on adapter
     * @return \Velis\Db\Postgres
     */
    protected function _getDb()
    {
        return static::$_db;
    }


    /**
     * Initialize database handle
     */
    public static function init()
    {
        self::$_db = App::$di['db'];
    }


    /**
     * Changes database handle
     * @param \Velis\Db\Postgres $db
     */
    public static function changeDb(\Velis\Db\Postgres $db = null)
    {
        if ($db != null) {
            self::$_db = $db;
        } else {
            self::$_db = App::$di['db'];
        }
    }


    /**
     * Loads class by name
     * @param string $class
     */
    public static function loadClass($class)
    {
        $filename = ROOT_PATH . 'model' . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
        if (file_exists($filename)) {
            // This internal config file has its extension - it's declared with variable declaration.
            // @phpcs:ignore
            require_once $filename;
        }
    }


    /**
     * Register {@link loadClass()} with spl_autoload()
     */
    public static function registerAutoload()
    {
        spl_autoload_register(__CLASS__ . '::loadClass');
    }
}
