Completed
Push — to-be-a-hat-or-not-to-be-kuhwa ( 7c7f7b...b72886 )
by Kamil
20:35
created

TshirtProductFixture::getUniqueNames()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
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
namespace Sylius\Bundle\CoreBundle\Fixture;
13
14
use Sylius\Bundle\FixturesBundle\Fixture\AbstractFixture;
15
use Sylius\Component\Attribute\AttributeType\TextAttributeType;
16
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
17
use Symfony\Component\OptionsResolver\OptionsResolver;
18
19
/**
20
 * @author Kamil Kokot <[email protected]>
21
 */
22
final class TshirtProductFixture extends AbstractFixture
23
{
24
    /**
25
     * @var TaxonFixture
26
     */
27
    private $taxonFixture;
28
29
    /**
30
     * @var ProductAttributeFixture
31
     */
32
    private $productAttributeFixture;
33
34
    /**
35
     * @var ProductOptionFixture
36
     */
37
    private $productOptionFixture;
38
39
    /**
40
     * @var ProductFixture
41
     */
42
    private $productFixture;
43
44
    /**
45
     * @var \Faker\Generator
46
     */
47
    private $faker;
48
49
    /**
50
     * @var OptionsResolver
51
     */
52
    private $optionsResolver;
53
54
    /**
55
     * @param TaxonFixture $taxonFixture
56
     * @param ProductAttributeFixture $productAttributeFixture
57
     * @param ProductOptionFixture $productOptionFixture
58
     * @param ProductFixture $productFixture
59
     */
60
    public function __construct(
61
        TaxonFixture $taxonFixture,
62
        ProductAttributeFixture $productAttributeFixture,
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $productAttributeFixture exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
63
        ProductOptionFixture $productOptionFixture,
64
        ProductFixture $productFixture
65
    ) {
66
        $this->taxonFixture = $taxonFixture;
67
        $this->productAttributeFixture = $productAttributeFixture;
68
        $this->productOptionFixture = $productOptionFixture;
69
        $this->productFixture = $productFixture;
70
71
        $this->faker = \Faker\Factory::create();
72
        $this->optionsResolver =
73
            (new OptionsResolver())
74
                ->setRequired('amount')
75
                ->setAllowedTypes('amount', 'int')
76
        ;
77
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82
    public function getName()
83
    {
84
        return 'tshirt_product';
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public function load(array $options)
91
    {
92
        $options = $this->optionsResolver->resolve($options);
93
94
        $this->taxonFixture->load(['custom' => [[
95
            'code' => 'category',
96
            'name' => 'Category',
97
            'children' => [
98
                [
99
                    'code' => 't_shirts',
100
                    'name' => 'T-Shirts',
101
                    'children' => [
102
                        [
103
                            'code' => 'mens_t_shirts',
104
                            'name' => 'Men',
105
                        ],
106
                        [
107
                            'code' => 'womens_t_shirts',
108
                            'name' => 'Women',
109
                        ],
110
                    ],
111
                ],
112
            ],
113
        ]]]);
114
115
        $this->productAttributeFixture->load(['custom' => [
116
            ['name' => 'T-Shirt brand', 'code' => 't_shirt_brand', 'type' => TextAttributeType::TYPE],
117
            ['name' => 'T-Shirt collection', 'code' => 't_shirt_collection', 'type' => TextAttributeType::TYPE],
118
            ['name' => 'T-Shirt material', 'code' => 't_shirt_material', 'type' => TextAttributeType::TYPE],
119
        ]]);
120
121
        $this->productOptionFixture->load(['custom' => [
122
            [
123
                'name' => 'T-Shirt color',
124
                'code' => 't_shirt_color',
125
                'values' => [
126
                    't_shirt_color_red' => 'Red',
127
                    't_shirt_color_black' => 'Black',
128
                    't_shirt_color_white' => 'White',
129
                ],
130
            ],
131
            [
132
                'name' => 'T-Shirt size',
133
                'code' => 't_shirt_size',
134
                'values' => [
135
                    't_shirt_size_s' => 'S',
136
                    't_shirt_size_m' => 'M',
137
                    't_shirt_size_l' => 'L',
138
                    't_shirt_size_xl' => 'XL',
139
                    't_shirt_size_xxl' => 'XXL',
140
                ],
141
            ],
142
        ]]);
143
144
        $products = [];
145
        $productsNames = $this->getUniqueNames($options['amount']);
146
        for ($i = 0; $i < $options['amount']; ++$i) {
147
            $categoryTaxonCode = $this->faker->randomElement(['mens_t_shirts', 'womens_t_shirts']);
148
149
            $products[] = [
150
                'name' => sprintf('T-Shirt "%s"', $productsNames[$i]),
151
                'code' => $this->faker->uuid,
152
                'main_taxon' => $categoryTaxonCode,
153
                'taxons' => [$categoryTaxonCode],
154
                'product_attributes' => [
155
                    't_shirt_brand' => $this->faker->randomElement(['Nike', 'Adidas', 'JKM-476 Streetwear', 'Potato', 'Centipede Wear']),
156
                    't_shirt_collection' => sprintf('Sylius %s %s', $this->faker->randomElement(['Summer', 'Winter', 'Spring', 'Autumn']), mt_rand(1995, 2012)),
157
                    't_shirt_material' => $this->faker->randomElement(['Centipede', 'Wool', 'Centipede 10% / Wool 90%', 'Potato 100%']),
158
                ],
159
                'product_options' => ['t_shirt_color', 't_shirt_size'],
160
                'images' => [
161
                    'main' => sprintf('%s/../Resources/fixtures/%s', __DIR__, 't-shirts.jpg'),
162
                    'thumbnail' => sprintf('%s/../Resources/fixtures/%s', __DIR__, 't-shirts.jpg'),
163
                ],
164
            ];
165
        }
166
167
        $this->productFixture->load(['custom' => $products]);
168
    }
169
170
    /**
171
     * {@inheritdoc}
172
     */
173
    protected function configureOptionsNode(ArrayNodeDefinition $optionsNode)
174
    {
175
        $optionsNode
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Config...\Builder\NodeDefinition as the method min() does only exist in the following sub-classes of Symfony\Component\Config...\Builder\NodeDefinition: Symfony\Component\Config...der\FloatNodeDefinition, Symfony\Component\Config...r\IntegerNodeDefinition, Symfony\Component\Config...r\NumericNodeDefinition. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
176
            ->children()
177
                ->integerNode('amount')->isRequired()->min(0)->end()
178
        ;
179
    }
180
181
    /**
182
     * @param int $amount
183
     *
184
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be array? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
185
     */
186
    private function getUniqueNames($amount)
187
    {
188
        $productsNames = [];
189
190
        for ($i = 0; $i < $amount; ++$i) {
191
            $name = $this->faker->word;
192
            while (in_array($name, $productsNames)) {
193
                $name = $this->faker->word;
194
            }
195
            $productsNames[] = $name;
196
        }
197
198
        return $productsNames;
199
    }
200
}
201