FabRiviere / Livre_Or_Symfony

Développement du projet concernant un livre d'or sur les conférences. Projet du livre Symfony 6.
0 stars 0 forks source link

Asynchrone - Création d'un état (statut) sur les commentaires #37

Closed FabRiviere closed 1 year ago

FabRiviere commented 1 year ago
FabRiviere commented 1 year ago

Modification de l'entité Comment avec ajout de la propriété "state" :

symfony console make:entity Comment

Ajout de la proprité "state" , string, 255, not null.

Dans le fichier Entity/Comment.php , on modifie le champ pour lui attribué "submitted" comme valeur par défaut.

#[ORM\Column(length: 255, options: ['default' => 'submitted'])]
    private ?string $state = 'submitted';

Créer une migration :

symfony console make:migration

Modification du fichier de migration généré :

public function up(Schema $schema): void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->addSql('ALTER TABLE comment ADD state VARCHAR(255) DEFAULT \'submitted\' NOT NULL');
        $this->addSql("UPDATE comment SET state='published'");
    }

Modification du CommentRepository.php :

public function getCommentPaginator(Conference $conference, int $offset): Paginator
    {
        $query = $this->createQueryBuilder('c')
            ->andWhere('c.conference = :conference')
            ->andWhere('c.state = :state')
            ->setParameter('conference', $conference)
            ->setParameter('state', 'published')
            ->orderBy('c.createdAt', 'DESC')
            ->setMaxResults(self::PAGINATOR_PER_PAGE)
            ->setFirstResult($offset)
            ->getQuery()
        ;

        return new Paginator($query);
    }

Modification du CommentCrudController.php :

public function configureFields(string $pageName): iterable
    {
        yield AssociationField::new('conference');
        yield TextField::new('author');
        yield EmailField::new('email');
        yield TextareaField::new('text')->hideOnIndex();
        // yield TextField::new('photoFilename')->onlyOnIndex();
        yield ImageField::new('photoFilename')
                    ->setBasePath('/uploads/photos')
                    ->setLabel('Photo')
                    ->onlyOnIndex()
        ;
        yield TextField::new('state');

        $createdAt = DateTimeField::new('createdAt')->setFormTypeOptions([
            'years' => range(date('Y'), date('Y') + 5),
            'widget' => 'single_text',
        ]);
        if (Crud::PAGE_EDIT === $pageName) {
            yield $createdAt->setFormTypeOption('disabled', true);
        // } else {
        //     yield $createdAt;
        }
    }

Modification du AppFixtures.php :

On en profite pour ajouter un commentaire sans renseigner son statut.

public function load(ObjectManager $manager): void
    {
        $amsterdam = new Conference();
        $amsterdam->setCity('Amsterdam');
        $amsterdam->setYear('2019');
        $amsterdam->setIsInternational(true);
        $manager->persist($amsterdam);

        $paris = new Conference();
        $paris->setCity('Paris');
        $paris->setYear('2020');
        $paris->setIsInternational(false);
        $manager->persist($paris);

        $comment1 = new Comment();
        $comment1->setConference($amsterdam);
        $comment1->setAuthor('Fabien');
        $comment1->setEmail('fabien@example.com');
        $comment1->setText('This is a great conference.');
        $comment1->setState('published');
        $manager->persist($comment1);

        $comment2 = new Comment();
        $comment2->setConference($amsterdam);
        $comment2->setAuthor('Lucas');
        $comment2->setEmail('lucas@example.com');
        $comment2->setText('I think this one is going to be moderated.');
        $manager->persist($comment2);

        $admin = new Admin();
        $admin->setRoles(['ROLE_ADMIN']);
        $admin->setUsername('Fabsolo');
        $admin->setEmail('fabsolo@email.fr');
        $admin->setPassword($this->passwordHasherFactory->getPasswordHasher(Admin::class)->hash('azerty'));
        $admin->setFirstname('Fab');
        $admin->setLastname('Solo');
        $admin->setIsVerified(1);
        $manager->persist($admin);

        $manager->flush();
    }

Modification du ConferenceControllerTest.php :

public function testCommentSubmission()
    {
        $client = static::createClient();
        $client->request('GET', '/conference/amsterdam-2019');
        $client->submitForm('Submit', [
            'comment_form[author]' => 'Fabien',
            'comment_form[text]' => 'Some feedback from an automated functional test',
            'comment_form[email]' => $email = 'me@automat.ed',
            'comment_form[photo]' => dirname(__DIR__, 2). '/public/images/under-construction.gif',
        ]);
        $this->assertResponseRedirects();

        //! simulate comment validation
        $comment = self::getContainer()->get(CommentRepository::class)->findOneByEmail($email);
        $comment->setState('published');
        self::getContainer()->get(EntityManagerInterface::class)->flush();

        $client->followRedirect();
        $this->assertSelectorExists('div:contains("There are 2 comments")');
    }