<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace LifeStyle\Tools\ElkLogFormatterBundle\Monolog\Processor;

/**
 * Class TrackId
 * @package LifeStyle\Tools\ElkLogFormatterBundle\Monolog\Processor
 */
final class TrackId
{
    /**
     * @var string
     */
    protected $trackId;

    /**
     * TrackId constructor.
     * @param null $trackId
     */
    public function __construct($trackId = null)
    {
        if (null === $trackId) {
            $this->trackId = substr(md5(uniqid(rand(), true)), 0, 10);
        } else {
            $this->trackId = $trackId;
        }
    }

    /**
     * @return string
     */
    public function getTrackId()
    {
        return $this->trackId;
    }

    /**
     * @param string $trackId
     * @return TrackId
     */
    public function setTrackId($trackId)
    {
        $this->trackId = $trackId;
        return $this;
    }

    /**
     * @param array $record
     * @return array
     */
    public function processRecord(array $record)
    {
        // Remove any passwords from message
        $record['message'] = preg_replace('#<Password>.*</Password>#Ui', '<Password>***</Password>',
            $record['message']);

        // Add track-id
        $record['extra']['token'] = $this->getTrackId();

        return $record;
    }

    /**
     * @param array $record
     * @return array
     */
    public function __invoke(array $record)
    {
        $record['extra']['token'] = $this->getTrackId();
        return $record;
    }
}
