Add Art section: upload named images, gallery, delete

- Artwork entity (name, stored filename, original name, mime, size, date)
- /art gallery grid; /art/upload (name + image file, PNG/JPEG/GIF/WebP,
  20M cap); /art/{id}/file streams the image behind auth; /art/{id}/delete
  (CSRF) removes row + file
- files stored under var/uploads/art/ (git-ignored, on the php_var volume
  in Docker), served through a controller so they stay login-gated
- "Art" nav item

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Frank
2026-09-06 16:41:33 +02:00
co-authored by Claude Sonnet 5
parent 1f4b5290b2
commit ed9390319b
8 changed files with 380 additions and 0 deletions
+111
View File
@@ -0,0 +1,111 @@
<?php
namespace App\Controller;
use App\Entity\Artwork;
use App\Form\ArtworkType;
use App\Repository\ArtworkRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class ArtController extends AbstractController
{
public function __construct(
#[Autowire('%kernel.project_dir%/var/uploads/art')]
private readonly string $artDir,
) {
}
#[Route('/art', name: 'app_art', methods: ['GET'])]
public function index(ArtworkRepository $repo): Response
{
return $this->render('art/index.html.twig', [
'artworks' => $repo->findBy([], ['uploadedAt' => 'DESC']),
]);
}
#[Route('/art/upload', name: 'app_art_upload', methods: ['GET', 'POST'])]
public function upload(Request $request, EntityManagerInterface $em): Response
{
$artwork = new Artwork();
$form = $this->createForm(ArtworkType::class, $artwork);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** @var UploadedFile $file */
$file = $form->get('file')->getData();
$ext = $file->guessExtension() ?: 'bin';
$stored = bin2hex(random_bytes(16)).'.'.$ext;
try {
if (!is_dir($this->artDir)) {
mkdir($this->artDir, 0775, true);
}
$file->move($this->artDir, $stored);
} catch (FileException) {
$this->addFlash('error', 'Could not store the uploaded file.');
return $this->redirectToRoute('app_art_upload');
}
$artwork
->setFilename($stored)
->setOriginalName($file->getClientOriginalName())
->setMimeType($file->getClientMimeType())
->setSize((int) (@filesize($this->artDir.'/'.$stored) ?: 0));
$em->persist($artwork);
$em->flush();
$this->addFlash('success', sprintf('Uploaded "%s".', $artwork->getName()));
return $this->redirectToRoute('app_art');
}
return $this->render('art/upload.html.twig', ['form' => $form]);
}
#[Route('/art/{id}/file', name: 'app_art_file', requirements: ['id' => '\d+'], methods: ['GET'])]
public function serve(Artwork $artwork): BinaryFileResponse
{
$path = $this->artDir.'/'.$artwork->getFilename();
if (!is_file($path)) {
throw $this->createNotFoundException('File missing on disk.');
}
$response = new BinaryFileResponse($path);
$response->headers->set('Content-Type', $artwork->getMimeType());
$response->setContentDisposition(
HeaderUtils::DISPOSITION_INLINE,
$artwork->getOriginalName() ?? $artwork->getFilename(),
);
$response->setPrivate();
return $response;
}
#[Route('/art/{id}/delete', name: 'app_art_delete', requirements: ['id' => '\d+'], methods: ['POST'])]
public function delete(Request $request, Artwork $artwork, EntityManagerInterface $em): Response
{
if ($this->isCsrfTokenValid('delete-art-'.$artwork->getId(), (string) $request->request->get('_token'))) {
$path = $this->artDir.'/'.$artwork->getFilename();
if (is_file($path)) {
@unlink($path);
}
$em->remove($artwork);
$em->flush();
$this->addFlash('success', sprintf('Deleted "%s".', $artwork->getName()));
}
return $this->redirectToRoute('app_art');
}
}
+113
View File
@@ -0,0 +1,113 @@
<?php
namespace App\Entity;
use App\Repository\ArtworkRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Entity(repositoryClass: ArtworkRepository::class)]
#[ORM\Table(name: 'artwork')]
class Artwork
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 200)]
#[Assert\NotBlank]
private string $name = '';
/** Randomised on-disk name under var/uploads/art/. */
#[ORM\Column(length: 120)]
private string $filename = '';
#[ORM\Column(length: 255, nullable: true)]
private ?string $originalName = null;
#[ORM\Column(length: 100)]
private string $mimeType = 'application/octet-stream';
#[ORM\Column(type: Types::INTEGER)]
private int $size = 0;
#[ORM\Column(type: Types::DATETIME_IMMUTABLE)]
private \DateTimeImmutable $uploadedAt;
public function __construct()
{
$this->uploadedAt = new \DateTimeImmutable();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function setName(string $name): static
{
$this->name = $name;
return $this;
}
public function getFilename(): string
{
return $this->filename;
}
public function setFilename(string $filename): static
{
$this->filename = $filename;
return $this;
}
public function getOriginalName(): ?string
{
return $this->originalName;
}
public function setOriginalName(?string $originalName): static
{
$this->originalName = $originalName;
return $this;
}
public function getMimeType(): string
{
return $this->mimeType;
}
public function setMimeType(string $mimeType): static
{
$this->mimeType = $mimeType;
return $this;
}
public function getSize(): int
{
return $this->size;
}
public function setSize(int $size): static
{
$this->size = $size;
return $this;
}
public function getUploadedAt(): \DateTimeImmutable
{
return $this->uploadedAt;
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace App\Form;
use App\Entity\Artwork;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Image;
use Symfony\Component\Validator\Constraints\NotNull;
class ArtworkType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name', TextType::class, [
'help' => 'Shown in the gallery.',
])
->add('file', FileType::class, [
'label' => 'Image file',
'mapped' => false,
'constraints' => [
new NotNull(message: 'Please choose an image.'),
new Image(
maxSize: '20M',
mimeTypes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp'],
mimeTypesMessage: 'Upload a PNG, JPEG, GIF or WebP image.',
),
],
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(['data_class' => Artwork::class]);
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Repository;
use App\Entity\Artwork;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Artwork>
*/
class ArtworkRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Artwork::class);
}
}