<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/

/**
 * Class AHDB_Core_Request
 */
class AHDB_Core_Request {

    // Class constants
    const PARAM_CONTROLLER = 'c';
    const PARAM_ACTION = 'a';

    // Members
    public $controller = NULL;
    public $action = NULL;
    /** @var AHDB_Core_RequestData|null $data */
    public $data = NULL;

    /**
     * @param $controller
     * @param $action
     * @param array $data
     */
    public function __construct( $controller, $action, array $data = array() ) {
        $this->controller = $controller;
        $this->action = $action;
        $this->data = new AHDB_Core_RequestData( $data );
    }

    /**
     * Create a request from given http request data
     *
     * @param array $httpRequest $_REQUEST data
     * @return AHDB_Core_Request
     */
    public static function create( array $httpRequest = array() ) {
        // Revolve controller & action
        $controller = isset( $httpRequest[ self::PARAM_CONTROLLER ] ) ? $httpRequest[ self::PARAM_CONTROLLER ] : 'Index';
        $action = isset( $httpRequest[ self::PARAM_ACTION ] ) ? $httpRequest[ self::PARAM_ACTION ] : 'index';

        // Remove controller & action data from data
        unset( $httpRequest[ self::PARAM_CONTROLLER ] );
        unset( $httpRequest[ self::PARAM_ACTION  ] );

        return new AHDB_Core_Request( $controller, $action, $httpRequest );
    }

    /**
     * Creates a valid request url
     *
     * @param string $baseUrl Base URL
     * @param string $controller Name of controller class
     * @param string $action Action(=method) name of controller class
     * @param null|array $args (optional) is NULL
     * @param string $protocol (optional) default is 'http'
     * @return string
     */
    public static function createUrl( $baseUrl, $controller = 'Index', $action = 'index', $args = NULL, $protocol = 'http' ) {
        $url  = rtrim( $baseUrl, '/' ) . '/?' . self::PARAM_CONTROLLER . '=';
        $url .= $controller;
        $url .= '&' . self::PARAM_ACTION . '=' . $action;

        if ( is_array( $args ) &&
            0 < count( $args ) ) {
            $url .= '&' . http_build_query( $args );
        }

        return $protocol . '://' . $url;
    }
} 