Completed
Push — symfony3 ( ec9673...e0eba1 )
by Kamil
18:54
created

AbstractDriver   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 191
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 22
lcom 1
cbo 5
dl 0
loc 191
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 19 4
C setClassesParameters() 0 26 8
B addController() 0 26 1
A addFactory() 0 19 2
B addForms() 0 41 6
A getMetadataDefinition() 0 10 1
addDefaultForm() 0 1 ?
addManager() 0 1 ?
addRepository() 0 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\ResourceBundle\DependencyInjection\Driver;
13
14
use Sylius\Component\Resource\Factory\Factory;
15
use Sylius\Component\Resource\Factory\TranslatableFactoryInterface;
16
use Sylius\Component\Resource\Metadata\Metadata;
17
use Sylius\Component\Resource\Metadata\MetadataInterface;
18
use Symfony\Component\DependencyInjection\ContainerBuilder;
19
use Symfony\Component\DependencyInjection\Definition;
20
use Symfony\Component\DependencyInjection\Parameter;
21
use Symfony\Component\DependencyInjection\Reference;
22
23
/**
24
 * @author Paweł Jędrzejewski <[email protected]>
25
 * @author Arnaud Langlade <[email protected]>
26
 */
27
abstract class AbstractDriver implements DriverInterface
28
{
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function load(ContainerBuilder $container, MetadataInterface $metadata)
33
    {
34
        $this->setClassesParameters($container, $metadata);
35
36
        if ($metadata->hasClass('controller')) {
37
            $this->addController($container, $metadata);
38
        }
39
40
        $this->addManager($container, $metadata);
41
        $this->addRepository($container, $metadata);
42
43
        if ($metadata->hasClass('factory')) {
44
            $this->addFactory($container, $metadata);
45
        }
46
47
        if ($metadata->hasClass('form')) {
48
            $this->addForms($container, $metadata);
49
        }
50
    }
51
52
    /**
53
     * @param ContainerBuilder $container
54
     * @param MetadataInterface $metadata
55
     */
56
    protected function setClassesParameters(ContainerBuilder $container, MetadataInterface $metadata)
57
    {
58
        if ($metadata->hasClass('model')) {
59
            $container->setParameter(sprintf('%s.model.%s.class', $metadata->getApplicationName(), $metadata->getName()), $metadata->getClass('model'));
60
        }
61
        if ($metadata->hasClass('controller')) {
62
            $container->setParameter(sprintf('%s.controller.%s.class', $metadata->getApplicationName(), $metadata->getName()), $metadata->getClass('controller'));
63
        }
64
        if ($metadata->hasClass('factory')) {
65
            $container->setParameter(sprintf('%s.factory.%s.class', $metadata->getApplicationName(), $metadata->getName()), $metadata->getClass('factory'));
66
        }
67
        if ($metadata->hasClass('repository')) {
68
            $container->setParameter(sprintf('%s.repository.%s.class', $metadata->getApplicationName(), $metadata->getName()), $metadata->getClass('repository'));
69
        }
70
71
        if (!$metadata->hasParameter('validation_groups')) {
72
            return;
73
        }
74
75
        $validationGroups = $metadata->getParameter('validation_groups');
76
77
        foreach ($validationGroups as $formName => $groups) {
0 ignored issues
show
Bug introduced by
The expression $validationGroups of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
78
            $suffix = 'default' === $formName ? '' : sprintf('_%s', $formName);
79
            $container->setParameter(sprintf('%s.validation_groups.%s%s', $metadata->getApplicationName(), $metadata->getName(), $suffix), array_merge(['Default'], $groups));
80
        }
81
    }
82
83
    /**
84
     * @param ContainerBuilder $container
85
     * @param MetadataInterface $metadata
86
     */
87
    protected function addController(ContainerBuilder $container, MetadataInterface $metadata)
88
    {
89
        $definition = new Definition($metadata->getClass('controller'));
0 ignored issues
show
Bug introduced by
It seems like $metadata->getClass('controller') targeting Sylius\Component\Resourc...taInterface::getClass() can also be of type array; however, Symfony\Component\Depend...finition::__construct() does only seem to accept string|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
90
        $definition
91
            ->setArguments([
92
                $this->getMetadataDefinition($metadata),
93
                new Reference('sylius.resource_controller.request_configuration_factory'),
94
                new Reference('sylius.resource_controller.view_handler'),
95
                new Reference($metadata->getServiceId('repository')),
96
                new Reference($metadata->getServiceId('factory')),
97
                new Reference('sylius.resource_controller.new_resource_factory'),
98
                new Reference($metadata->getServiceId('manager')),
99
                new Reference('sylius.resource_controller.single_resource_provider'),
100
                new Reference('sylius.resource_controller.resources_collection_provider'),
101
                new Reference('sylius.resource_controller.form_factory'),
102
                new Reference('sylius.resource_controller.redirect_handler'),
103
                new Reference('sylius.resource_controller.flash_helper'),
104
                new Reference('sylius.resource_controller.authorization_checker'),
105
                new Reference('sylius.resource_controller.event_dispatcher'),
106
                new Reference('sylius.resource_controller.state_machine'),
107
            ])
108
            ->addMethodCall('setContainer', [new Reference('service_container')])
109
        ;
110
111
        $container->setDefinition($metadata->getServiceId('controller'), $definition);
112
    }
113
114
    /**
115
     * @param ContainerBuilder $container
116
     * @param MetadataInterface $metadata
117
     */
118
    protected function addFactory(ContainerBuilder $container, MetadataInterface $metadata)
119
    {
120
        $factoryClass = $metadata->getClass('factory');
121
        $modelClass = $metadata->getClass('model');
122
123
        $definition = new Definition($factoryClass);
0 ignored issues
show
Bug introduced by
It seems like $factoryClass defined by $metadata->getClass('factory') on line 120 can also be of type array; however, Symfony\Component\Depend...finition::__construct() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
124
125
        $definitionArgs = [$modelClass];
126
        if (in_array(TranslatableFactoryInterface::class, class_implements($factoryClass))) {
127
            $decoratedDefinition = new Definition(Factory::class);
128
            $decoratedDefinition->setArguments($definitionArgs);
129
130
            $definitionArgs = [$decoratedDefinition, new Reference('sylius_resource.translation.locale_provider')];
131
        }
132
133
        $definition->setArguments($definitionArgs);
134
135
        $container->setDefinition($metadata->getServiceId('factory'), $definition);
136
    }
137
138
    /**
139
     * @param ContainerBuilder $container
140
     * @param MetadataInterface $metadata
141
     */
142
    protected function addForms(ContainerBuilder $container, MetadataInterface $metadata)
143
    {
144
        foreach ($metadata->getClass('form') as $formName => $formClass) {
0 ignored issues
show
Bug introduced by
The expression $metadata->getClass('form') of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
145
            $suffix = 'default' === $formName ? '' : sprintf('_%s', $formName);
146
            $alias = sprintf('%s_%s%s', $metadata->getApplicationName(), $metadata->getName(), $suffix);
147
148
            $definition = new Definition($formClass);
149
150
            switch ($formName) {
151
                case 'choice':
152
                    $definition->addArgument($this->getMetadataDefinition($metadata));
153
                    break;
154
155
                default:
156
                    $validationGroupsParameterName = sprintf('%s.validation_groups.%s%s', $metadata->getApplicationName(), $metadata->getName(), $suffix);
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $validationGroupsParameterName 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...
157
                    $validationGroups = new Parameter($validationGroupsParameterName);
158
159
                    if (!$container->hasParameter($validationGroupsParameterName)) {
160
                        $validationGroups = ['Default'];
161
                    }
162
163
                    $definition->setArguments([
164
                        $metadata->getClass('model'),
165
                        $validationGroups,
166
                    ]);
167
                    break;
168
            }
169
170
            $definition->addTag('form.type', ['alias' => $alias]);
171
172
            $container->setParameter(sprintf('%s.form.type.%s%s.class', $metadata->getApplicationName(), $metadata->getName(), $suffix), $formClass);
173
            $container->setDefinition(
174
                sprintf('%s.form.type.%s%s', $metadata->getApplicationName(), $metadata->getName(), $suffix),
175
                $definition
176
            );
177
        }
178
179
        if (!$container->hasDefinition(sprintf('%s.form.type.%s', $metadata->getApplicationName(), $metadata->getName()))) {
180
            $this->addDefaultForm($container, $metadata);
181
        }
182
    }
183
184
    /**
185
     * @param MetadataInterface $metadata
186
     *
187
     * @return Definition
188
     */
189
    protected function getMetadataDefinition(MetadataInterface $metadata)
190
    {
191
        $definition = new Definition(Metadata::class);
192
        $definition
193
            ->setFactory([new Reference('sylius.resource_registry'), 'get'])
194
            ->setArguments([$metadata->getAlias()])
195
        ;
196
197
        return $definition;
198
    }
199
200
    /**
201
     * @param ContainerBuilder $container
202
     * @param MetadataInterface $metadata
203
     */
204
    abstract protected function addDefaultForm(ContainerBuilder $container, MetadataInterface $metadata);
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
205
206
    /**
207
     * @param ContainerBuilder $container
208
     * @param MetadataInterface $metadata
209
     */
210
    abstract protected function addManager(ContainerBuilder $container, MetadataInterface $metadata);
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
211
212
    /**
213
     * @param ContainerBuilder $container
214
     * @param MetadataInterface $metadata
215
     */
216
    abstract protected function addRepository(ContainerBuilder $container, MetadataInterface $metadata);
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
217
}
218