Completed
Push — master ( 5472e0...10da27 )
by Eric
18:09 queued 11:39
created

ResourceConfiguration::createResourceNodes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
cc 2
eloc 6
nc 2
nop 0
crap 2
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->createClassNode(
92 7
                'model',
93 7
                $resource->getModel(),
94 7
                $resource->getInterfaces(),
95
                true
96 7
            ))
97 7
            ->append($this->createDriverNode($resource))
98 7
            ->append($this->createClassNode(
99 7
                'repository',
100 7
                $resource->getRepository(),
101 7
                [RepositoryInterface::class]
102 7
            ))
103 7
            ->append($this->createClassNode(
104 7
                'factory',
105 7
                $resource->getFactory(),
106 7
                [FactoryInterface::class]
107 7
            ))
108 7
            ->append($this->createClassNode(
109 7
                'form',
110 7
                $resource->getForm(),
111 7
                [FormTypeInterface::class]
112 7
            ))
113 7
            ->append($this->createClassNode(
114 7
                'choice_form',
115 7
                $resource->getChoiceForm(),
116 7
                [FormTypeInterface::class]
117 7
            ))
118 7
            ->append($this->createClassNode(
119 7
                'domain_manager',
120 7
                $resource->getDomainManager(),
121 7
                [DomainManagerInterface::class]
122 7
            ))
123 7
            ->append($this->createClassNode(
124 7
                'controller',
125 7
                $resource->getController(),
126 7
                [ControllerInterface::class]
127 7
            ))
128 7
            ->append($this->createNode('id_property_path', 'scalar', $resource->getIdPropertyPath()))
129 7
            ->append($this->createNode('label_property_path', 'scalar', $resource->getLabelPropertyPath()));
130
131 7
        foreach ($resource->getRelations() as $name => $relation) {
132
            $childrenNode->append($this->createResourceNode($relation, $name));
133 7
        }
134
135 7
        return $resourceNode;
136
    }
137
138
    /**
139
     * @param ResourceInterface $resource
140
     *
141
     * @return ArrayNodeDefinition
142
     */
143 7
    private function createDriverNode(ResourceInterface $resource)
144
    {
145 7
        $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...
146 7
        $driverNode->children()
147 7
            ->append($this->createNode('name', 'scalar', $resource->getDriver()))
148 7
            ->append($this->createNode('manager', 'scalar', $resource->getDriverManager()))
149 7
            ->append($this->createDriverMappingNode($resource));
150
151 7
        return $driverNode;
152
    }
153
154
    /**
155
     * @param ResourceInterface $resource
156
     *
157
     * @return ArrayNodeDefinition
158
     */
159 7
    private function createDriverMappingNode(ResourceInterface $resource)
160
    {
161 7
        $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...
162 7
        $mappingNode->children()
163 7
            ->append($this->createNode('path', 'scalar', $resource->getDriverMappingPath()))
164 7
            ->append($this->createNode('format', 'scalar', $resource->getDriverMappingFormat()));
165
166 7
        return $mappingNode;
167
    }
168
169
    /**
170
     * @param string   $name
171
     * @param string   $class
172
     * @param string[] $interfaces
173
     * @param bool     $required
174
     *
175
     * @return NodeDefinition
176
     */
177
    private function createClassNode($name, $class, array $interfaces = [], $required = false)
178
    {
179 7
        return $this->createNode($name, 'scalar', $class, function ($class) use ($interfaces, $required) {
180
            if ($class === null) {
181
                return $required;
182
            }
183
184
            if (!class_exists($class)) {
185
                return true;
186
            }
187
188
            $classInterfaces = class_implements($class);
189
190
            foreach ($interfaces as $interface) {
191
                if (!in_array($interface, $classInterfaces, true)) {
192
                    return true;
193
                }
194
            }
195
196
            return false;
197 7
        }, 'The %s %%s does not exist.');
198
    }
199
200
    /**
201
     * @param string        $name
202
     * @param string        $type
203
     * @param mixed         $default
204
     * @param callable|null $if
205
     * @param string|null   $then
206
     *
207
     * @return ArrayNodeDefinition|NodeDefinition
208
     */
209 7
    private function createNode($name, $type = 'array', $default = null, $if = null, $then = null)
210
    {
211 7
        $node = $this->createTreeBuilder()->root($name, $type);
212
213 7
        if ($default !== null) {
214 7
            $node->defaultValue($default);
215 7
        }
216
217 7
        if ($if !== null && $then !== null) {
218 7
            $node->validate()->ifTrue($if)->thenInvalid(sprintf($then, $name));
219 7
        }
220
221 7
        return $node;
222
    }
223
224
    /**
225
     * @return TreeBuilder
226
     */
227 7
    private function createTreeBuilder()
228
    {
229 7
        return new TreeBuilder();
230
    }
231
}
232