<?php

/**
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected 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
 * @version    $Id:$
 * @link       http://www.life-style.de
 */

namespace Sso\ApiBundle\Api\Logger;

use Sso\ApiBundle\Api\Exception\Type\Api as ApiException;

/**
 * Class TrackId
 * @package Sso\ApiBundle\Api\Logger
 */
class TrackId
{

    /**
     * Track id
     *
     * @var string
     */
    protected $_trackId;

    /**
     * Constructor
     */
    public function __construct()
    {
        ApiException::setTrackId($this->getId());
    }

    /**
     * Process record for logger
     *
     * @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->getId();

        return $record;
    }

    /**
     * Get track id
     *
     * @return string
     */
    public function getId()
    {
        return null !== $this->_trackId ? $this->_trackId : ($this->_trackId = $this->_generateTrackId());
    }

    /**
     * Generate track id
     *
     * @return string
     */
    protected function _generateTrackId()
    {
        return substr(md5(uniqid(rand(), true)), 0, 10);
    }

}
