Completed
Push — master ( f94c4d...339dcc )
by Daniel
03:14
created

YamlRpcLoader::getContainer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
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
25
    public function __construct(ContainerInterface $container, $path = null, ControllerNameParser $controllerNameConverser = null)
26
    {
27
        $this->controllerParser = $controllerNameConverser;
28
29
        if (is_null($controllerNameConverser)) {
30
            $this->controllerParser = $container->get('controller_name_converter');
31
        }
32
33
        if (is_null($path)) {
34
            $path = '%kernel.dir_src%/Resources';
35
        }
36
        $locator = new FileLocator($path);
37
        parent::__construct($locator);
38
    }
39
40
    public function load($file, $type = null)
41
    {
42
        $path = $this->locator->locate($file);
43
44
        if (!stream_is_local($path)) {
45
            throw new \InvalidArgumentException(sprintf('This is not a local file "%s".', $path));
46
        }
47
48
        if (!file_exists($path)) {
49
            throw new \InvalidArgumentException(sprintf('File "%s" not found.', $path));
50
        }
51
52
        if (null === $this->yamlParser) {
53
            $this->yamlParser = new YamlParser();
54
        }
55
56
        try {
57
            $parsedConfig = $this->yamlParser->parse(file_get_contents($path));
58
        } catch (ParseException $e) {
59
            throw new \InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML.', $path), 0, $e);
60
        }
61
62
        $collection = new MethodCollection();
63
        $collection->addResource(new FileResource($path));
0 ignored issues
show
Bug introduced by
It seems like $path defined by $this->locator->locate($file) on line 42 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...
64
65
        // empty file
66
        if (null === $parsedConfig) {
67
            return $collection;
68
        }
69
70
        // not an array
71
        if (!is_array($parsedConfig)) {
72
            throw new \InvalidArgumentException(sprintf('The file "%s" must contain a YAML array.', $path));
73
        }
74
75
        foreach ($parsedConfig as $name => $config) {
76
77
            $this->validate($config, $name, $path);
78
79
            if (isset($config['resource'])) {
80
                $this->parseImport($collection, $config, $path, $file);
81
            } else {
82
                $this->parseRoute($collection, $name, $config);
83
            }
84
        }
85
86
        return $collection;
87
    }
88
89
    protected function parseImport(MethodCollection $collection, array $config, $path, $file)
90
    {
91
        $defaults = [];
92
93
        if (isset($config['defaults'])) {
94
            $defaults = $config['defaults'];
95
        }
96
        $type = null;
97
98
        if (isset($config['type'])) {
99
            $type = $config['type'];
100
        }
101
        $this->setCurrentDir(dirname($path));
102
        $subCollection = $this->import($config['resource'], $type, false, $file);
103
        $subCollection->addDefaults($defaults);
104
105
        $collection->addCollection($subCollection);
106
    }
107
108
    protected function parseRoute(MethodCollection $collection, $name, array $config)
109
    {
110
        $defaults = [];
111
112
        if (isset($config['defaults'])) {
113
            $defaults = $config['defaults'];
114
        }
115
        $route = new Method(null, $config['method'], $defaults);
116
117
        if ($controller = $route->getDefault('_controller')) {
118
            try {
119
                $controller = $this->controllerParser->parse($controller);
120
            } catch (\Exception $e) {
121
                // unable to optimize unknown notation
122
            }
123
124
            $route->setDefault('_controller', $controller);
125
        }
126
127
        $collection->add($name, $route);
128
    }
129
130
    protected function validate($config, $name, $path)
131
    {
132
        if (!is_array($config)) {
133
            throw new \InvalidArgumentException(sprintf('The definition of "%s" in "%s" must be a YAML array.', $name, $path));
134
        }
135
136
        if ($extraKeys = array_diff(array_keys($config), self::$availableKeys)) {
137
            throw new \InvalidArgumentException(sprintf(
138
                'The routing file "%s" contains unsupported keys for "%s": "%s". Expected one of: "%s".',
139
                $path, $name, implode('", "', $extraKeys), implode('", "', self::$availableKeys)
140
            ));
141
        }
142
143 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...
144
            throw new \InvalidArgumentException(sprintf(
145
                '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.',
146
                $path, $name
147
            ));
148
        }
149
150 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...
151
            throw new \InvalidArgumentException(sprintf(
152
                'The "type" key for the route definition "%s" in "%s" is unsupported. It is only available for imports in combination with the "resource" key.',
153
                $name, $path
154
            ));
155
        }
156
    }
157
158
    /**
159
     * {@inheritdoc}
160
     */
161
    public function supports($resource, $type = null)
162
    {
163
        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...
164
    }
165
}