Symfony 4.4. Add the Admin role with make:command to a existing user

I try to add the admin role with a make:command to a existing user.
The problem: [ERROR] There is no user with that email address.

What i have done.

Creating user with easyAdminBundle.That’s ok

My entity :

 namespace AppEntity;

use CocurSlugifySlugify;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;
use DoctrineORMMappingHasLifecycleCallbacks;
use SymfonyComponentValidatorConstraints as Assert;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity;

/**
 * @ORMEntity(repositoryClass="AppRepositoryUserRepository")
 * @ORMHasLifecycleCallbacks()
 * @UniqueEntity("email")
 */
class User implements UserInterface
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     */
    private $id;

    /**
     * @ORMColumn(type="string", length=180, unique=true)
     * @AssertEmail(message="Veuillez rentrer une adresse email valide")
     */
    private $email;

    /**
     * @ORMColumn(type="json")
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORMColumn(type="string")
     */
    private $password;



    /**
     * @ORMColumn(type="string", length=255)
     */
    private $lastName;

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $firstName;

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $slug;


    /**
     * @ORMColumn(type="string", length=255)
     */
    private $avatarImage;

    /**
     * @ORMOneToMany(targetEntity="AppEntityArticle", mappedBy="author", orphanRemoval=true)
     */
    private $articles;

    public function __construct()
    {
        $this->articles = new ArrayCollection();
    }


    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string) $this->email;
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = "ROLE_USER";

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    public function addRoles(string $roles): self
    {
        if (!in_array($roles, $this->roles)) {
            $this->roles[] = $roles;
        }

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getPassword(): string
    {
        return (string) $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }



    public function getLastName(): ?string
    {
        return $this->lastName;
    }

    public function setLastName(string $lastName): self
    {
        $this->lastName = $lastName;

        return $this;
    }

    public function getFirstName(): ?string
    {
        return $this->firstName;
    }

    public function setFirstName(string $firstName): self
    {
        $this->firstName = $firstName;

        return $this;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

    public function getAvatarImage(): ?string
    {
        return $this->avatarImage;
    }

    public function setAvatarImage(string $avatarImage): self
    {
        $this->avatarImage = $avatarImage;

        return $this;
    }

    /**
     *@ORMPrePersist
     *@ORMPreUpdate
     */
    public function initializeSlug(){
        if(empty($this->slug)){
            $slugify=new Slugify();
            $this->slug=$slugify->slugify($this->lastName .' '.$this->firstName);
        }
    }

    /**
     * @return Collection|Article[]
     */
    public function getArticles(): Collection
    {
        return $this->articles;
    }

    public function addArticle(Article $article): self
    {
        if (!$this->articles->contains($article)) {
            $this->articles[] = $article;
            $article->setAuthor($this);
        }

        return $this;
    }

    public function removeArticle(Article $article): self
    {
        if ($this->articles->contains($article)) {
            $this->articles->removeElement($article);
            // set the owning side to null (unless already changed)
            if ($article->getAuthor() === $this) {
                $article->setAuthor(null);
            }
        }

        return $this;
    }
}

Creating a command : php bin/console make:command

// src/Command/UserPromoteCommand.php

namespace AppCommand;

use AppEntityUser;
use DoctrineCommonPersistenceManagerRegistry;
use DoctrineORMEntityManagerInterface;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleStyleSymfonyStyle;
use SymfonyComponentConsoleInputInputArgument;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;

class UserPromoteCommand extends Command
{
    protected static $defaultName = 'app:user:promote';

    private $manager;

    public function __construct(EntityManagerInterface $manager)
    {
        $this->manager = $manager;

        parent::__construct();
    }

    protected function configure()
    {
        $this
            ->setDescription('Promote a user by adding him a new roles.')
            ->addArgument('email', InputArgument::REQUIRED, 'Email address of the user you want to promote.')
            ->addArgument('roles', InputArgument::REQUIRED, 'The roles you want to add to the user.')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $email = $input->getArgument('email');
        $roles = $input->getArgument('roles');

        $userRepository = $this->manager->getRepository(User::class);
        $user = $userRepository->find($email);

        if ($user) {
            $user->addRoles($roles);
            $this->manager->flush();

            $io->success('The roles has been successfully added to the user.');
        } else {
            $io->error('There is no user with that email address.');
        }

        return 0;
    }
}

Result of php bin/console

app:user:promote [email protected] ROLE_ADMIN : [ERROR] There is no user with that email address.

What is the problem? EntityManagerInterface maybe? I don’t know.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *