<?php

namespace Lc\SovBundle\Repository\User;

use App\Entity\User\User;
use Doctrine\Persistence\ManagerRegistry;
use Lc\SovBundle\Repository\AbstractRepository;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserInterface as SfUserInterface;

class UserRepository extends AbstractRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, User::class);
    }

    /**
     * Used to upgrade (rehash) the user's password automatically over time.
     */
    public function upgradePassword(SfUserInterface $user, string $newEncodedPassword): void
    {
        if (!$user instanceof SfUserInterface) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user)));
        }

        $user->setPassword($newEncodedPassword);
        $this->_em->update($user);
        $this->_em->flush();
    }

    public function findByRole($role)
    {
        return $this->createQueryBuilder('u')
            ->andWhere('u.roles LIKE :role')
            ->setParameter('role', '%' . $role . '%')
            ->getQuery()
            ->getResult();
    }
}
