<?php

namespace Velis\Bpm\ErrorNotification;

use DateTime;
use DateTimeZone;
use Exception;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 */
class ErrorLogLineParser
{
    /**
     * @param string $line
     * @return array|null
     * @throws Exception
     */
    public function parseLine(string $line)
    {
        preg_match_all('/^(([0-9a-z\-]+) \|\| )?\[(.*)\] PHP.* (error|deprecated):(.+)/i', $line, $matches);

        if (!isset($matches[3]) || !isset($matches[3][0]) || !$matches[3][0]) {
            return null;
        }

        preg_match_all('/\w+\/\w+(\/\w+)?$/', $matches[3][0], $timezoneMatches);
        if ($timezoneMatches[0][0]) {
            $timezone = new DateTimeZone($timezoneMatches[0][0]);
            $dateString = trim(str_replace([$timezoneMatches[0][0], 'posix/'], '', $matches[3][0]));
            $date = DateTime::createFromFormat('d-M-Y H:i:s', $dateString, $timezone);
        } else {
            $date = new DateTime($matches[3][0]);
        }

        return [
            'datetime' => $date,
            'type' => $matches[4][0],
            'message' => trim($matches[5][0]),
            'server' => $matches[2][0] ?: null,
        ];
    }
}
