Skip to content

Commit

Permalink
Move DB logic to repositories and use EntityManagerInterface.
Browse files Browse the repository at this point in the history
  • Loading branch information
janbarasek committed Nov 15, 2021
1 parent df8af52 commit 9a35836
Show file tree
Hide file tree
Showing 11 changed files with 177 additions and 119 deletions.
29 changes: 29 additions & 0 deletions src/Announcement/Entity/AnnouncementRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,33 @@

final class AnnouncementRepository extends EntityRepository
{
/**
* @return array<int, array{
* id: int,
* pinned: bool,
* message: string,
* showSince: \DateTime,
* user: array{
* id: int,
* username: string
* }
* }>
*/
public function getFeed(): array
{
/** @phpstan-ignore-next-line */
return $this->createQueryBuilder('topic')
->select('PARTIAL topic.{id, pinned, message, showSince}')
->addSelect('PARTIAL user.{id, username}')
->leftJoin('topic.user', 'user')
->where('topic.parent IS NULL')
->andWhere('topic.active = TRUE')
->andWhere('topic.showSince >= :now')
->andWhere('topic.showUntil < :now OR topic.showUntil IS NULL')
->setParameter('now', date('Y-m-d') . ' 00:00:00')
->orderBy('topic.pinned', 'DESC')
->addOrderBy('topic.showSince', 'DESC')
->getQuery()
->getArrayResult();
}
}
23 changes: 7 additions & 16 deletions src/Api/CmsDashboardEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,17 @@


use Baraja\Cms\Announcement\Entity\Announcement;
use Baraja\Cms\Announcement\Entity\AnnouncementRepository;
use Baraja\Cms\User\Entity\User;
use Baraja\Cms\User\UserManager;
use Baraja\Doctrine\EntityManager;
use Baraja\Localization\Localization;
use Baraja\StructuredApi\BaseEndpoint;
use Doctrine\ORM\EntityManagerInterface;

