<?php
declare(strict_types=1);
namespace Ecocode\EcoShrinky;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
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\System\CustomField\CustomFieldTypes;
class EcoShrinky extends Plugin
{
const OPTIMIZED_COLUMN_NAME = 'ecoshrinky_optimized';
public function install(InstallContext $installContext): void
{
parent::install($installContext);
$context = $installContext->getContext();
try {
$this->createCustomField($context);
} catch (UniqueConstraintViolationException $exception) {
// custom fieldset already present
}
}
public function uninstall(UninstallContext $uninstallContext): void
{
parent::uninstall($uninstallContext);
$context = $uninstallContext->getContext();
/** @var EntityRepositoryInterface $customFieldSetRepository */
$customFieldSetRepository = $this->container->get('custom_field_set.repository');
$customFieldSetId = $customFieldSetRepository->searchIds(
(new Criteria())
->addFilter(new EqualsFilter('name', 'ecoshrinky')),
$context
)->getIds();
//Get the Ids from the fetched Entities
$ids = array_map(static function ($id) {
return ['id' => $id];
}, $customFieldSetId);
$customFieldSetRepository->delete($ids, $context);
}
protected function createCustomField($context): void
{
$customFieldSetRepository = $this->container->get('custom_field_set.repository');
$result = $customFieldSetRepository->create(
[[
'name' => 'ecoshrinky',
'customFields' => [
['name' => self::OPTIMIZED_COLUMN_NAME, 'type' => CustomFieldTypes::BOOL],
]
]], $context
);
$result->getEventByEntityName('custom_field_set')->getIds();
}
}