<?php declare(strict_types=1);
namespace Acris\Tax;
use Doctrine\DBAL\Connection;
use Shopware\Core\Content\Rule\Aggregate\RuleCondition\RuleConditionEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\EntitySearchResult;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\MultiFilter;
use Shopware\Core\Framework\Plugin;
use Shopware\Core\Framework\Plugin\Context\UninstallContext;
use Shopware\Core\Framework\Plugin\Context\UpdateContext;
class AcrisTaxCS extends Plugin
{
public function update(UpdateContext $updateContext): void
{
if(version_compare($updateContext->getCurrentPluginVersion(), '2.3.0', '<')
&& version_compare($updateContext->getUpdatePluginVersion(), '2.3.0', '>=')) {
$this->replaceExistingRuleNames($updateContext->getContext());
}
}
public function uninstall(UninstallContext $context): void
{
if ($context->keepUserData()) {
return;
}
$this->cleanupDatabase();
}
private function cleanupDatabase(): void
{
$connection = $this->container->get(Connection::class);
$connection->executeUpdate('DROP TABLE IF EXISTS acris_tax_customer_group_rule');
$connection->executeUpdate('DROP TABLE IF EXISTS acris_tax_country_rule');
try {
$connection->executeUpdate('ALTER TABLE `customer_group` DROP `acrisRules`');
$connection->executeUpdate('ALTER TABLE `country` DROP `acrisRules`');
} catch (\Exception $e) { }
}
private function replaceExistingRuleNames(Context $context)
{
$ruleConditionRepository = $this->container->get('rule_condition.repository');
/** @var EntitySearchResult $existingRuleConditionSearchResult */
$existingRuleConditionSearchResult = $ruleConditionRepository->search((new Criteria())->addFilter(
new MultiFilter(MultiFilter::CONNECTION_OR, [
new EqualsFilter('type', 'customerHasVatIdBillingRule'),
new EqualsFilter('type', 'customerHasVatIdShippingRule')
])
), $context);
if ($existingRuleConditionSearchResult->count() <= 0) {
return;
}
$changedRuleConditions = [];
/** @var RuleConditionEntity $ruleConditionEntity */
foreach ($existingRuleConditionSearchResult->getElements() as $ruleConditionEntity) {
$value = $ruleConditionEntity->getValue();
if(!is_array($value)) {
continue;
}
if(array_key_exists('customerHasVatIdBilling', $value)) {
$value = ['customerHasVatId' => $value['customerHasVatIdBilling']];
} elseif(array_key_exists('customerHasVatIdShipping', $value)) {
$value = ['customerHasVatId' => $value['customerHasVatIdShipping']];
} else {
continue;
}
$changedRuleConditions[] = [
'id' => $ruleConditionEntity->getId(),
'type' => 'customerHasVatIdRule',
'value' => $value
];
}
if(!empty($changedRuleConditions)) {
$ruleConditionRepository->upsert($changedRuleConditions, $context);
}
}
}