<?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 Sso\WebserviceBundle\Api\Logger;

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

/**
 * Class TrackId
 * @package Sso\WebserviceBundle\Api\Logger
 */
class TrackId
{
    /**
     * @var string
     */
    protected $_trackId;

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

    /**
     * @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']);
        $record['message'] = preg_replace('#<NewPassword>.*</NewPassword>#Ui', '<NewPassword>***</NewPassword>', $record['message']);
        $record['message'] = preg_replace('#<NewPasswordConfirm>.*</NewPasswordConfirm>#Ui', '<NewPasswordConfirm>***</NewPasswordConfirm>', $record['message']);

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

        return $record;
    }

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

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