Completed
Push — 1.4-autowiring-for-resource-bu... ( cfe966...176999 )
by Kamil
09:09
created

ShippingMethodExampleFactory::create()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 35
rs 8.7377
c 0
b 0
f 0
cc 6
nc 16
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\Bundle\CoreBundle\Fixture\Factory;
15
16
use Sylius\Bundle\CoreBundle\Fixture\OptionsResolver\LazyOption;
17
use Sylius\Component\Addressing\Model\ZoneInterface;
18
use Sylius\Component\Channel\Repository\ChannelRepositoryInterface;
19
use Sylius\Component\Core\Formatter\StringInflector;
20
use Sylius\Component\Core\Model\ChannelInterface;
21
use Sylius\Component\Core\Model\ShippingMethodInterface;
22
use Sylius\Component\Locale\Model\LocaleInterface;
23
use Sylius\Component\Resource\Factory\FactoryInterface;
24
use Sylius\Component\Resource\Repository\RepositoryInterface;
25
use Sylius\Component\Shipping\Calculator\DefaultCalculators;
26
use Sylius\Component\Shipping\Model\ShippingCategoryInterface;
27
use Sylius\Component\Taxation\Model\TaxCategoryInterface;
28
use Symfony\Component\OptionsResolver\Options;
29
use Symfony\Component\OptionsResolver\OptionsResolver;
30
31
class ShippingMethodExampleFactory extends AbstractExampleFactory implements ExampleFactoryInterface
32
{
33
    /** @var FactoryInterface */
34
    private $shippingMethodFactory;
35
36
    /** @var RepositoryInterface */
37
    private $zoneRepository;
38
39
    /** @var RepositoryInterface */
40
    private $shippingCategoryRepository;
41
42
    /** @var RepositoryInterface */
43
    private $taxCategoryRepository;
44
45
    /** @var RepositoryInterface */
46
    private $localeRepository;
47
48
    /** @var ChannelRepositoryInterface */
49
    private $channelRepository;
50
51
    /** @var \Faker\Generator */
52
    private $faker;
53
54
    /** @var OptionsResolver */
55
    private $optionsResolver;
56
57
    public function __construct(
58
        FactoryInterface $shippingMethodFactory,
59
        RepositoryInterface $zoneRepository,
60
        RepositoryInterface $shippingCategoryRepository,
61
        RepositoryInterface $localeRepository,
62
        ChannelRepositoryInterface $channelRepository,
63
        ?RepositoryInterface $taxCategoryRepository = null
64
    ) {
65
        $this->shippingMethodFactory = $shippingMethodFactory;
66
        $this->zoneRepository = $zoneRepository;
67
        $this->shippingCategoryRepository = $shippingCategoryRepository;
68
        $this->taxCategoryRepository = $taxCategoryRepository;
69
        if($this->taxCategoryRepository === null) {
70
            @trigger_error(sprintf('Not passing a $taxCategoryRepository to %s constructor is deprecated since Sylius 1.4 and will be removed in Sylius 2.0.', self::class), \E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
71
        }
72
        $this->localeRepository = $localeRepository;
73
        $this->channelRepository = $channelRepository;
74
75
        $this->faker = \Faker\Factory::create();
76
        $this->optionsResolver = new OptionsResolver();
77
78
        $this->configureOptions($this->optionsResolver);
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function create(array $options = []): ShippingMethodInterface
85
    {
86
        $options = $this->optionsResolver->resolve($options);
87
88
        /** @var ShippingMethodInterface $shippingMethod */
89
        $shippingMethod = $this->shippingMethodFactory->createNew();
90
        $shippingMethod->setCode($options['code']);
91
        $shippingMethod->setEnabled($options['enabled']);
92
        $shippingMethod->setZone($options['zone']);
93
        $shippingMethod->setCalculator($options['calculator']['type']);
94
        $shippingMethod->setConfiguration($options['calculator']['configuration']);
95
        $shippingMethod->setArchivedAt($options['archived_at']);
96
97
        if (array_key_exists('category', $options)) {
98
            $shippingMethod->setCategory($options['category']);
99
        }
100
101
        if (array_key_exists('tax_category', $options) && ($options['tax_category'] instanceof TaxCategoryInterface)) {
102
            $shippingMethod->setTaxCategory($options['tax_category']);
103
        }
104
105
        foreach ($this->getLocales() as $localeCode) {
106
            $shippingMethod->setCurrentLocale($localeCode);
107
            $shippingMethod->setFallbackLocale($localeCode);
108
109
            $shippingMethod->setName($options['name']);
110
            $shippingMethod->setDescription($options['description']);
111
        }
112
113
        foreach ($options['channels'] as $channel) {
114
            $shippingMethod->addChannel($channel);
115
        }
116
117
        return $shippingMethod;
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123
    protected function configureOptions(OptionsResolver $resolver): void
124
    {
125
        $resolver
126
            ->setDefault('code', function (Options $options): string {
127
                return StringInflector::nameToCode($options['name']);
128
            })
129
            ->setDefault('name', function (Options $options): string {
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
130
                return $this->faker->words(3, true);
131
            })
132
            ->setDefault('description', function (Options $options): string {
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
133
                return $this->faker->sentence();
134
            })
135
            ->setDefault('enabled', function (Options $options): bool {
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
136
                return $this->faker->boolean(90);
137
            })
138
            ->setAllowedTypes('enabled', 'bool')
139
            ->setDefault('zone', LazyOption::randomOne($this->zoneRepository))
140
            ->setAllowedTypes('zone', ['null', 'string', ZoneInterface::class])
141
            ->setNormalizer('zone', LazyOption::findOneBy($this->zoneRepository, 'code'))
142
            ->setDefined('tax_category')
143
            ->setAllowedTypes('tax_category', ['null', 'string', TaxCategoryInterface::class])
144
            ->setDefined('category')
145
            ->setAllowedTypes('category', ['null', 'string', ShippingCategoryInterface::class])
146
            ->setNormalizer('category', LazyOption::findOneBy($this->shippingCategoryRepository, 'code'))
147
            ->setDefault('calculator', function (Options $options): array {
148
                $configuration = [];
149
                /** @var ChannelInterface $channel */
150
                foreach ($options['channels'] as $channel) {
151
                    $configuration[$channel->getCode()] = ['amount' => $this->faker->randomNumber(4)];
152
                }
153
154
                return [
155
                    'type' => DefaultCalculators::FLAT_RATE,
156
                    'configuration' => $configuration,
157
                ];
158
            })
159
            ->setDefault('channels', LazyOption::all($this->channelRepository))
160
            ->setAllowedTypes('channels', 'array')
161
            ->setNormalizer('channels', LazyOption::findBy($this->channelRepository, 'code'))
162
            ->setDefault('archived_at', null)
163
            ->setAllowedTypes('archived_at', ['null', \DateTimeInterface::class])
164
        ;
165
        if($this->taxCategoryRepository !== null) {
166
            $resolver->setNormalizer('tax_category', LazyOption::findOneBy($this->taxCategoryRepository, 'code'));
167
        }
168
    }
169
170
    private function getLocales(): iterable
171
    {
172
        /** @var LocaleInterface[] $locales */
173
        $locales = $this->localeRepository->findAll();
174
        foreach ($locales as $locale) {
175
            yield $locale->getCode();
176
        }
177
    }
178
}
179