<?php

declare(strict_types=1);

namespace Meibuyu\Micro\Amqp\Producer;

use Exception;
use Hyperf\Amqp\Annotation\Producer;
use Hyperf\Amqp\Message\ProducerMessage;
use Meibuyu\Micro\Exceptions\HttpResponseException;
use Meibuyu\Micro\Model\Auth;

/**
 * @Producer(exchange="micro", routingKey="exception-log")
 */
class ExceptionLogProducer extends ProducerMessage
{

    public function __construct($data)
    {
        try {
            $data['operator'] = Auth::user()['name'];
        } catch (HttpResponseException $e) {
            put_log('获取操作人失败; ' . $e->getMessage(), 'ExceptionLogProducer.log');
        }
        // 排除依赖包文件和运行缓存文件
        if (strpos($data['file'], '/vendor/') === false && strpos($data['file'], '/runtime/') === false) {
            try {
                exec("git blame -L {$data['line']},{$data['line']} {$data['file']}", $output);
                if (!empty($output[0]) && is_string($output[0])) {
                    preg_match('/(?<=\()[^ ]+/', $output[0], $matches);
                    if (!empty($matches[0])) {
                        $data['coder'] = $matches[0];
                    }
                }
            } catch (Exception $e) {
                put_log('获取编码人失败; ' . $e->getMessage(), 'ExceptionLogProducer.log');
            }
        }
        $this->payload = $data;
    }

}