static method fromFormData added to Paste class

This commit is contained in:
mitsuha_s 2023-07-22 17:07:06 +03:00
parent f2072b9b10
commit c164ed446b
3 changed files with 21 additions and 19 deletions

View file

@ -24,23 +24,9 @@ class PasteController extends AbstractController
$form->handleRequest($request); $form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() && $form->isValid()) {
$pasteData = $form->getData(); $pasteData = $form->getData();
$pasteData->ip = $request->getClientIp();
$secret = null; $paste = Paste::fromFormData($pasteData);
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
);
$pasteRepository->save($paste); $pasteRepository->save($paste);
return $this->redirectToRoute($request->attributes->get('_route')); return $this->redirectToRoute($request->attributes->get('_route'));

View file

@ -20,6 +20,7 @@ class PasteFormData
public string $author = 'anonymous'; public string $author = 'anonymous';
#[Assert\Type(\DateTimeImmutable::class)] #[Assert\Type(\DateTimeImmutable::class)]
public ?\DateTimeImmutable $expirationDate; public ?\DateTimeImmutable $expirationDate;
public string $ip;
public function __construct(?Paste $paste=null) public function __construct(?Paste $paste=null)
{ {

View file

@ -2,7 +2,7 @@
declare(strict_types = 1); declare(strict_types = 1);
namespace App\Entity; namespace App\Entity;
use App\DTO\PasteFormData;
use App\Repository\PasteRepository; use App\Repository\PasteRepository;
use Doctrine\DBAL\Types\Types; use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
@ -15,7 +15,7 @@ class Paste
#[ORM\Column] #[ORM\Column]
public readonly int $id; public readonly int $id;
public function __construct( private function __construct(
#[ORM\Column(type: 'text', nullable: false)] #[ORM\Column(type: 'text', nullable: false)]
public readonly string $text, public readonly string $text,
#[ORM\Column(length: 25, nullable: true)] #[ORM\Column(length: 25, nullable: true)]
@ -35,4 +35,19 @@ class Paste
#[ORM\Column(length: 40, nullable: true)] #[ORM\Column(length: 40, nullable: true)]
public readonly ?string $secret, public readonly ?string $secret,
) {} ) {}
}
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,
);
}
}