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