Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
AUDUL committed Nov 14, 2023
1 parent 70066aa commit cb8fb9b
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 141 deletions.
41 changes: 0 additions & 41 deletions bundle/Command/InstallCommand.php

This file was deleted.

114 changes: 48 additions & 66 deletions bundle/Command/MigrateEzMailingCommand.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<?php



declare(strict_types=1);

namespace CodeRhapsodie\IbexaMailingBundle\Command;
Expand All @@ -11,6 +10,7 @@
use CodeRhapsodie\IbexaMailingBundle\Entity\MailingList;
use CodeRhapsodie\IbexaMailingBundle\Entity\Registration;
use CodeRhapsodie\IbexaMailingBundle\Entity\User;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\EntityManagerInterface;
use Ibexa\Contracts\Core\Repository\Repository;
use Ibexa\Contracts\Core\SiteAccess\ConfigResolverInterface;
Expand All @@ -22,46 +22,28 @@

class MigrateEzMailingCommand extends Command
{
/**
* @var IOService
*/
private $ioService;

/**
* @var SymfonyStyle
*/
private $io;

/**
* @var EntityManagerInterface
*/
private $entityManager;

/**
* @var Repository;
*/
private $ezRepository;

/**
* @var ConfigResolverInterface
*/
private $configResolver;

public const DEFAULT_FALLBACK_LOCATION_ID = 2;

public const DUMP_FOLDER = 'migrate/ibexamailing';

private readonly Connection $connection;

public function __construct(
IOService $ioService,
EntityManagerInterface $entityManager,
Repository $ezRepository,
ConfigResolverInterface $configResolver
) {
private readonly IOService $ioService,
private readonly EntityManagerInterface $entityManager,
private readonly Repository $ezRepository,
)
{
parent::__construct();
$this->ioService = $ioService;
$this->entityManager = $entityManager;
$this->ezRepository = $ezRepository;
$this->configResolver = $configResolver;
$this->connection = $this->entityManager->getConnection();
}

protected function configure(): void
Expand Down Expand Up @@ -109,12 +91,12 @@ private function export(): void

// Lists

$sql = 'SELECT id, name, lang FROM ibexamailingmailinglist WHERE draft = 0';
$sql = 'SELECT id, name, lang FROM ezmailingmailinglist WHERE draft = 0';

$list_rows = $this->runQuery($sql);
foreach ($list_rows as $list_row) {
$fileName = $this->ioService->saveFile(
self::DUMP_FOLDER."/list/list_{$list_row['id']}.json",
self::DUMP_FOLDER . "/list/list_{$list_row['id']}.json",
json_encode([$list_row['lang'] => $list_row['name']]) // Approve should be false when importing
);
$lists[] = pathinfo($fileName)['filename'];
Expand All @@ -124,12 +106,12 @@ private function export(): void

$sql = 'SELECT id, subject, sender_name, sender_email, report_email, destination_mailing_list ';

$sql .= 'FROM ibexamailingcampaign WHERE draft = 0';
$sql .= 'FROM ezmailingcampaign WHERE draft = 0';

$campaign_rows = $this->runQuery($sql);
foreach ($campaign_rows as $campaign_row) {
$fileName = $this->ioService->saveFile(
self::DUMP_FOLDER."/campaign/campaign_{$campaign_row['id']}.json",
self::DUMP_FOLDER . "/campaign/campaign_{$campaign_row['id']}.json",
json_encode(
[
'name' => [$defaultLanguageCode => $campaign_row['subject']],
Expand All @@ -144,13 +126,13 @@ private function export(): void
}

// Users
$sql = 'SELECT id, email, first_name, last_name, origin FROM ibexamailinguser WHERE draft = 0 ';
$sql = 'SELECT id, email, first_name, last_name, origin FROM ezmailinguser WHERE draft = 0 ';

$sql .= 'AND (id, email) in (select max(id), email from ibexamailinguser group by email)';
$sql .= 'AND (id, email) in (select max(id), email from ezmailinguser group by email)';

$user_rows = $this->runQuery($sql);
foreach ($user_rows as $user_row) {
$sql = 'SELECT mailinglist_id, state FROM ibexamailingregistration WHERE mailing_user_id = ?';
$sql = 'SELECT mailinglist_id, state FROM ezmailingregistration WHERE mailing_user_id = ?';
$subscription_rows = $this->runQuery($sql, [$user_row['id']]);
$subscriptions = [];
foreach ($subscription_rows as $subscription_row) {
Expand All @@ -162,7 +144,7 @@ private function export(): void
}

$fileName = $this->ioService->saveFile(
self::DUMP_FOLDER."/user/user_{$user_row['id']}.json",
self::DUMP_FOLDER . "/user/user_{$user_row['id']}.json",
json_encode(
[
'email' => $user_row['email'],
Expand All @@ -177,12 +159,12 @@ private function export(): void
}

$this->ioService->saveFile(
self::DUMP_FOLDER.'/manifest.json',
self::DUMP_FOLDER . '/manifest.json',
json_encode(['lists' => $lists, 'campaigns' => $campaigns, 'users' => $users])
);
$this->io->section(
'Total: '.count($lists).' lists, '.count($campaigns).' campaigns, '.$mailingCounter.' mailings, '.
count($users).' users, '.$registrationCounter.' registrations.'
'Total: ' . count($lists) . ' lists, ' . count($campaigns) . ' campaigns, ' . $mailingCounter . ' mailings, ' .
count($users) . ' users, ' . $registrationCounter . ' registrations.'
);
$this->io->success('Export done.');
}
Expand All @@ -193,7 +175,7 @@ private function import(): void
$this->clean();
$this->io->section('Importing from json files to new database.');

$manifest = $this->ioService->readFile(self::DUMP_FOLDER.'/manifest.json');
$manifest = $this->ioService->readFile(self::DUMP_FOLDER . '/manifest.json');
$fileNames = json_decode($manifest);

// Lists
Expand All @@ -205,9 +187,9 @@ private function import(): void
$userRepository = $this->entityManager->getRepository(User::class);

foreach ($fileNames->lists as $listFile) {
$listData = json_decode($this->ioService->readFile(self::DUMP_FOLDER.'/list/'.$listFile.'.json'));
$listData = json_decode($this->ioService->readFile(self::DUMP_FOLDER . '/list/' . $listFile . '.json'));
$mailingList = new MailingList();
$mailingList->setNames((array) $listData);
$mailingList->setNames((array)$listData);
$mailingList->setWithApproval(false);
$this->entityManager->persist($mailingList);
++$listCounter;
Expand All @@ -218,10 +200,10 @@ private function import(): void
// Campaigns
foreach ($fileNames->campaigns as $campaignFile) {
$campaignData = json_decode(
$this->ioService->readFile(self::DUMP_FOLDER.'/campaign/'.$campaignFile.'.json')
$this->ioService->readFile(self::DUMP_FOLDER . '/campaign/' . $campaignFile . '.json')
);
$campaign = new Campaign();
$campaign->setNames((array) $campaignData->name);
$campaign->setNames((array)$campaignData->name);
$campaign->setReportEmail($campaignData->reportEmail);
$campaign->setSenderEmail($campaignData->senderEmail);
$campaign->setReturnPathEmail('');
Expand All @@ -248,7 +230,7 @@ private function import(): void

// Users & Subscriptions
foreach ($fileNames->users as $userFile) {
$userData = json_decode($this->ioService->readFile(self::DUMP_FOLDER.'/user/'.$userFile.'.json'));
$userData = json_decode($this->ioService->readFile(self::DUMP_FOLDER . '/user/' . $userFile . '.json'));

// check if email already exists
$existingUser = $userRepository->findOneBy(['email' => $userData->email]);
Expand Down Expand Up @@ -283,42 +265,42 @@ private function import(): void
$this->entityManager->flush();

$this->io->section(
'Total: '.$listCounter.' lists, '.$campaignCounter.' campaigns, '.$mailingCounter.' mailings, '.
$userCounter.' users, '.$registrationCounter.' registrations.'
'Total: ' . $listCounter . ' lists, ' . $campaignCounter . ' campaigns, ' . $mailingCounter . ' mailings, ' .
$userCounter . ' users, ' . $registrationCounter . ' registrations.'
);
$this->io->success('Import done.');
}

private function clean(): void
{
// We don't run TRUNCATE command here because of foreign keys constraints
$this->entityManager->getConnection()->query('DELETE FROM ibexamailing_stats_hit');
$this->entityManager->getConnection()->query('ALTER TABLE ibexamailing_stats_hit AUTO_INCREMENT = 1');
$this->entityManager->getConnection()->query('DELETE FROM ibexamailing_broadcast');
$this->entityManager->getConnection()->query('ALTER TABLE ibexamailing_broadcast AUTO_INCREMENT = 1');
$this->entityManager->getConnection()->query('DELETE FROM ibexamailing_mailing');
$this->entityManager->getConnection()->query('ALTER TABLE ibexamailing_mailing AUTO_INCREMENT = 1');
$this->entityManager->getConnection()->query('DELETE FROM ibexamailing_campaign_mailinglists_destination');
$this->entityManager->getConnection()->query('DELETE FROM ibexamailing_campaign');
$this->entityManager->getConnection()->query('ALTER TABLE ibexamailing_campaign AUTO_INCREMENT = 1');
$this->entityManager->getConnection()->query('DELETE FROM ibexamailing_confirmation_token');
$this->entityManager->getConnection()->query('DELETE FROM ibexamailing_registrations');
$this->entityManager->getConnection()->query('ALTER TABLE ibexamailing_registrations AUTO_INCREMENT = 1');
$this->entityManager->getConnection()->query('DELETE FROM ibexamailing_mailing_list');
$this->entityManager->getConnection()->query('ALTER TABLE ibexamailing_mailing_list AUTO_INCREMENT = 1');
$this->entityManager->getConnection()->query('DELETE FROM ibexamailing_user');
$this->entityManager->getConnection()->query('ALTER TABLE ibexamailing_user AUTO_INCREMENT = 1');
$this->connection->executeQuery('DELETE FROM ibexamailing_stats_hit');
$this->connection->executeQuery('ALTER TABLE ibexamailing_stats_hit AUTO_INCREMENT = 1');
$this->connection->executeQuery('DELETE FROM ibexamailing_broadcast');
$this->connection->executeQuery('ALTER TABLE ibexamailing_broadcast AUTO_INCREMENT = 1');
$this->connection->executeQuery('DELETE FROM ibexamailing_mailing');
$this->connection->executeQuery('ALTER TABLE ibexamailing_mailing AUTO_INCREMENT = 1');
$this->connection->executeQuery('DELETE FROM ibexamailing_campaign_mailinglists_destination');
$this->connection->executeQuery('DELETE FROM ibexamailing_campaign');
$this->connection->executeQuery('ALTER TABLE ibexamailing_campaign AUTO_INCREMENT = 1');
$this->connection->executeQuery('DELETE FROM ibexamailing_confirmation_token');
$this->connection->executeQuery('DELETE FROM ibexamailing_registrations');
$this->connection->executeQuery('ALTER TABLE ibexamailing_registrations AUTO_INCREMENT = 1');
$this->connection->executeQuery('DELETE FROM ibexamailing_mailing_list');
$this->connection->executeQuery('ALTER TABLE ibexamailing_mailing_list AUTO_INCREMENT = 1');
$this->connection->executeQuery('DELETE FROM ibexamailing_user');
$this->connection->executeQuery('ALTER TABLE ibexamailing_user AUTO_INCREMENT = 1');
$this->io->section('Current tables in the new database have been cleaned.');
}

private function runQuery(string $sql, array $parameters = [], $fetchMode = null): array
private function runQuery(string $sql, array $parameters = []): array
{
$stmt = $this->entityManager->getConnection()->prepare($sql);
$stmt = $this->connection->prepare($sql);
for ($i = 1, $iMax = count($parameters); $i <= $iMax; ++$i) {
$stmt->bindValue($i, $parameters[$i - 1]);
}
$stmt->execute();
$result = $stmt->executeQuery();

return $stmt->fetchAll($fetchMode);
return $result->fetchAllAssociative();
}
}
2 changes: 1 addition & 1 deletion bundle/Core/AjaxGuard.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
namespace CodeRhapsodie\IbexaMailingBundle\Core;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Proxy\Proxy;
use Doctrine\Persistence\Proxy;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Security\Csrf\CsrfToken;
Expand Down
4 changes: 2 additions & 2 deletions bundle/Core/Provider/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

use CodeRhapsodie\IbexaMailingBundle\Entity\User as UserEntity;
use Doctrine\ORM\EntityManagerInterface;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Doctrine\ORM\QueryAdapter;
use Pagerfanta\Pagerfanta;

class User
Expand All @@ -26,7 +26,7 @@ public function __construct(EntityManagerInterface $entityManager)
public function getPagerFilters(array $filters = [], int $page = 1, int $limit = 25): Pagerfanta
{
$repo = $this->entityManager->getRepository(UserEntity::class);
$adapter = new DoctrineORMAdapter($repo->createQueryBuilderForFilters($filters));
$adapter = new QueryAdapter($repo->createQueryBuilderForFilters($filters));
$pager = new Pagerfanta($adapter);
$pager->setMaxPerPage($limit);
$pager->setCurrentPage($page);
Expand Down
18 changes: 6 additions & 12 deletions bundle/Listener/EntityContentLink.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
namespace CodeRhapsodie\IbexaMailingBundle\Listener;

use CodeRhapsodie\IbexaMailingBundle\Entity\eZ\ContentInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PostLoadEventArgs;
use Doctrine\ORM\Mapping\PostLoad;
use Ibexa\Contracts\Core\Repository\Exceptions\NotFoundException;
use Ibexa\Contracts\Core\Repository\LocationService;
use Ibexa\Contracts\Core\Repository\Repository;

/**
Expand All @@ -18,26 +19,19 @@
*/
class EntityContentLink
{
/**
* @var Repository
*/
private $repository;

public function __construct(Repository $repository)
public function __construct(private readonly Repository $repository, private readonly LocationService $locationService)
{
$this->repository = $repository;
}

/** @PostLoad */
public function postLoadHandler(ContentInterface $entity, LifecycleEventArgs $event): void
public function postLoadHandler(ContentInterface $entity, PostLoadEventArgs $event): void
{
if (null !== $entity->getLocationId()) {
try {
$this->repository->sudo(function () use ($entity) {
$location = $this->repository->getLocationService()->loadLocation($entity->getLocationId());
$content = $this->repository->getContentService()->loadContentByContentInfo($location->contentInfo);
$location = $this->locationService->loadLocation($entity->getLocationId());
$entity->setLocation($location);
$entity->setContent($content);
$entity->setContent($location->getContent());
});
} catch (NotFoundException) {
}
Expand Down
2 changes: 1 addition & 1 deletion bundle/Listener/PreContentView.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public function onPreContentView(PreContentViewEvent $event): void
return;
}

$masterRequest = $this->requestStack->getMasterRequest();
$masterRequest = $this->requestStack->getMainRequest();
if (null === $masterRequest) {
return;
}
Expand Down
Loading

0 comments on commit cb8fb9b

Please sign in to comment.