<?php

namespace App\Plugins;



use App\Exception\ExceptionErrorCatch;
use Helpers\DebugLog;

class Hook extends \Yaf\Plugin_Abstract {

	public function routerStartup(\Yaf\Request_Abstract $request, \Yaf\Response_Abstract $response) {
        // 重定义异常处理
        ExceptionErrorCatch::register();
	}

	public function routerShutdown(\Yaf\Request_Abstract $request, \Yaf\Response_Abstract $response) {
		/*---Debug Begin---*/
		if((defined('_IS_DEBUG') && _IS_DEBUG) || (isset($_REQUEST['__debug']) && strpos($_REQUEST['__debug'], _DEBUG_PASS) !== false))
		{
			// $_REQUEST['__debug'] = _DEBUG_PASS + 1 (2 数字表示级别 )
			$debug_level = intval(substr($_REQUEST['__debug'], -1));
			if ($debug_level > 0) {
				define('DEBUG_LEVEL', $debug_level );
			} else {
				define('DEBUG_LEVEL', 1);
			}
			//Debug模式将错误打开
			ini_set('display_errors', true);
			//设置错误级别
			error_reporting(_ERROR_LEVEL);
			//开启ob函数
			ob_start();
			//Debug开关打开
			DebugLog::init();
			//注册shutdown函数用来Debug显示
			register_shutdown_function(array('Helpers\DebugLog', 'show'));
		} else {
			define('DEBUG_LEVEL', 0);
		}
		// 调试探针，初始化完成，页面开始执行
		DebugLog::time('init.php, start page');
	}

	public function dispatchLoopStartup(\Yaf\Request_Abstract $request, \Yaf\Response_Abstract $response) {
	}

	public function preDispatch(\Yaf\Request_Abstract $request, \Yaf\Response_Abstract $response) {
		//处理$_POST, $_REQUEST请求,兼容application/json形式
		if(!$_POST && $request->isPost() 
			&& $request->getServer('CONTENT_TYPE') == 'application/json') {
            $jsonPost = file_get_contents("php://input");
            if($jsonPost) {
				$_POST = json_decode($jsonPost, true);
				$ini = ini_get('request_order');
				if($ini) {
					$arrIni = str_split($ini, 1);
					foreach($arrIni as $type) {
						if(strtoupper($type) === 'G') {
							$_REQUEST = array_merge($_REQUEST, $_GET);
						}elseif(strtoupper($type) === 'P') { 
							$_REQUEST = array_merge($_REQUEST, $_POST);
						}
					}
				}
            }
		}
	}

	public function postDispatch(\Yaf\Request_Abstract $request, \Yaf\Response_Abstract $response) {
	}

	public function dispatchLoopShutdown(\Yaf\Request_Abstract $request, \Yaf\Response_Abstract $response) {
	}
}
