<?php declare(strict_types=1);
/*
* (c) webpiloten. <kontakt@web-piloten.de>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spno\SalutationOrder;
use Doctrine\DBAL\Connection;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
use Shopware\Core\Framework\Plugin;
use Shopware\Core\Framework\Plugin\Context\InstallContext;
use Shopware\Core\Framework\Plugin\Context\UninstallContext;
use Spno\SalutationOrder\Entity\SalutationPosition\SalutationPositionDefinition;
class SpnoSalutationOrder extends Plugin
{
public function postInstall(InstallContext $installContext): void
{
/** @var EntityRepositoryInterface $salutationRepository */
$salutationRepository = $this->container->get('salutation.repository');
$criteria = new Criteria();
$criteria->addSorting(new FieldSorting('salutationKey', FieldSorting::DESCENDING));
$salutationIds = $salutationRepository->searchIds($criteria, $installContext->getContext())->getIds();
$salutations = [];
$position = 10;
foreach ($salutationIds as $salutationId) {
$salutations[] = [
'salutationId' => $salutationId,
'position' => $position,
];
$position = $position + 10;
}
/** @var Connection $connection */
$connection = $this->container->get(Connection::class);
foreach ($salutations as $salutation) {
$connection->executeStatement(\sprintf(
"INSERT INTO `%s` (`salutation_id`, `position`, `created_at`) VALUES (UNHEX('%s'), %s, date(now())) ON DUPLICATE KEY UPDATE `salutation_id` = UNHEX('%s')",
SalutationPositionDefinition::ENTITY_NAME,
$salutation['salutationId'],
$salutation['position'],
$salutation['salutationId']
));
}
}
public function uninstall(UninstallContext $uninstallContext): void
{
if ($uninstallContext->keepUserData()) {
parent::uninstall($uninstallContext);
return;
}
/** @var Connection $connection */
$connection = $this->container->get(Connection::class);
$connection->executeStatement(\sprintf('DROP TABLE IF EXISTS `%s`', SalutationPositionDefinition::ENTITY_NAME));
}
}