<?php

namespace App\Security;

use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class ApiKeyUserProvider implements UserProviderInterface
{
    public function __construct(ObjectManager $manager)
    {
        $this->manager = $manager;
    }

    public function getUsernameForApiKey($apiKey)
    {
        $user = $this->manager->getRepository('App\Entity\User')
            ->findOneByApiKey($apiKey);

        if (!$user) {
            return null;
        }

        return $user->getUsername();
    }

    public function loadUserByUsername($username)
    {
        return $this->manager->getRepository('App\Entity\User')
            ->findOneByUsername($username);
    }

    public function refreshUser(UserInterface $user)
    {
        // this is used for storing authentication in the session
        // but in this example, the token is sent in each request,
        // so authentication can be stateless. Throwing this exception
        // is proper to make things stateless
        throw new UnsupportedUserException();
    }

    public function supportsClass($class)
    {
        return 'Symfony\Component\Security\Core\User\User' === $class;
    }
}
