<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin;

use Admin\Data\Common;
use Admin\Data\Config;
use Laminas\Log\Logger;
use Laminas\Log\Writer\Stream;
use Laminas\Mvc\MvcEvent;
use Laminas\Session\SessionManager;

class Module
{
    public function getConfig()
    {
        return include __DIR__ . '/../config/module.config.php';
    }

    public function onBootstrap(MvcEvent $event)
    {
        //时区设置
        $nowTimeZone = Common::configValue('base', 'config')['website_timezone'];
        date_default_timezone_set($nowTimeZone?:Config::SHOP_TIME_ZONE);

        //第一时间启用会话配置
        $sessionManager = $event->getApplication()->getServiceManager()->get(SessionManager::class);
        $sessionManager->start();

        $eventManager = $event->getApplication()->getEventManager();
        //错误日志记录
        $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, [$this, 'onError'], 99);
    }

    /**
     * 错误日志记录
     * @param MvcEvent $event
     */
    public function onError(MvcEvent $event)
    {
        $exception = $event->getParam('exception');
        if($exception != null) {
            $exceptionName = $exception->getMessage();
            $file = $exception->getFile();
            $line = $exception->getLine();
            $stackTrace = $exception->getTraceAsString();

            $errorMessage = $event->getError();
            $controllerName = $event->getController();

            $body = '';
            if(isset($_SERVER['REQUEST_URI'])) {
                $body .= "Request URI: " . $_SERVER['REQUEST_URI'] . "\n";
            }
            $body .= "Controller: $controllerName\n";
            $body .= "Error message: $errorMessage\n";
            $body .= "Exception: $exceptionName\n";
            $body .= "File: $file\n";
            $body .= "Line: $line\n";
            $body .= "Stack trace:\n" . $stackTrace."\n\n";

            $log     = new Logger();
            $errorLog= new Stream('./data/error/'.date("Y-m-d").'_error.log');
            $log->addWriter($errorLog)->err($body);
        }

    }
}