<?php

namespace App\Plugins;

use App\Exception\ExceptionErrorCatch;
use Helpers\DebugLog;
use Api\PhpUtils\Log\FileLog;

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 数字表示级别 )
            if(!empty($_REQUEST['__debug'])) {
                $debug_level = intval(substr($_REQUEST['__debug'], -1));
            } else {
                $debug_level = 1;
            }
            define('DEBUG_LEVEL', $debug_level );

			//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) {
		// application/json形式，仅处理$_POST, 不整合$_GET
		if($request->isPost()
			&& $request->getServer('CONTENT_TYPE') == 'application/json') {

		    $jsonPost = file_get_contents("php://input");
            if(empty($jsonPost)) {
                $_POST = [];
                return true;
            }

            $_POST = json_decode($jsonPost, true);

            if(!is_array($_POST)) {
                $_POST = [];
                FileLog::error('bp-gateway', 'json decode error raw:' . $jsonPost);
            }

            $_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) {
	}
}
