MainConfiguration::addValidatorValidation()   B
last analyzed

Complexity

Conditions 4
Paths 1

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 12
nc 1
nop 1
1
<?php
2
3
/**
4
 * Copyright 2014 Jonathan Bouzekri. All rights reserved.
5
 *
6
 * @copyright Copyright 2014 Jonathan Bouzekri <[email protected]>
7
 * @license https://github.com/jbouzekri/FileUploaderBundle/blob/master/LICENSE
8
 * @link https://github.com/jbouzekri/FileUploaderBundle
9
 */
10
11
namespace Jb\Bundle\FileUploaderBundle\DependencyInjection;
12
13
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
14
use Symfony\Component\Config\Definition\ConfigurationInterface;
15
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
16
17
/**
18
 * JbFileUploaderBundle configuration structure.
19
 *
20
 * @author Jonathan Bouzekri <[email protected]>
21
 */
22
class MainConfiguration implements ConfigurationInterface
23
{
24
    /**
25
     * @var array
26
     */
27
    protected $factories;
28
29
    /**
30
     * Constructor
31
     *
32
     * @param array $factories
33
     */
34
    public function __construct(array $factories)
35
    {
36
        $this->factories = $factories;
37
    }
38
39
    /**
40
     * Generates the configuration tree builder.
41
     *
42
     * @return TreeBuilder The tree builder
43
     */
44
    public function getConfigTreeBuilder()
45
    {
46
        $treeBuilder = new TreeBuilder();
47
        $rootNode = $treeBuilder->root('jb_fileuploader');
48
49
        $this->addResolversSection($rootNode, $this->factories);
50
51
        $rootNode
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 children() 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...
52
            ->children()
53
                ->scalarNode('upload_resolver')->end()
54
                ->scalarNode('croped_resolver')->end()
55
                ->scalarNode('crop_route')->defaultValue('jb_image_crop_endpoint')->end()
56
                ->scalarNode('croped_fs')->end()
57
                ->arrayNode('endpoints')
58
                    ->defaultValue(array())
59
                    ->prototype('array')
60
                        ->children()
61
                            ->scalarNode('upload_resolver')->end()
62
                            ->scalarNode('croped_resolver')->end()
63
                            ->scalarNode('croped_fs')->end()
64
                            ->append($this->getValidators('upload_validators'))
65
                            ->append($this->getValidators('crop_validators'))
66
                        ->end()
67
                    ->end()
68
                ->end()
69
            ->end();
70
71
        return $treeBuilder;
72
    }
73
74
    /**
75
     * Add resolvers section
76
     *
77
     * @param \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition $node
78
     * @param array $factories
79
     */
80
    protected function addResolversSection(ArrayNodeDefinition $node, array $factories)
81
    {
82
        $resolverNodeBuilder = $node
83
            ->fixXmlConfig('resolver')
84
            ->children()
85
                ->arrayNode('resolvers')
86
                    ->useAttributeAsKey('name')
87
                    ->prototype('array')
88
                    ->performNoDeepMerging()
89
                    ->children()
90
        ;
91
92
        foreach ($factories as $name => $factory) {
93
            $factoryNode = $resolverNodeBuilder->arrayNode($name)->canBeUnset();
94
95
            $factory->addConfiguration($factoryNode);
96
        }
97
    }
98
99
    /**
100
     * Add a custom validator key to configuration
101
     *
102
     * @param $key
103
     *
104
     * @param string $key
105
     *
106
     * @return TreeBuilder
107
     */
108
    protected function getValidators($key)
109
    {
110
        $treeBuilder = new TreeBuilder();
111
        $rootNode = $treeBuilder->root($key);
112
113
        $rootNode
0 ignored issues
show
Bug introduced by
The method beforeNormalization() does not seem to exist on object<Symfony\Component...on\Builder\NodeBuilder>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
114
            ->defaultValue(array())
115
            ->prototype('variable')
116
            ->end()
117
            ->beforeNormalization()
118
                ->always()
119
                ->then(function ($values) {
120
                    // Normalize null as array
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
121
                    foreach ($values as $key => $value) {
122
                        if ($value === null) {
123
                            $values[$key] = array();
124
                        }
125
                    }
126
                    return $values;
127
                })
128
            ->end();
129
130
        $this->addValidatorValidation($rootNode);
131
132
        return $rootNode;
133
    }
134
135
    /**
136
     * Add validation to a validator key
137
     *
138
     * @param ArrayNodeDefinition $node
139
     */
140
    protected function addValidatorValidation(ArrayNodeDefinition $node)
141
    {
142
        $node->validate()
143
            ->ifTrue(function ($value) {
144
                if (!is_array($value)) {
145
                    return true;
146
                }
147
148
                // All key must be string. Used as alias for the validator service
149
                if (count(array_filter(array_keys($value), 'is_string')) != count($value)) {
150
                    return true;
151
                }
152
153
                // All value must be array. Used as configuration for validator
154
                if (count(array_filter(array_values($value), 'is_array')) != count($value)) {
155
                    return true;
156
                }
157
158
                return false;
159
            })
160
            ->thenInvalid('Invalid validators configuration')
161
        ->end();
162
    }
163
}
164