<?php
/**
 * Part of Showkase web site management package
 *
 * @package Showkase
 * @author Jack Hardie {@link http://www.jhardie.com}
 * @copyright Copyright (c) 2012, SimpleViewer Inc.
 */
defined('SK_ACCESS')||die('<h1>403: Forbidden</h1>');
$ds = DIRECTORY_SEPARATOR;
require_once "commands{$ds}showpages.php";
class CommandResolver
{
    private static $base_cmd;
    private static $default_cmd;
    private $commandPath;
    function __construct() {
        $sep = DIRECTORY_SEPARATOR;
        $this->commandPath = "commands{$sep}";
        if (! self::$base_cmd) {
            self::$base_cmd = new ReflectionClass("Command");
            self::$default_cmd = new ShowPages();
        }
    }
    function getCommand(Request $request) {
        $cmd = $request->getProperty('cmd');
        $sep = DIRECTORY_SEPARATOR;
        if (! $cmd) {
            return self::$default_cmd;
        }
        // important for security
        $cmd = strtolower(str_replace(array('.',$sep), "", $cmd));
        $filepath = $this->commandPath.$cmd.'.php';
        $classname = "$cmd";
        if (file_exists($filepath)) {
            require_once("$filepath");
            if (class_exists( $classname)) {
                $cmd_class = new ReflectionClass($classname);
                if ($cmd_class->isSubClassOf( self::$base_cmd)) {
                    return $cmd_class->newInstance();
                } else {
                    $request->addFeedback("Command '$cmd' is not a Command");
                }
            }
        }
        $request->addFeedback("Command '$cmd' not found");
        return clone self::$default_cmd;
    }
}