<?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  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace AppBundle\Handler;

use AppBundle\Database\Session as Database;
use AppBundle\Entity\Session as SessionEntity;
use Psr\Log\LoggerInterface;

class UserIdentifierValidate
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var Database
     */
    private $database;

    /**
     * UserIdentifierValidate constructor.
     * @param LoggerInterface $logger
     * @param Database $database
     */
    public function __construct(LoggerInterface $logger, Database $database)
    {
        $this->logger = $logger;
        $this->database = $database;
    }

    /**
     * @param string $userIdentifier
     * @param string|bool $username
     * @return SessionEntity|null
     */
    public function validate($userIdentifier, $username = false)
    {
        $rows = $this->database->findByUserIdentifier($userIdentifier);

        $rows = false === $username ? $rows : array_filter($rows, function(SessionEntity $session) use ($username) {
            return $session->getUsername() === $username;
        });

        return 0 < count($rows) ? reset($rows) : null;
    }
}