From c164ed446be9738cddf71f148b7a20c23f096883 Mon Sep 17 00:00:00 2001 From: mitsuha_s Date: Sat, 22 Jul 2023 17:07:06 +0300 Subject: [PATCH] static method fromFormData added to Paste class --- src/Controller/PasteController.php | 18 ++---------------- src/DTO/PasteFormData.php | 1 + src/Entity/Paste.php | 21 ++++++++++++++++++--- 3 files changed, 21 insertions(+), 19 deletions(-) diff --git a/src/Controller/PasteController.php b/src/Controller/PasteController.php index 368ea79..5b37231 100644 --- a/src/Controller/PasteController.php +++ b/src/Controller/PasteController.php @@ -24,23 +24,9 @@ class PasteController extends AbstractController $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $pasteData = $form->getData(); + $pasteData->ip = $request->getClientIp(); - $secret = null; - if ($pasteData->private) { - $secret = hash('sha1', random_bytes(25)); - } - - $paste = new Paste( - $pasteData->text, - $pasteData->language, - $pasteData->description, - $pasteData->filename, - $pasteData->author, - new \DateTimeImmutable(), - $pasteData->expirationDate, - $request->getClientIp(), - $secret - ); + $paste = Paste::fromFormData($pasteData); $pasteRepository->save($paste); return $this->redirectToRoute($request->attributes->get('_route')); diff --git a/src/DTO/PasteFormData.php b/src/DTO/PasteFormData.php index 2ccc362..52e0a99 100644 --- a/src/DTO/PasteFormData.php +++ b/src/DTO/PasteFormData.php @@ -20,6 +20,7 @@ class PasteFormData public string $author = 'anonymous'; #[Assert\Type(\DateTimeImmutable::class)] public ?\DateTimeImmutable $expirationDate; + public string $ip; public function __construct(?Paste $paste=null) { diff --git a/src/Entity/Paste.php b/src/Entity/Paste.php index 54c36dc..2e3d3e6 100644 --- a/src/Entity/Paste.php +++ b/src/Entity/Paste.php @@ -2,7 +2,7 @@ declare(strict_types = 1); namespace App\Entity; - +use App\DTO\PasteFormData; use App\Repository\PasteRepository; use Doctrine\DBAL\Types\Types; use Doctrine\ORM\Mapping as ORM; @@ -15,7 +15,7 @@ class Paste #[ORM\Column] public readonly int $id; - public function __construct( + private function __construct( #[ORM\Column(type: 'text', nullable: false)] public readonly string $text, #[ORM\Column(length: 25, nullable: true)] @@ -35,4 +35,19 @@ class Paste #[ORM\Column(length: 40, nullable: true)] public readonly ?string $secret, ) {} -} \ No newline at end of file + + public static function fromFormData(PasteFormData $pasteFormData): Paste + { + return new self( + $pasteFormData->text, + $pasteFormData->language, + $pasteFormData->description, + $pasteFormData->filename, + $pasteFormData->author, + new \DateTimeImmutable(), + $pasteFormData->expirationDate, + $pasteFormData->ip, + $pasteFormData->private ? \hash('sha1', \random_bytes(25)) : null, + ); + } +}