<?php declare(strict_types=1);
namespace Crehler\Inspirations;
use Shopware\Core\Framework\Context;
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\DataAbstractionLayer\Search\IdSearchResult;
use Shopware\Core\Framework\Plugin;
use Shopware\Core\Framework\Plugin\Context\ActivateContext;
use Shopware\Core\Framework\Plugin\Context\DeactivateContext;
use Shopware\Core\System\CustomField\CustomFieldTypes;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
class CrehlerInspirations extends Plugin
{
public const CATEGORY_CUSTOM_FIELDS = [
'name' => 'crehler_category_is_inspirations',
'type' => CustomFieldTypes::BOOL,
];
public function build(ContainerBuilder $container): void
{
parent::build($container);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/DependencyInjection/'));
$loader->load('entity.xml');
$loader->load('subscriber.xml');
$loader->load('service.xml');
$loader->load('snippets.xml');
$loader->load('message.xml');
}
public function activate(ActivateContext $activateContext): void
{
$this->activateCustomField(self::CATEGORY_CUSTOM_FIELDS, $activateContext->getContext(), $this->container->get('custom_field.repository'));
}
public function deactivate(DeactivateContext $deactivateContext): void
{
}
private function activateCustomField(array $customField, Context $context, EntityRepositoryInterface $customFieldRepository): void
{
$customFieldIds = $this->getCustomFieldIds($customField, $context, $customFieldRepository);
if ($customFieldIds->getTotal() !== 0) {
return;
}
$customFieldRepository->upsert([$customField], $context);
}
private function getCustomFieldIds(array $customField, Context $context, EntityRepositoryInterface $customFieldRepository): IdSearchResult
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('name', $customField['name']));
return $customFieldRepository->searchIds($criteria, $context);
}
}