<?php
declare(strict_types=1);
namespace EconsorSetup;
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\EqualsAnyFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\IdSearchResult;
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;
use Shopware\Core\System\SystemConfig\SystemConfigService;
/** @psalm-suppress PropertyNotSetInConstructor */
class EconsorSetup extends Plugin
{
public function install(InstallContext $installContext): void
{
/** @var SystemConfigService $systemConfigService */
$systemConfigService = $this->container->get(SystemConfigService::class);
$systemConfigService->set('core.basicInformation.acceptAllCookies', true);
$this->getCustomFieldSetRepository()->upsert([
[
'name' => 'custom_setup',
'config' => [
'label' => [
'en-GB' => 'ECONSOR Setup',
'de-DE' => 'ECONSOR Setup'
],
],
'customFields' => [
[
'name' => 'custom_meta_robots',
'type' => CustomFieldTypes::BOOL,
'config' => [
'componentName' => 'sw-field',
'type' => 'checkbox',
'customFieldType' => 'checkbox',
'customFieldPosition' => 1,
'label' => [
'en-GB' => 'Noindex?',
'de-DE' => 'Noindex?'
],
]
],
],
'relations' => [
[
'entityName' => 'sales_channel'
],
[
'entityName' => 'category'
],
[
'entityName' => 'product'
],
]
]
], $installContext->getContext());
}
public function uninstall(UninstallContext $uninstallContext): void
{
if ($uninstallContext->keepUserData()) {
parent::uninstall($uninstallContext);
return;
}
$this->removeCustomField($uninstallContext);
parent::uninstall($uninstallContext);
}
private function removeCustomField(UninstallContext $uninstallContext): void
{
$fieldIds = $this->customFieldsExist($uninstallContext->getContext());
if ($fieldIds) {
$this
->getCustomFieldSetRepository()
->delete(array_values($fieldIds->getData()), $uninstallContext->getContext());
}
}
private function customFieldsExist(Context $context): ?IdSearchResult
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsAnyFilter('name', ['custom_setup']));
$ids = $this->getCustomFieldSetRepository()->searchIds($criteria, $context);
return $ids->getTotal() > 0 ? $ids : null;
}
private function getCustomFieldSetRepository(): EntityRepository
{
$repository = $this->container->get('custom_field_set.repository');
assert($repository instanceof EntityRepository);
return $repository;
}
}