<?php declare(strict_types=1);
namespace Cogi\CogiContest;
use Doctrine\DBAL\Connection;
use Shopware\Core\Content\ImportExport\Exception\FileNotFoundException;
use Shopware\Core\Content\MailTemplate\Aggregate\MailTemplateType\MailTemplateTypeEntity;
use Shopware\Core\Defaults;
use Shopware\Core\Framework\Api\Context\SystemSource;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Plugin;
use Shopware\Core\Framework\Plugin\Context\InstallContext;
use Shopware\Core\Framework\Plugin\Context\UninstallContext;
use Shopware\Core\Framework\Uuid\Uuid;
use Shopware\Core\System\Language\LanguageEntity;
class CogiContest extends Plugin
{
public const TEMPLATE_TYPE_TECHNICAL_NAME = 'contest_type';
public const MAIL_TEMPLATE_NAMTE = "ContestMailTemplate";
public function install(InstallContext $installContext): void
{
/** @var Connection $connection */
$connection = $this->container->get(Connection::class);
//Customer Emails
// $context = new Context(new SystemSource());
$languageTypeRepository = $this->container->get('mail_template_type.repository');
$criteria = new Criteria();
$criteria->setLimit(1);
$criteria->addFilter(new EqualsFilter('technicalName', self::TEMPLATE_TYPE_TECHNICAL_NAME));
/** @var MailTemplateTypeEntity $languageTypeEntity */
$languageTypeEntity = $languageTypeRepository->search($criteria, $installContext->getContext())->first();
if(isset($languageTypeEntity)){
$typeName = $languageTypeEntity->getTechnicalName();
}
else {
$typeName = " ";
}
if ($typeName != self::TEMPLATE_TYPE_TECHNICAL_NAME) {
$templateTypeData['technicalName'] = self::TEMPLATE_TYPE_TECHNICAL_NAME;
$templateTypeData['availableEntities'] = [
'order' => 'order',
'salesChannel' => 'sales_channel',
'customer' => 'customer',
'mailHeaderFooter' => 'mail_header_footer'
];
$templateTypeData['enName'] = 'Contest';
$templateTypeData['deName'] = 'Gewinnspiel';
$mailTemplateTypeId = $this->createMailTemplateType($connection, $templateTypeData);
$templateData['en-GB']['senderName'] = '{{ salesChannel.translated.name }}';
$templateData['en-GB']['subject'] = 'Congratulations, you have won! {{ salesChannel.translated.name }}';
$templateData['en-GB']['description'] = '';
$templateData['en-GB']['contentHtml'] = $this->getMailContent('en-GB', 'contest', 'html');
$templateData['en-GB']['contentPlain'] = $this->getMailContent('en-GB', 'contest', 'plain');
$templateData['de-DE']['senderName'] = '{{ salesChannel.translated.name }}';
$templateData['de-DE']['subject'] = 'Du hast gewonnen! {{ salesChannel.translated.name }}';
$templateData['de-DE']['description'] = '';
$templateData['de-DE']['contentHtml'] = $this->getMailContent('de-DE', 'contest', 'html');
$templateData['de-DE']['contentPlain'] = $this->getMailContent('de-DE', 'contest', 'plain');
$this->createMailTemplate($connection, $mailTemplateTypeId, $templateData);
}
parent::install($installContext);
}
public function uninstall(UninstallContext $uninstallContext): void
{
parent::uninstall($uninstallContext);
if ($uninstallContext->keepUserData()) {
return;
}
//get the Templates and Associations added by this Plugin from the DB
/** @var EntityRepositoryInterface $mailTemplateTypeRepository */
$mailTemplateTypeRepository = $this->container->get('mail_template_type.repository');
/** @var EntityRepositoryInterface $mailTemplateRepository */
$mailTemplateRepository = $this->container->get('mail_template.repository');
/** @var MailTemplateTypeEntity $myCustomMailTemplateType */
$myCustomMailTemplateType = $mailTemplateTypeRepository->search(
(new Criteria())
->addFilter(new EqualsFilter('technicalName', self::TEMPLATE_TYPE_TECHNICAL_NAME)),
$uninstallContext
->getContext()
)->first();
$mailTemplateIds = $mailTemplateRepository->searchIds(
(new Criteria())
->addFilter(new EqualsFilter('mailTemplateTypeId', $myCustomMailTemplateType->getId())),
$uninstallContext
->getContext()
)->getIds();
//Get the Ids from the fetched Entities
$ids = array_map(static function ($id) {
return ['id' => $id];
}, $mailTemplateIds);
//Delete the Templates which were added by this Plugin
$mailTemplateRepository->delete($ids, $uninstallContext->getContext());
//Delete the TemplateType which were added by this Plugin
$mailTemplateTypeRepository->delete([
['id' => $myCustomMailTemplateType->getId()]
], $uninstallContext->getContext());
$connection = $this->container->get(Connection::class);
$connection->exec('DROP TABLE IF EXISTS `cogi_contest_member`');
$connection->exec('DROP TABLE IF EXISTS `cogi_contest_translation`');
$connection->exec('DROP TABLE IF EXISTS `cogi_contest`');
}
private function createMailTemplateType(Connection $connection, array $data): string
{
$mailTemplateTypeId = Uuid::randomHex();
$defaultLangId = $this->getLanguageIdByLocale($connection, 'en-GB');
$deLangId = $this->getLanguageIdByLocale($connection, 'de-DE');
$defaultSystemLanguage = Uuid::fromHexToBytes(Defaults::LANGUAGE_SYSTEM);
$connection->insert('mail_template_type', [
'id' => Uuid::fromHexToBytes($mailTemplateTypeId),
'technical_name' => $data['technicalName'],
'available_entities' => json_encode($data['availableEntities']),
'created_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]);
if ($defaultLangId !== $deLangId) {
$connection->insert('mail_template_type_translation', [
'mail_template_type_id' => Uuid::fromHexToBytes($mailTemplateTypeId),
'language_id' => $defaultLangId,
'name' => $data['enName'],
'created_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]);
}
if ($defaultLangId !== $defaultSystemLanguage && $deLangId !== $defaultSystemLanguage) {
$connection->insert('mail_template_type_translation', [
'mail_template_type_id' => Uuid::fromHexToBytes($mailTemplateTypeId),
'language_id' => $defaultSystemLanguage,
'name' => $data['enName'],
'created_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]);
}
if ($deLangId) {
$connection->insert('mail_template_type_translation', [
'mail_template_type_id' => Uuid::fromHexToBytes($mailTemplateTypeId),
'language_id' => $deLangId,
'name' => $data['deName'],
'created_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]);
}
return $mailTemplateTypeId;
}
private function getMailContent(string $locale, string $prefix, string $type): string {
$path = $this->getPath() . '/Resources/email/' . $locale . '/';
switch ($type) {
case 'html':
$ext = 'html';
break;
case 'plain':
$ext = 'txt';
break;
default:
$ext = 'txt';
}
$file = $path . $prefix . '-' . $type . '.' . $ext;
if (!is_file($file)) {
throw new FileNotFoundException($file);
}
return file_get_contents($file);
}
private function createMailTemplate(Connection $connection, string $mailTemplateTypeId, array $data): void {
$mailTemplateId = Uuid::randomHex();
$defaultLangId = $this->getLanguageIdByLocale($connection, 'en-GB');
$deLangId = $this->getLanguageIdByLocale($connection, 'de-DE');
$defaultSystemLanguage = Uuid::fromHexToBytes(Defaults::LANGUAGE_SYSTEM);
$connection->insert('mail_template', [
'id' => Uuid::fromHexToBytes($mailTemplateId),
'mail_template_type_id' => Uuid::fromHexToBytes($mailTemplateTypeId),
'system_default' => true,
'created_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]);
if ($defaultLangId !== $deLangId) {
$connection->insert('mail_template_translation', [
'mail_template_id' => Uuid::fromHexToBytes($mailTemplateId),
'language_id' => $defaultLangId,
'sender_name' => $data['en-GB']['senderName'],
'subject' => $data['en-GB']['subject'],
'description' => $data['en-GB']['description'],
'content_html' => $data['en-GB']['contentHtml'],
'content_plain' => $data['en-GB']['contentPlain'],
'created_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]);
}
if ($defaultLangId !== $defaultSystemLanguage && $deLangId !== $defaultSystemLanguage) {
$connection->insert('mail_template_translation', [
'mail_template_id' => Uuid::fromHexToBytes($mailTemplateId),
'language_id' => $defaultSystemLanguage,
'sender_name' => $data['en-GB']['senderName'],
'subject' => $data['en-GB']['subject'],
'description' => $data['en-GB']['description'],
'content_html' => $data['en-GB']['contentHtml'],
'content_plain' => $data['en-GB']['contentPlain'],
'created_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]);
}
if ($deLangId) {
$connection->insert('mail_template_translation', [
'mail_template_id' => Uuid::fromHexToBytes($mailTemplateId),
'language_id' => $deLangId,
'sender_name' => $data['de-DE']['senderName'],
'subject' => $data['de-DE']['subject'],
'description' => $data['de-DE']['description'],
'content_html' => $data['de-DE']['contentHtml'],
'content_plain' => $data['de-DE']['contentPlain'],
'created_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]);
}
}
private function getLanguageIdByLocale(Connection $connection, string $locale): ?string
{
$sql = <<<'SQL'
SELECT `language`.`id`
FROM `language`
INNER JOIN `locale` ON `locale`.`id` = `language`.`locale_id`
WHERE `locale`.`code` = :code
SQL;
$languageId = $connection->executeQuery($sql, ['code' => $locale])->fetchColumn();
if (!$languageId && $locale !== 'en-GB') {
return null;
}
if (!$languageId) {
return Uuid::fromHexToBytes(Defaults::LANGUAGE_SYSTEM);
}
return $languageId;
}
}