<?php declare(strict_types=1);
namespace Cogi\CogiRecruiting;
use DateTime;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DBALException;
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\Exception\InconsistentCriteriaIdsException;
use Shopware\Core\Framework\DataAbstractionLayer\Indexing\Indexer\InheritanceIndexer;
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\ActivateContext;
use Shopware\Core\Framework\Plugin\Context\InstallContext;
use Shopware\Core\Framework\Plugin\Context\UninstallContext;
use Shopware\Core\Framework\Plugin\Context\UpdateContext;
use Shopware\Core\Framework\Uuid\Exception\InvalidUuidException;
use Shopware\Core\Framework\Uuid\Uuid;
use Shopware\Core\System\Language\LanguageEntity;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
class CogiRecruiting extends Plugin {
const MAIL_TEMPLATE_ADMIN_NEW_APPLICATION = 'cogi_recruiting_admin_new_application';
const MAIL_TEMPLATE_APPLICATION_CONFIRMATION = 'cogi_recruiting_application_confirmation';
public function build(ContainerBuilder $container): void {
parent::build($container);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/Resources/config'));
$loader->load('services.xml');
}
public function activate(ActivateContext $activateContext): void {
}
public function update(UpdateContext $updateContext): void {
if ($updateContext->getCurrentPluginVersion() === "1.1.7" || $updateContext->getUpdatePluginVersion() === "1.1.8") {
$this->_createMailTemplates($updateContext->getContext());
}
}
public function install(InstallContext $installContext): void {
$this->_createMailTemplates($installContext->getContext());
}
public function uninstall(UninstallContext $context): void {
if ($context->keepUserData()) {
parent::uninstall($context);
return;
}
/** @var Connection $connection */
$connection = $this->container->get(Connection::class);
$connection->executeStatement('DROP TABLE IF EXISTS `cogi_recruiting_application_link`');
$connection->executeStatement('DROP TABLE IF EXISTS `cogi_recruiting_application_comment`');
$connection->executeStatement('DROP TABLE IF EXISTS `cogi_recruiting_application`');
$connection->executeStatement('DROP TABLE IF EXISTS `cogi_recruiting_job_translation`');
$connection->executeStatement('DROP TABLE IF EXISTS `cogi_recruiting_job_event`');
$connection->executeStatement('DROP TABLE IF EXISTS `cogi_recruiting_job`');
$connection->executeStatement('DROP TABLE IF EXISTS `cogi_recruiting_category_translation`');
$connection->executeStatement('DROP TABLE IF EXISTS `cogi_recruiting_category`');
$connection->executeStatement("DELETE FROM `seo_url_template` WHERE `entity_name` LIKE '%cogi_recruiting%';");
$connection->executeStatement("DELETE FROM `seo_url` WHERE `route_name` LIKE '%frontend.cogirecruiting%';");
// Uninstall email templates
$this->removeEmailTemplate(self::MAIL_TEMPLATE_ADMIN_NEW_APPLICATION, $context->getContext());
$this->removeEmailTemplate(self::MAIL_TEMPLATE_APPLICATION_CONFIRMATION, $context->getContext());
}
private function _createMailTemplates(Context $context) {
/** @var Connection $connection */
$connection = $this->container->get(Connection::class);
//Admin Mail
// try {
$templateTypeData['technicalName'] = self::MAIL_TEMPLATE_ADMIN_NEW_APPLICATION;
$templateTypeData['availableEntities'] = [
'application' => 'cogi_recruiting_application',
'job' => 'cogi_recruiting_job',
];
$templateTypeData['enName'] = 'Recruiting Admin - new job application';
$templateTypeData['deName'] = 'Recruiting Admin - Neue Stellenbewerbung';
$mailTemplateTypeId = $this->createMailTemplateType($connection, $templateTypeData, $context);
$templateData['en-GB']['senderName'] = '{{ salesChannel.name }}';
$templateData['en-GB']['subject'] = 'Recruiting - new job application';
$templateData['en-GB']['description'] = '';
$templateData['en-GB']['contentHtml'] = $this->getMailContent('en-GB', 'admin_new_application', 'html');
$templateData['en-GB']['contentPlain'] = $this->getMailContent('en-GB', 'admin_new_application', 'txt');
$templateData['de-DE']['senderName'] = '{{ salesChannel.name }}';
$templateData['de-DE']['subject'] = 'Recruiting - Neue Stellenbewerbung';
$templateData['de-DE']['description'] = '';
$templateData['de-DE']['contentHtml'] = $this->getMailContent('de-DE', 'admin_new_application', 'html');
$templateData['de-DE']['contentPlain'] = $this->getMailContent('de-DE', 'admin_new_application', 'txt');
$this->createMailTemplate($connection, $mailTemplateTypeId, $templateData, $context);
// } catch (\Exception $e) {
// }
//Applicant Mail
// try {
$templateTypeData['technicalName'] = self::MAIL_TEMPLATE_APPLICATION_CONFIRMATION;
$templateTypeData['availableEntities'] = [
'application' => 'cogi_recruiting_application',
'job' => 'cogi_recruiting_job',
];
$templateTypeData['enName'] = 'Recruiting Applicant - thank you';
$templateTypeData['deName'] = 'Recruiting Bewerber - vielen Dank';
$mailTemplateTypeId = $this->createMailTemplateType($connection, $templateTypeData, $context);
$templateData['en-GB']['senderName'] = '{{ salesChannel.name }}';
$templateData['en-GB']['subject'] = 'Confirmation of your application';
$templateData['en-GB']['description'] = '';
$templateData['en-GB']['contentHtml'] = $this->getMailContent('en-GB', 'user_new_application', 'html');
$templateData['en-GB']['contentPlain'] = $this->getMailContent('en-GB', 'user_new_application', 'txt');
$templateData['de-DE']['senderName'] = '{{ salesChannel.name }}';
$templateData['de-DE']['subject'] = 'Bestätigung Ihrer Bewerbung';
$templateData['de-DE']['description'] = '';
$templateData['de-DE']['contentHtml'] = $this->getMailContent('de-DE', 'user_new_application', 'html');
$templateData['de-DE']['contentPlain'] = $this->getMailContent('de-DE', 'user_new_application', 'txt');
$this->createMailTemplate($connection, $mailTemplateTypeId, $templateData, $context);
// } catch (\Exception $e) {
// }
}
/**
* ------------------------
*
* Mail helpers below!
*
* ------------------------
*/
/**
* @param Connection $connection
* @param array $data
*
* @return string
*
* @throws DBALException
* @throws InconsistentCriteriaIdsException
* @throws InvalidUuidException
*/
private function createMailTemplateType(Connection $connection, array $data, Context $context): string {
$mailTemplateTypeId = Uuid::randomHex();
$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)
]);
$connection->insert('mail_template_type_translation', [
'mail_template_type_id' => Uuid::fromHexToBytes($mailTemplateTypeId),
'language_id' => Uuid::fromHexToBytes($this->getLanguageIdByLocale('en-GB')),
'name' => $data['enName'],
'created_at' => (new DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]);
$connection->insert('mail_template_type_translation', [
'mail_template_type_id' => Uuid::fromHexToBytes($mailTemplateTypeId),
'language_id' => Uuid::fromHexToBytes($this->getLanguageIdByLocale('de-DE')),
'name' => $data['deName'],
'created_at' => (new DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]);
// Add fallback
$defaultLocalCode = $this->getDefaultLocaleCode($context);
if (!in_array($defaultLocalCode, ['de-DE', 'en-GB'])) {
$connection->insert('mail_template_type_translation', [
'mail_template_type_id' => Uuid::fromHexToBytes($mailTemplateTypeId),
'language_id' => Uuid::fromHexToBytes($this->getLanguageIdByLocale($defaultLocalCode)),
'name' => $data['enName'],
'created_at' => (new DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]);
}
return $mailTemplateTypeId;
}
/**
* @param string $locale
*
* @return string
*
* @throws InconsistentCriteriaIdsException
*/
private function getLanguageIdByLocale(string $locale): string {
$context = new Context(new SystemSource());
/** @var EntityRepository $languageRepository */
$languageRepository = $this->container->get('language.repository');
$criteria = new Criteria();
$criteria->addAssociation('locale');
$criteria->addFilter(new EqualsFilter('locale.code', $locale));
/** @var LanguageEntity $languageEntity */
$languageEntity = $languageRepository->search($criteria, $context)->first();
return $languageEntity->getId();
}
private function getDefaultLocaleCode($context): string {
/** @var EntityRepository $languageRepository */
$languageRepository = $this->container->get('language.repository');
$criteria = new Criteria();
$criteria->addAssociation('locale');
$criteria->addFilter(new EqualsFilter('id', Defaults::LANGUAGE_SYSTEM));
/** @var LanguageEntity $languageEntity */
$languageEntity = $languageRepository->search($criteria, $context)->get(Defaults::LANGUAGE_SYSTEM);
return $languageEntity->getLocale()->getCode();
}
/**
* @param string $locale
* @param string $prefix
* @param string $type
*
* @return string
*/
private function getMailContent(string $locale, string $prefix, string $type): string {
$path = $this->getPath() . '/Resources/email/' . $locale . '/';
$file = "{$path}{$prefix}.{$type}";
if (!is_file($file)) {
throw new FileNotFoundException($file);
}
return file_get_contents($file);
}
/**
* @param Connection $connection
* @param string $mailTemplateTypeId
* @param array $data
*
* @return void
*
* @throws DBALException
* @throws InconsistentCriteriaIdsException
* @throws InvalidUuidException
*/
private function createMailTemplate(Connection $connection, string $mailTemplateTypeId, array $data, Context $context): void {
$mailTemplateId = Uuid::randomHex();
$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)
]);
$connection->insert('mail_template_translation', [
'mail_template_id' => Uuid::fromHexToBytes($mailTemplateId),
'language_id' => Uuid::fromHexToBytes($this->getLanguageIdByLocale('en-GB')),
'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)
]);
$connection->insert('mail_template_translation', [
'mail_template_id' => Uuid::fromHexToBytes($mailTemplateId),
'language_id' => Uuid::fromHexToBytes($this->getLanguageIdByLocale('de-DE')),
'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)
]);
// Add fallback
$defaultLocalCode = $this->getDefaultLocaleCode($context);
if (!in_array($defaultLocalCode, ['de-DE', 'en-GB'])) {
$connection->insert('mail_template_translation', [
'mail_template_id' => Uuid::fromHexToBytes($mailTemplateId),
'language_id' => Uuid::fromHexToBytes($this->getLanguageIdByLocale($defaultLocalCode)),
'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)
]);
}
}
/**
* Removes a specific email template by templateTypeTechnicalName
* @param $templateTypeTechnicalName
* @param Context $context
* @return void
*/
public function removeEmailTemplate($templateTypeTechnicalName, Context $context) {
/** @var EntityRepository $mailTemplateTypeRepository */
$mailTemplateTypeRepository = $this->container->get('mail_template_type.repository');
/** @var EntityRepository $mailTemplateRepository */
$mailTemplateRepository = $this->container->get('mail_template.repository');
/** @var MailTemplateTypeEntity $customMailTemplateType */
$customMailTemplateType = $mailTemplateTypeRepository->search(
(new Criteria())
->addFilter(new EqualsFilter('technicalName', $templateTypeTechnicalName)),
$context
)->first();
if ($customMailTemplateType) {
$mailTemplateIds = $mailTemplateRepository->searchIds(
(new Criteria())
->addFilter(new EqualsFilter('mailTemplateTypeId', $customMailTemplateType->getId())),
$context
)->getIds();
$ids = array_map(static function ($id) {
return ['id' => $id];
}, $mailTemplateIds);
$mailTemplateRepository->delete($ids, $context);
// Delete the TemplateType which were added by this Plugin
$mailTemplateTypeRepository->delete([
['id' => $customMailTemplateType->getId()]
], $context);
}
}
}