Completed
Push — 1.3 ( ea96f1...08f6de )
by Kamil
13:44
created

HasTaxonRuleUpdater::updateAfterDeletingTaxon()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Sylius\Component\Core\Promotion\Updater\Rule;
15
16
use Doctrine\ORM\EntityManagerInterface;
17
use Sylius\Component\Core\Model\TaxonInterface;
18
use Sylius\Component\Core\Promotion\Checker\Rule\HasTaxonRuleChecker;
19
use Sylius\Component\Promotion\Model\PromotionRuleInterface;
20
use Sylius\Component\Resource\Repository\RepositoryInterface;
21
22
final class HasTaxonRuleUpdater implements TaxonAwareRuleUpdaterInterface
23
{
24
    /** @var RepositoryInterface */
25
    private $promotionRuleRepository;
26
27
    /** @var EntityManagerInterface */
28
    private $manager;
29
30
    public function __construct(RepositoryInterface $promotionRuleRepository, EntityManagerInterface $manager)
31
    {
32
        $this->promotionRuleRepository = $promotionRuleRepository;
33
        $this->manager = $manager;
34
    }
35
36
    public function updateAfterDeletingTaxon(TaxonInterface $taxon): array
37
    {
38
        $updatedPromotionCodes = [];
39
        $promotionRules = $this->promotionRuleRepository->findBy(['type' => HasTaxonRuleChecker::TYPE]);
40
41
        /** @var PromotionRuleInterface $promotionRule */
42
        foreach ($promotionRules as $promotionRule) {
43
            $configuration = $promotionRule->getConfiguration();
44
            if (in_array($taxon->getCode(), $configuration['taxons'])) {
45
                $configuration['taxons'] = array_values(array_diff($configuration['taxons'], [$taxon->getCode()]));
46
                $promotionRule->setConfiguration($configuration);
47
48
                $updatedPromotionCodes[] = $promotionRule->getPromotion()->getCode();
49
            }
50
        }
51
52
        $this->manager->flush();
53
54
        return $updatedPromotionCodes;
55
    }
56
}
57