<?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\DbLogBundle\Processor;

use LifeStyle\Tools\DbLogBundle\ProcessDetailsInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

/**
 * Class ProcessDetails
 *
 * @copyright  2017 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package LifeStyle\Tools\DbLogBundle\Processor
 */
class ProcessDetails implements ProcessDetailsInterface
{
    /**
     * @var TokenStorageInterface
     */
    private $securityTokenStorage;

    /**
     * @var string
     */
    private $username;

    /**
     * ProcessDetails constructor.
     * @param TokenStorageInterface $securityTokenStorage
     */
    public function __construct(TokenStorageInterface $securityTokenStorage)
    {
        $this->securityTokenStorage = $securityTokenStorage;
    }

    /**
     * Get currently logged in username or username on login failure
     *
     * @return string
     */
    public function getUsername()
    {
        // cli process - no username available
        if (php_sapi_name() === 'cli') {
            return 'CLI';
        }

        // Try to get username from current session
        if (null === $this->username) {
            $token = $this->securityTokenStorage->getToken();
            if ($token) {
                $user = $token->getUser();
                if (is_object($user)) {
                    $this->username = $user->getUsername();
                }
            }
        }

        return null !== $this->username ? $this->username : 'not set';
    }
}