final class CmsDashboardEndpoint extends BaseEndpoint
{
public function __construct(
private EntityManager $entityManager,
private EntityManagerInterface $entityManager,
private UserManager $userManager,
private Localization $localization,
) {
Expand All @@ -24,22 +25,12 @@ public function __construct(

public function actionFeed(): void
{
/** @var AnnouncementRepository $repository */
$repository = $this->entityManager->getRepository(AnnouncementRepository::class);

$this->sendJson(
[
'feed' => $this->entityManager->getRepository(Announcement::class)
->createQueryBuilder('topic')
->select('PARTIAL topic.{id, pinned, message, showSince}')
->addSelect('PARTIAL user.{id, username}')
->leftJoin('topic.user', 'user')
->where('topic.parent IS NULL')
->andWhere('topic.active = TRUE')
->andWhere('topic.showSince >= :now')
->andWhere('topic.showUntil < :now OR topic.showUntil IS NULL')
->setParameter('now', date('Y-m-d') . ' 00:00:00')
->orderBy('topic.pinned', 'DESC')
->addOrderBy('topic.showSince', 'DESC')
->getQuery()
->getArrayResult(),
'feed' => $repository->getFeed(),
],
);
}
Expand Down
20 changes: 7 additions & 13 deletions src/Api/CmsEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@
use Baraja\Cms\User\Entity\CmsUser;
use Baraja\Cms\User\Entity\User;
use Baraja\Cms\User\Entity\UserResetPasswordRequest;
use Baraja\Cms\User\Entity\UserResetPasswordRequestRepository;
use Baraja\Cms\User\UserManager;
use Baraja\Doctrine\EntityManager;
use Baraja\Markdown\CommonMarkRenderer;
use Baraja\StructuredApi\Attributes\PublicEndpoint;
use Baraja\StructuredApi\BaseEndpoint;
use Baraja\Url\Url;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\NoResultException;
use Nette\Security\AuthenticationException;
Expand All @@ -32,7 +33,7 @@ public function __construct(
private UserManager $userManager,
private CloudManager $cloudManager,
private Settings $settings,
private EntityManager $entityManager,
private EntityManagerInterface $entityManager,
private ContextAccessor $contextAccessor,
private CommonMarkRenderer $commonMarkRenderer,
) {
Expand Down Expand Up @@ -202,18 +203,11 @@ public function postReportProblem(string $locale, string $description, string $u

public function postForgotPasswordSetNew(string $token, string $locale, string $password): void
{
try {
/** @var UserResetPasswordRequest $request */
$request = $this->entityManager->getRepository(UserResetPasswordRequest::class)
->createQueryBuilder('resetRequest')
->select('resetRequest, user')
->leftJoin('resetRequest.user', 'user')
->where('resetRequest.token = :token')
->setParameter('token', $token)
->setMaxResults(1)
->getQuery()
->getSingleResult();
/** @var UserResetPasswordRequestRepository $repository */
$repository = $this->entityManager->getRepository(UserResetPasswordRequestRepository::class);

try {
$request = $repository->getByToken($token);
if ($request->isExpired() === true) {
$this->sendError('Token has been expired.');
}
Expand Down
4 changes: 2 additions & 2 deletions src/Api/CmsInstallEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
use Baraja\BarajaCloud\CloudManager;
use Baraja\Cms\Settings;
use Baraja\Cms\User\Entity\User;
use Baraja\Doctrine\EntityManager;
use Baraja\DynamicConfiguration\Configuration;
use Baraja\DynamicConfiguration\ConfigurationSection;
use Baraja\StructuredApi\Attributes\PublicEndpoint;
use Baraja\StructuredApi\BaseEndpoint;
use Baraja\Url\Url;
use Doctrine\ORM\EntityManagerInterface;
use Nette\Utils\Strings;
use Nette\Utils\Validators;

Expand All @@ -24,7 +24,7 @@ final class CmsInstallEndpoint extends BaseEndpoint


public function __construct(
private EntityManager $entityManager,
private EntityManagerInterface $entityManager,
private CloudManager $cloudManager,
private Settings $settings,
Configuration $configuration,
Expand Down
6 changes: 3 additions & 3 deletions src/Context.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
use Baraja\Cms\User\UserManagerAccessor;
use Baraja\Cms\User\UserMetaManager;
use Baraja\Doctrine\Cache\FilesystemCache;
use Baraja\Doctrine\EntityManager;
use Baraja\DynamicConfiguration\Configuration;
use Baraja\DynamicConfiguration\ConfigurationSection;
use Baraja\Localization\Localization;
Expand All @@ -23,6 +22,7 @@
use Baraja\Plugin\PluginManager;
use DeviceDetector\Cache\DoctrineBridge;
use DeviceDetector\DeviceDetector;
use Doctrine\ORM\EntityManagerInterface;
use Nette\Http\Request;
use Nette\Http\Response;
use Nette\Security\User;
Expand All @@ -41,7 +41,7 @@ final class Context implements ContainerInterface
public function __construct(
private Request $request,
private Response $response,
private EntityManager $entityManager,
private EntityManagerInterface $entityManager,
private Settings $settings,
private User $user,
private TranslatorFilter $translatorFilter,
Expand Down Expand Up @@ -141,7 +141,7 @@ public function getResponse(): Response
}


public function getEntityManager(): EntityManager
public function getEntityManager(): EntityManagerInterface
{
return $this->entityManager;
}
Expand Down
16 changes: 5 additions & 11 deletions src/MiddleWare/TemplateRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Baraja\Cms\Settings;
use Baraja\Cms\User\Entity\CmsUser;
use Baraja\Cms\User\Entity\UserResetPasswordRequest;
use Baraja\Cms\User\Entity\UserResetPasswordRequestRepository;
use Baraja\Plugin\BasePlugin;
use Baraja\Plugin\CmsPluginPanel;
use Baraja\Plugin\Component\PluginComponent;
Expand Down Expand Up @@ -151,18 +152,11 @@ public function renderLoginOtpAuthTemplate(string $locale): string

public function renderResetPasswordTemplate(string $token, string $locale): string
{
try {
/** @var UserResetPasswordRequest $request */
$request = $this->context->getEntityManager()->getRepository(UserResetPasswordRequest::class)
->createQueryBuilder('resetRequest')
->select('resetRequest, PARTIAL user.{id, username}')
->leftJoin('resetRequest.user', 'user')
->where('resetRequest.token = :token')
->setParameter('token', $token)
->setMaxResults(1)
->getQuery()
->getSingleResult();
/** @var UserResetPasswordRequestRepository $repository */
$repository = $this->context->getEntityManager()->getRepository(UserResetPasswordRequestRepository::class);

try {
$request = $repository->getByToken($token);
if ($request->isExpired() === true) {
throw new \InvalidArgumentException('Token has been expired.');
}
Expand Down
4 changes: 2 additions & 2 deletions src/Search/CmsGlobalSearchEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@


use Baraja\Cms\LinkGenerator;
use Baraja\Doctrine\EntityManager;
use Baraja\Plugin\PluginManager;
use Baraja\Search\SearchAccessor;
use Baraja\StructuredApi\BaseEndpoint;
use Doctrine\ORM\EntityManagerInterface;

final class CmsGlobalSearchEndpoint extends BaseEndpoint
{
public function __construct(
private PluginManager $pluginManager,
private EntityManager $entityManager,
private EntityManagerInterface $entityManager,
private ?SearchAccessor $searchAccessor = null,
) {
}
Expand Down
77 changes: 16 additions & 61 deletions src/Settings/DoctrineStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@
namespace Baraja\DoctrineConfiguration;


use Baraja\Doctrine\EntityManager;
use Baraja\DynamicConfiguration\Storage;
use Doctrine\ORM\Mapping\MappingException;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\NoResultException;

Expand All @@ -16,9 +15,15 @@
*/
final class DoctrineStorage implements Storage
{
private OptionRepository $optionRepository;


public function __construct(
private EntityManager $entityManager,
private EntityManagerInterface $entityManager,
) {
/** @var OptionRepository $optionRepository */
$optionRepository = $entityManager->getRepository(OptionRepository::class);
$this->optionRepository = $optionRepository;
}


Expand All @@ -27,15 +32,8 @@ public function __construct(
*/
public function loadAll(): array
{
/** @var array<int, array{id: int, key: string, value: string}> $data */
$data = $this->entityManager->getRepository(Option::class)
->createQueryBuilder('option')
->select('PARTIAL option.{id, key, value}')
->getQuery()
->getArrayResult();

$return = [];
foreach ($data as $item) {
foreach ($this->optionRepository->loadAll() as $item) {
$return[$item['key']] = $item['value'];
}

Expand All @@ -45,19 +43,7 @@ public function loadAll(): array

public function get(string $key): ?string
{
/** @var array<int, array{id: int, value: string|null}> $option */
$option = $this->entityManager->getRepository(Option::class)
->createQueryBuilder('option')
->select('PARTIAL option.{id, value}')
->where('option.key = :key')
->setParameter('key', $key)
->setMaxResults(1)
->getQuery()
->getArrayResult();

return isset($option[0]['value']) === true
? $option[0]['value']
: null;
return $this->optionRepository->getAsArray($key);
}


Expand All @@ -71,17 +57,8 @@ public function getMultiple(array $keys): array
return [];
}

/** @var array<int, array{key: string, value: string}> $options */
$options = $this->entityManager->getRepository(Option::class)
->createQueryBuilder('option')
->select('PARTIAL option.{id, key, value}')
->where('option.key IN (:keys)')
->setParameter('keys', $keys)
->getQuery()
->getArrayResult();

$return = [];
foreach ($options as $option) {
foreach ($this->optionRepository->getMultiple($keys) as $option) {
$return[$option['key']] = $option['value'];
}

Expand All @@ -92,7 +69,7 @@ public function getMultiple(array $keys): array
public function save(string $key, string $value): void
{
try {
$option = $this->getOptionEntity($key);
$option = $this->optionRepository->getAsEntity($key);
} catch (NoResultException | NonUniqueResultException) {
$option = new Option($key, $value);
$this->entityManager->persist($option);
Expand All @@ -105,35 +82,13 @@ public function save(string $key, string $value): void
public function remove(string $key): void
{
try {
$option = $this->getOptionEntity($key);
$option = $this->optionRepository->getAsEntity($key);
} catch (NoResultException | NonUniqueResultException) {
return;
}

try {
$this->entityManager->remove($option);
$this->entityManager->flush();
$this->entityManager->clear($option);
} catch (MappingException $e) {
throw new \RuntimeException($e->getMessage(), 500, $e);
}
}


/**
* @throws NoResultException|NonUniqueResultException
*/
private function getOptionEntity(string $key): Option
{
$option = $this->entityManager->getRepository(Option::class)
->createQueryBuilder('option')
->where('option.key = :key')
->setParameter('key', $key)
->setMaxResults(1)
->getQuery()
->getSingleResult();
assert($option instanceof Option);

return $option;
$this->entityManager->remove($option);
$this->entityManager->flush();
$this->entityManager->clear($option::class);
}
}
Loading

0 comments on commit 9a35836

Please sign in to comment.