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

Redimensionner les images #41

Closed FabRiviere closed 1 year ago

FabRiviere commented 1 year ago
FabRiviere commented 1 year ago

Ajout d'un nouvel état au workflow :

framework:
    workflows: 
        comment:
            type: state_machine
            audit_trail:
                enabled: "%kernel.debug%"
            marking_store:
                type: 'method'
                property: 'state'
            supports:
                - App\Entity\Comment
            initial_marking: submitted
            places:
                - submitted
                - ham
                - potential_spam
                - spam
                - rejected
                - ready
                - published
            transitions:
                accept:
                    from: submitted
                    to: ham
                might_be_spam:
                    from: submitted
                    to: potential_spam
                reject_spam:
                    from: submitted
                    to: spam
                publish:
                    from: potential_spam
                    to: ready
                reject:
                    from: potential_spam
                    to: rejected
                publish_ham:
                    from: ham
                    to: ready
                reject_ham:
                    from: ham
                    to: rejected
                optimize:
                    from: ready
                    to: published

Générer une représentation visuelle de la configuration du nouveau workflow :

symfony console workflow:dump comment | dot -Tpng -o workflow.png

Optimiser les images avec Imagine

Installation du package imagine :

symfony composer req "imagine/imagine:^1.2"

Création d'un service ImageOptimizer.php :

<?php

namespace App\Service;

use Imagine\Image\Box;
use Imagine\Gd\Imagine;

class ImageOptimizer
{
    private const MAX_WIDTH = 200;
    private const MAX_HEIGHT = 150;

    private $imagine;

    public function __construct()
    {
        $this->imagine = new Imagine();
    }

    public function resize(string $filename): void
    {
        list($iwidth, $iheight) = getimagesize($filename);
        $ratio = $iwidth / $iheight;
        $width = self::MAX_WIDTH;
        $height = self::MAX_HEIGHT;
        if ($width / $height > $ratio) {
            $width = $height * $ratio;
        } else {
            $height = $width / $ratio;
        }

        $photo = $this->imagine->open($filename);
        $photo->resize(new Box($width, $height))->save($filename);
    }
}

Ajout d'une nouvelle étape au workflow :

Modification du fichier CommentmessageHandler.php

<?php

namespace App\MessageHandler;

use App\Service\SpamChecker;
use Psr\Log\LoggerInterface;
use App\Message\CommentMessage;
use App\Service\ImageOptimizer;
use App\Repository\CommentRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Workflow\WorkflowInterface;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

#[AsMessageHandler]
class CommentMessageHandler
{
    public function __construct(
        private EntityManagerInterface $entityManager,
        private SpamChecker $spamChecker,
        private CommentRepository $commentRepository,
        private MessageBusInterface $bus,
        private WorkflowInterface $commentStateMachine,
        private ImageOptimizer $imageOptimizer,
        #[Autowire('%photo_dir%')] private string $photoDir,
        private ?LoggerInterface $logger = null,
    ) {        
    }

    public function __invoke(CommentMessage $message)
    {
        $comment = $this->commentRepository->find($message->getId());
        if (!$comment) {
            return;
        }

        // ! Mis en commentaire pour utilisation du WorkflowInterface
        // if (2 === $this->spamChecker->getSpamScore($comment, $message->getContext())) {
        //     $comment->setState('spam');
        // } else {
        //     $comment->setState('published');
        // }

        // $this->entityManager->flush();

        //! Utilisation du Workflow
        if ($this->commentStateMachine->can($comment, 'accept')) {
            $score = $this->spamChecker->getSpamScore($comment, $message->getContext());
            $transition = match ($score) {
                2 => 'reject_spam',
                1 => 'might_be_spam',
                default => 'accept',
            };
            $this->commentStateMachine->apply($comment, $transition);
            $this->entityManager->flush();
            $this->bus->dispatch($message);
        } elseif ($this->commentStateMachine->can($comment, 'optimize')) {
            if ($comment->getPhotoFilename()) {
                $this->imageOptimizer->resize($this->photoDir.'/'.$comment->getPhotoFilename());
            }
            $this->commentStateMachine->apply($comment, 'optimize');
            $this->entityManager->flush();
        }elseif ($this->logger) {
            $this->logger->debug('Dropping comment message', ['comment' => $comment->getId(), 'state' => $comment->getState()]);
        }
    }
}

Modification du fichier platform/services.yaml :

files:
    type: network-storage:2.0
    disk: 256

Modification du .platform.app.yaml :

mounts:
    "/var": { source: local, source_path: var }
    "/public/uploads": { source: service, service: files, source_path: uploads}