Completed
Push — master ( 05aecd...a61eba )
by Daniel
03:35
created

YamlRpcLoader   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 158
Duplicated Lines 7.59 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 5
Bugs 2 Features 1
Metric Value
wmc 31
c 5
b 2
f 1
lcom 1
cbo 8
dl 12
loc 158
rs 9.8

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 3
C load() 0 48 9
B parseImport() 0 23 4
A parseRoute() 0 21 4
C validate() 12 27 7
A supports() 0 4 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Cmobi\RabbitmqBundle\Routing\Loader;
4
5
use Cmobi\RabbitmqBundle\Routing\Method;
6
use Cmobi\RabbitmqBundle\Routing\MethodCollection;
7
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
8
use Symfony\Component\Config\FileLocator;
9
use Symfony\Component\Config\Loader\FileLoader;
10
use Symfony\Component\Config\Resource\FileResource;
11
use Symfony\Component\DependencyInjection\ContainerInterface;
12
use Symfony\Component\Yaml\Exception\ParseException;
13
use Symfony\Component\Yaml\Parser as YamlParser;
14
15
class YamlRpcLoader extends FileLoader
16
{
17
18
    private static $availableKeys = [
19
        'method', 'type', 'defaults', 'resource'
20
    ];
21
22
    private $yamlParser;
23
    private $controllerParser;
24
    private $container;
25
26
    public function __construct(ContainerInterface $container, $path = null, ControllerNameParser $controllerNameConverser = null)
27
    {
28
        $this->controllerParser = $controllerNameConverser;
29
        $this->container = $container;
30
31
        if (is_null($controllerNameConverser)) {
32
            $this->controllerParser = $container->get('controller_name_converter');
33
        }
34
35
        if (is_null($path)) {
36
            $path = '%kernel.dir_src%/Resources';
37
        }
38
        $locator = new FileLocator($path);
39
        parent::__construct($locator);
40
    }
41
42
    public function load($file, $type = null)
43
    {
44
        $path = $this->locator->locate($file);
45
46
        if (!stream_is_local($path)) {
47
            throw new \InvalidArgumentException(sprintf('This is not a local file "%s".', $path));
48
        }
49
50
        if (!file_exists($path)) {
51
            throw new \InvalidArgumentException(sprintf('File "%s" not found.', $path));
52
        }
53
54
        if (null === $this->yamlParser) {
55
            $this->yamlParser = new YamlParser();
56
        }
57
58
        try {
59
            $parsedConfig = $this->yamlParser->parse(file_get_contents($path));
60
        } catch (ParseException $e) {
61
            throw new \InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML.', $path), 0, $e);
62
        }
63
64
        $collection = new MethodCollection();
65
        $collection->addResource(new FileResource($path));
0 ignored issues
show
Bug introduced by
It seems like $path defined by $this->locator->locate($file) on line 44 can also be of type array; however, Symfony\Component\Config...Resource::__construct() does only seem to accept string, 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...
66
67
        // empty file
68
        if (null === $parsedConfig) {
69
            return $collection;
70
        }
71
72
        // not an array
73
        if (!is_array($parsedConfig)) {
74
            throw new \InvalidArgumentException(sprintf('The file "%s" must contain a YAML array.', $path));
75
        }
76
77
        foreach ($parsedConfig as $name => $config) {
78
79
            $this->validate($config, $name, $path);
80
81
            if (isset($config['resource'])) {
82
                $this->parseImport($collection, $config, $path, $file);
83
            } else {
84
                $this->parseRoute($collection, $name, $config);
85
            }
86
        }
87
88
        return $collection;
89
    }
90
91
    protected function parseImport(MethodCollection $collection, array $config, $path, $file)
92
    {
93
        $defaults = [];
94
95
        if (isset($config['defaults'])) {
96
            $defaults = $config['defaults'];
97
        }
98
        $type = null;
99
100
        if (isset($config['type'])) {
101
            $type = $config['type'];
102
        }
103
        $this->setCurrentDir(dirname($path));
104
        $resource = $config['resource'];
105
106
        if (substr($resource, 0, 1) === '@') {
107
            $resource = $this->container->get('kernel')->locateResource($config['resource']);
108
        }
109
        $subCollection = $this->import($resource, $type, false, $file);
110
        $subCollection->addDefaults($defaults);
111
112
        $collection->addCollection($subCollection);
113
    }
114
115
    protected function parseRoute(MethodCollection $collection, $name, array $config)
116
    {
117
        $defaults = [];
118
119
        if (isset($config['defaults'])) {
120
            $defaults = $config['defaults'];
121
        }
122
        $route = new Method(null, $config['method'], $defaults);
123
124
        if ($controller = $route->getDefault('_controller')) {
125
            try {
126
                $controller = $this->controllerParser->parse($controller);
127
            } catch (\Exception $e) {
128
                // unable to optimize unknown notation
129
            }
130
131
            $route->setDefault('_controller', $controller);
132
        }
133
134
        $collection->add($name, $route);
135
    }
136
137
    protected function validate($config, $name, $path)
138
    {
139
        if (!is_array($config)) {
140
            throw new \InvalidArgumentException(sprintf('The definition of "%s" in "%s" must be a YAML array.', $name, $path));
141
        }
142
143
        if ($extraKeys = array_diff(array_keys($config), self::$availableKeys)) {
144
            throw new \InvalidArgumentException(sprintf(
145
                'The routing file "%s" contains unsupported keys for "%s": "%s". Expected one of: "%s".',
146
                $path, $name, implode('", "', $extraKeys), implode('", "', self::$availableKeys)
147
            ));
148
        }
149
150 View Code Duplication
        if (isset($config['resource']) && isset($config['method'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
151
            throw new \InvalidArgumentException(sprintf(
152
                'The routing file "%s" must not specify both the "resource" key and the "method" key for "%s". Choose between an import and a route definition.',
153
                $path, $name
154
            ));
155
        }
156
157 View Code Duplication
        if (!isset($config['resource']) && isset($config['type'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
158
            throw new \InvalidArgumentException(sprintf(
159
                'The "type" key for the route definition "%s" in "%s" is unsupported. It is only available for imports in combination with the "resource" key.',
160
                $name, $path
161
            ));
162
        }
163
    }
164
165
    /**
166
     * {@inheritdoc}
167
     */
168
    public function supports($resource, $type = null)
169
    {
170
        return is_string($resource) && in_array(pathinfo($resource, PATHINFO_EXTENSION), array('yml', 'yaml'), true) && (!$type || 'yaml' === $type);
0 ignored issues
show
Bug Best Practice introduced by
The expression $type of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
171
    }
172
}