Completed
Push — master ( be577c...c616e0 )
by Paweł
17:41 queued 08:27
created

SimilarProductAssociationFixture::load()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
cc 2
eloc 14
nc 2
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\Core\Model\ProductInterface;
16
use Sylius\Component\Core\Repository\ProductRepositoryInterface;
17
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
18
use Symfony\Component\OptionsResolver\OptionsResolver;
19
20
/**
21
 * @author Grzegorz Sadowski <[email protected]>
22
 */
23
class SimilarProductAssociationFixture extends AbstractFixture
24
{
25
    /**
26
     * @var AbstractResourceFixture
27
     */
28
    private $productAssociationTypeFixture;
29
30
    /**
31
     * @var AbstractResourceFixture
32
     */
33
    private $productAssociationFixture;
34
35
    /**
36
     * @var ProductRepositoryInterface
37
     */
38
    private $productRepository;
39
40
    /**
41
     * @var \Faker\Generator
42
     */
43
    private $faker;
44
45
    /**
46
     * @var OptionsResolver
47
     */
48
    private $optionsResolver;
49
50
    /**
51
     * @param AbstractResourceFixture $productAssociationTypeFixture
52
     * @param AbstractResourceFixture $productAssociationFixture
53
     * @param ProductRepositoryInterface $productRepository
54
     */
55
    public function __construct(
56
        AbstractResourceFixture $productAssociationTypeFixture,
57
        AbstractResourceFixture $productAssociationFixture,
58
        ProductRepositoryInterface $productRepository
59
    ) {
60
        $this->productAssociationTypeFixture = $productAssociationTypeFixture;
61
        $this->productAssociationFixture = $productAssociationFixture;
62
        $this->productRepository = $productRepository;
63
64
        $this->faker = \Faker\Factory::create();
65
        $this->optionsResolver =
66
            (new OptionsResolver())
67
                ->setRequired('amount')
68
                ->setAllowedTypes('amount', 'int')
69
        ;
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function getName()
76
    {
77
        return 'similar_product_association';
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83
    public function load(array $options)
84
    {
85
        $options = $this->optionsResolver->resolve($options);
86
87
        $this->productAssociationTypeFixture->load(['custom' => [[
88
            'code' => 'similar_products',
89
            'name' => 'Similar products',
90
        ]]]);
91
92
        $products = $this->productRepository->findAll();
93
        $products = $this->faker->randomElements($products, $options['amount']);
94
95
        $productAssociations = [];
96
        /** @var ProductInterface $product */
97
        foreach ($products as $product) {
98
            $productAssociations[] = [
99
                'type' => 'similar_products',
100
                'owner' => $product->getCode(),
101
                'associated_products' => $this->getAssociatedProductsAsArray($product),
102
            ];
103
        }
104
105
        $this->productAssociationFixture->load(['custom' => $productAssociations]);
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111
    protected function configureOptionsNode(ArrayNodeDefinition $optionsNode)
112
    {
113
        $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...
114
            ->children()
115
                ->integerNode('amount')->isRequired()->min(0)->end()
116
        ;
117
    }
118
119
    /**
120
     * @param ProductInterface $owner
121
     *
122
     * @return string[]
123
     */
124
    private function getAssociatedProductsAsArray(ProductInterface $owner)
125
    {
126
        $products = $this->productRepository->findBy(['mainTaxon' => $owner->getMainTaxon()]);
127
        $products = $this->faker->randomElements($products, 3);
128
129
        $associatedProducts = [];
130
        /** @var ProductInterface $product */
131
        foreach ($products as $product) {
132
            $associatedProducts[] = $product->getCode();
133
        }
134
135
        return $associatedProducts;
136
    }
137
}
138