Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
declare(strict_types=1);
...
use Symfony\Component\Validator\Constraints as Assert;
class Command
{
/**
* @var string
*
* @Assert\NotBlank(message="Нельзя создать пустой тег")
*/
public $name;
/**
* @var string
*
* @Assert\NotBlank(message="У тега должна быть картинка.")
*/
public $image;
}
<?php
...
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;
class Form extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, ['label' => 'Имя'])
->add('image', FileType::class, ['label' => 'Изображение']);
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Command::class
]);
}
}
<?php
..
class Handler
{
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var TagRepository
*/
private $tags;
public function __construct(EntityManagerInterface $em, TagRepository $tagsRepository)
{
$this->em = $em;
$this->tags = $tagsRepository;
}
/**
* @param Command $command
* @throws \Exception
*/
public function handle(Command $command): void
{
if ($this->tags->findOneBy(['name' => $command->name])) {
throw new \DomainException('Такой тег уже существует');
}
$tag = new Tag($command->name, $command->image);
$this->tags->add($tag);
$this->em->flush();
}
}
<?php
...
class TagController extends AbstractController
{
public function create(Request $request, Create\Handler $handler, FileUploader $fileUploader): Response
{
$command = new Create\Command();
$form = $this->createForm(Create\Form::class, $command);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** @var UploadedFile $file */
$file = $form->get('image')->getData();
$uploadedFile = $fileUploader->upload($file, self::DIR);
$command->image = $uploadedFile->getFullName();
try {
$handler->handle($command);
$this->flashMessageService->success('Тег создан');
return $this->redirectToRoute('admin_tags_index');
} catch (\DomainException $exception) {
$this->flashMessageService->error($exception->getMessage());
return $this->redirectToRoute('admin_tags_index');
}
}
return $this->render('admin/work/management/tags/create.html.twig', [
'form' => $form->createView()
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment