Completed
Pull Request — master (#47)
by Eric
32:49
created

ResourceConfiguration::createResourceNode()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 51
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 3.0024

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 51
ccs 29
cts 31
cp 0.9355
rs 9.4109
cc 3
eloc 39
nc 2
nop 2
crap 3.0024

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the Lug package.
5
 *
6
 * (c) Eric GELOEN <[email protected]>
7
 *
8
 * For the full copyright and license information, please read the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Lug\Bundle\ResourceBundle\DependencyInjection\Extension;
13
14
use Lug\Bundle\ResourceBundle\ResourceBundleInterface;
15
use Lug\Component\Resource\Controller\ControllerInterface;
16
use Lug\Component\Resource\Domain\DomainManagerInterface;
17
use Lug\Component\Resource\Factory\FactoryInterface;
18
use Lug\Component\Resource\Model\ResourceInterface;
19
use Lug\Component\Resource\Repository\RepositoryInterface;
20
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
21
use Symfony\Component\Config\Definition\Builder\NodeBuilder;
22
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
23
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
24
use Symfony\Component\Config\Definition\ConfigurationInterface;
25
use Symfony\Component\Form\FormTypeInterface;
26
27
/**
28
 * @author GeLo <[email protected]>
29
 */
30
class ResourceConfiguration implements ConfigurationInterface
31
{
32
    /**
33
     * @var ResourceBundleInterface
34
     */
35
    private $bundle;
36
37
    /**
38
     * @param ResourceBundleInterface $bundle
39
     */
40 7
    public function __construct(ResourceBundleInterface $bundle)
41
    {
42 7
        $this->bundle = $bundle;
43 7
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48 7
    public function getConfigTreeBuilder()
49
    {
50 7
        $treeBuilder = $this->createTreeBuilder();
51 7
        $children = $treeBuilder->root($this->bundle->getAlias())->children();
52
53 7
        $this->configureBundle($children);
54 7
        $children->append($this->createResourceNodes());
55
56 7
        return $treeBuilder;
57
    }
58
59
    /**
60
     * @param NodeBuilder $builder
61
     */
62
    protected function configureBundle(NodeBuilder $builder)
63
    {
64
    }
65
66
    /**
67
     * @return ArrayNodeDefinition
68
     */
69 7
    private function createResourceNodes()
70
    {
71 7
        $resourcesNode = $this->createNode('resources')->addDefaultsIfNotSet();
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 addDefaultsIfNotSet() does only exist in the following sub-classes of Symfony\Component\Config...\Builder\NodeDefinition: Symfony\Component\Config...der\ArrayNodeDefinition. 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...
72 7
        $childrenNode = $resourcesNode->children();
73
74 7
        foreach ($this->bundle->getResources() as $resource) {
75 7
            $childrenNode->append($this->createResourceNode($resource));
76 7
        }
77
78 7
        return $resourcesNode;
79
    }
80
81
    /**
82
     * @param ResourceInterface $resource
83
     * @param string|null       $name
84
     *
85
     * @return ArrayNodeDefinition
86
     */
87 7
    private function createResourceNode(ResourceInterface $resource, $name = null)
88
    {
89 7
        $resourceNode = $this->createNode($name ?: $resource->getName())->addDefaultsIfNotSet();
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 addDefaultsIfNotSet() does only exist in the following sub-classes of Symfony\Component\Config...\Builder\NodeDefinition: Symfony\Component\Config...der\ArrayNodeDefinition. 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...
90 7
        $childrenNode = $resourceNode->children()
91 7
            ->append($this->createDriverNode($resource))
92 7
            ->append($this->createClassNode(
93 7
                'model',
94 7
                $resource->getModel(),
95 7
                $resource->getInterfaces(),
96 7
                true
97 7
            ))
98 7
            ->append($this->createClassNode(
99 7
                'repository',
100 7
                $resource->getRepository(),
101 7
                [RepositoryInterface::class],
102 7
                true
103 7
            ))
104 7
            ->append($this->createClassNode(
105
                'factory',
106 7
                $resource->getFactory(),
107
                [FactoryInterface::class]
108
            ))
109
            ->append($this->createClassNode(
110 7
                'form',
111
                $resource->getForm(),
112
                [FormTypeInterface::class
113
                ]))
114
            ->append($this->createClassNode(
115
                'choice_form',
116
                $resource->getChoiceForm(),
117
                [FormTypeInterface::class]
118 7
            ))
119
            ->append($this->createClassNode(
120 7
                'domain_manager',
121 7
                $resource->getDomainManager(),
122 7
                [DomainManagerInterface::class]
123 7
            ))
124 7
            ->append($this->createClassNode(
125
                'controller',
126 7
                $resource->getController(),
127
                [ControllerInterface::class]
128
            ))
129
            ->append($this->createNode('id_property_path', 'scalar', $resource->getIdPropertyPath()))
130
            ->append($this->createNode('label_property_path', 'scalar', $resource->getLabelPropertyPath()));
131
132
        if ($resource->getTranslation() !== null) {
133
            $childrenNode->append($this->createResourceNode($resource->getTranslation(), 'translation'));
134 7
        }
135
136 7
        return $resourceNode;
137 7
    }
138 7
139 7
    /**
140
     * @param ResourceInterface $resource
141 7
     *
142
     * @return ArrayNodeDefinition
143
     */
144
    private function createDriverNode(ResourceInterface $resource)
145
    {
146
        $driverNode = $this->createNode('driver')->addDefaultsIfNotSet();
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 addDefaultsIfNotSet() does only exist in the following sub-classes of Symfony\Component\Config...\Builder\NodeDefinition: Symfony\Component\Config...der\ArrayNodeDefinition. 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...
147
        $driverNode->children()
148
            ->append($this->createNode('name', 'scalar', $resource->getDriver()))
149
            ->append($this->createNode('manager', 'scalar', $resource->getDriverManager()))
150
            ->append($this->createDriverMappingNode($resource));
151
152
        return $driverNode;
153 7
    }
154
155
    /**
156
     * @param ResourceInterface $resource
157
     *
158
     * @return ArrayNodeDefinition
159
     */
160
    private function createDriverMappingNode(ResourceInterface $resource)
161
    {
162
        $mappingNode = $this->createNode('mapping')->addDefaultsIfNotSet();
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 addDefaultsIfNotSet() does only exist in the following sub-classes of Symfony\Component\Config...\Builder\NodeDefinition: Symfony\Component\Config...der\ArrayNodeDefinition. 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...
163
        $mappingNode->children()
164
            ->append($this->createNode('path', 'scalar', $resource->getDriverMappingPath()))
165
            ->append($this->createNode('format', 'scalar', $resource->getDriverMappingFormat()));
166
167 7
        return $mappingNode;
168
    }
169
170
    /**
171
     * @param string   $name
172
     * @param string   $class
173
     * @param string[] $interfaces
174
     * @param bool     $required
175
     *
176
     * @return NodeDefinition
177
     */
178
    private function createClassNode($name, $class, array $interfaces = [], $required = false)
179 7
    {
180
        return $this->createNode($name, 'scalar', $class, function ($class) use ($interfaces, $required) {
181 7
            if ($class === null) {
182
                return $required;
183 7
            }
184 7
185 7
            if (!class_exists($class)) {
186
                return true;
187 7
            }
188 7
189 7
            $classInterfaces = class_implements($class);
190
191 7
            foreach ($interfaces as $interface) {
192
                if (!in_array($interface, $classInterfaces, true)) {
193
                    return true;
194
                }
195
            }
196
197 7
            return false;
198
        }, 'The %s %%s does not exist.');
199 7
    }
200
201
    /**
202
     * @param string        $name
203
     * @param string        $type
204
     * @param mixed         $default
205
     * @param callable|null $if
206
     * @param string|null   $then
207
     *
208
     * @return ArrayNodeDefinition|NodeDefinition
209
     */
210
    private function createNode($name, $type = 'array', $default = null, $if = null, $then = null)
211
    {
212
        $node = $this->createTreeBuilder()->root($name, $type);
213
214
        if ($default !== null) {
215
            $node->defaultValue($default);
216
        }
217
218
        if ($if !== null && $then !== null) {
219
            $node->validate()->ifTrue($if)->thenInvalid(sprintf($then, $name));
220
        }
221
222
        return $node;
223
    }
224
225
    /**
226
     * @return TreeBuilder
227
     */
228
    private function createTreeBuilder()
229
    {
230
        return new TreeBuilder();
231
    }
232
}
233