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

StickerProductFixture::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 StickerProductFixture 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 'sticker_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' => 'stickers',
100
                    'name' => 'Stickers',
101
                ]
102
            ]
103
        ]]]);
104
105
        $this->productAttributeFixture->load(['custom' => [
106
            ['name' => 'Sticker paper', 'code' => 'sticker_paper', 'type' => TextAttributeType::TYPE],
107
            ['name' => 'Sticker resolution', 'code' => 'sticker_resolution', 'type' => TextAttributeType::TYPE],
108
        ]]);
109
110
        $this->productOptionFixture->load(['custom' => [
111
            [
112
                'name' => 'Sticker size',
113
                'code' => 'sticker_size',
114
                'values' => [
115
                    'sticker_size-3' => '3"',
116
                    'sticker_size_5' => '5"',
117
                    'sticker_size_7' => '7"',
118
                ],
119
            ],
120
        ]]);
121
122
        $products = [];
123
        $productsNames = $this->getUniqueNames($options['amount']);
124
        for ($i = 0; $i < $options['amount']; ++$i) {
125
            $products[] = [
126
                'name' => sprintf('Sticker "%s"', $productsNames[$i]),
127
                'code' => $this->faker->uuid,
128
                'main_taxon' => 'stickers',
129
                'taxons' => ['stickers'],
130
                'product_attributes' => [
131
                    'sticker_paper' => sprintf('Paper from tree %s', $this->faker->randomElement(['Wung', 'Tanajno', 'Lemon-San', 'Me-Gusta'])),
132
                    'sticker_resolution' => $this->faker->randomElement(['JKM XD', '476DPI', 'FULL HD', '200DPI']),
133
                ],
134
                'product_options' => ['sticker_size'],
135
                'images' => [
136
                    'main' => sprintf('%s/../Resources/fixtures/%s', __DIR__, 'stickers.jpg'),
137
                    'thumbnail' => sprintf('%s/../Resources/fixtures/%s', __DIR__, 'stickers.jpg'),
138
                ],
139
            ];
140
        }
141
142
        $this->productFixture->load(['custom' => $products]);
143
    }
144
145
    /**
146
     * {@inheritdoc}
147
     */
148
    protected function configureOptionsNode(ArrayNodeDefinition $optionsNode)
149
    {
150
        $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...
151
            ->children()
152
                ->integerNode('amount')->isRequired()->min(0)->end()
153
        ;
154
    }
155
156
    /**
157
     * @param int $amount
158
     *
159
     * @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...
160
     */
161
    private function getUniqueNames($amount)
162
    {
163
        $productsNames = [];
164
165
        for ($i = 0; $i < $amount; ++$i) {
166
            $name = $this->faker->word;
167
            while (in_array($name, $productsNames)) {
168
                $name = $this->faker->word;
169
            }
170
            $productsNames[] = $name;
171
        }
172
173
        return $productsNames;
174
    }
175
}
176