AzuraCast/src/Controller/Admin/AbstractAdminCrudController...

77 lines
1.8 KiB
PHP
Raw Normal View History

<?php
2021-07-19 05:53:45 +00:00
declare(strict_types=1);
namespace App\Controller\Admin;
use App\Exception\NotFoundException;
use App\Form\EntityForm;
use App\Http\ServerRequest;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ObjectRepository;
abstract class AbstractAdminCrudController
{
protected EntityManagerInterface $em;
protected string $entity_class;
protected ObjectRepository $record_repo;
protected string $csrf_namespace;
2021-04-23 05:24:12 +00:00
public function __construct(
protected EntityForm $form
) {
$this->em = $form->getEntityManager();
$this->entity_class = $form->getEntityClass();
$this->record_repo = $form->getEntityRepository();
}
/**
* @param ServerRequest $request
2021-07-19 05:53:45 +00:00
* @param int|string|null $id
*
*/
2021-07-19 05:53:45 +00:00
protected function doEdit(ServerRequest $request, int|string $id = null): object|bool|null
{
$record = $this->getRecord($id);
return $this->form->process($request, $record);
}
/**
2021-07-19 05:53:45 +00:00
* @param int|string|null $id
*/
2021-07-19 05:53:45 +00:00
protected function getRecord(int|string $id = null): ?object
{
if (null === $id) {
return null;
}
$record = $this->record_repo->find($id);
if (!$record instanceof $this->entity_class) {
throw new NotFoundException(__('Record not found.'));
}
return $record;
}
2019-09-04 18:00:51 +00:00
/**
* @param ServerRequest $request
* @param int|string $id
* @param string $csrf
2019-09-04 18:00:51 +00:00
*/
protected function doDelete(ServerRequest $request, int|string $id, string $csrf): void
2019-09-04 18:00:51 +00:00
{
$request->getCsrf()->verify($csrf, $this->csrf_namespace);
2019-09-04 18:00:51 +00:00
$record = $this->getRecord($id);
2019-09-04 18:00:51 +00:00
if ($record instanceof $this->entity_class) {
$this->em->remove($record);
$this->em->flush();
}
}
}