Completed
Push — master ( f8a04a...bca97c )
by Daniel
03:18
created

YamlRpcLoader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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