Completed
Push — master ( 0558ba...f9a35e )
by Guilh
07:04
created

RestYamlCollectionLoader   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 160
Duplicated Lines 6.25 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 91.25%

Importance

Changes 3
Bugs 1 Features 2
Metric Value
wmc 32
c 3
b 1
f 2
lcom 1
cbo 7
dl 10
loc 160
ccs 73
cts 80
cp 0.9125
rs 9.6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 1
F load() 10 90 24
A supports() 0 6 3
A addParentNamePrefix() 0 15 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
/*
4
 * This file is part of the FOSRestBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\RestBundle\Routing\Loader;
13
14
use FOS\RestBundle\Routing\RestRouteCollection;
15
use Symfony\Component\Config\FileLocatorInterface;
16
use Symfony\Component\Config\Resource\FileResource;
17
use Symfony\Component\Routing\Loader\YamlFileLoader;
18
use Symfony\Component\Routing\RouteCollection;
19
use Symfony\Component\Yaml\Yaml;
20
21
/**
22
 * RestYamlCollectionLoader YAML file collections loader.
23
 */
24
class RestYamlCollectionLoader extends YamlFileLoader
25
{
26
    protected $collectionParents = [];
27
    private $processor;
28
    private $includeFormat;
29
    private $formats;
30
    private $defaultFormat;
31
32
    /**
33
     * Initializes yaml loader.
34
     *
35
     * @param FileLocatorInterface $locator
36
     * @param RestRouteProcessor   $processor
37
     * @param bool                 $includeFormat
38
     * @param string[]             $formats
39
     * @param string               $defaultFormat
40
     */
41 24
    public function __construct(
42
        FileLocatorInterface $locator,
43
        RestRouteProcessor $processor,
44
        $includeFormat = true,
45
        array $formats = [],
46
        $defaultFormat = null
47
    ) {
48 24
        parent::__construct($locator);
49
50 24
        $this->processor = $processor;
51 24
        $this->includeFormat = $includeFormat;
52 24
        $this->formats = $formats;
53 24
        $this->defaultFormat = $defaultFormat;
54 24
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59 12
    public function load($file, $type = null)
60
    {
61 12
        $path = $this->locator->locate($file);
62
63 12
        $config = Yaml::parse(file_get_contents($path));
64
65 12
        $collection = new RouteCollection();
66 12
        $collection->addResource(new FileResource($path));
0 ignored issues
show
Bug introduced by
It seems like $path defined by $this->locator->locate($file) on line 61 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...
67
68
        // process routes and imports
69 12
        foreach ($config as $name => $config) {
70 12
            if (isset($config['resource'])) {
71 7
                $resource = $config['resource'];
72 7
                $prefix = isset($config['prefix']) ? $config['prefix'] : null;
73 7
                $namePrefix = isset($config['name_prefix']) ? $config['name_prefix'] : null;
74 7
                $parent = isset($config['parent']) ? $config['parent'] : null;
75 7
                $type = isset($config['type']) ? $config['type'] : null;
76 7
                $host = isset($config['host']) ? $config['host'] : null;
77 7
                $requirements = isset($config['requirements']) ? $config['requirements'] : [];
78 7
                $defaults = isset($config['defaults']) ? $config['defaults'] : [];
79 7
                $options = isset($config['options']) ? $config['options'] : [];
80 7
                $currentDir = dirname($path);
81
82 7
                $parents = [];
83 7 View Code Duplication
                if (!empty($parent)) {
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...
84 3
                    if (!isset($this->collectionParents[$parent])) {
85
                        throw new \InvalidArgumentException(sprintf('Cannot find parent resource with name %s', $parent));
86
                    }
87
88 3
                    $parents = $this->collectionParents[$parent];
89 3
                }
90
91 7
                $imported = $this->processor->importResource($this, $resource, $parents, $prefix, $namePrefix, $type, $currentDir);
92
93 7
                if ($imported instanceof RestRouteCollection) {
94 7
                    $parents[] = ($prefix ? $prefix.'/' : '').$imported->getSingularName();
95 7
                    $prefix = null;
96 7
                    $namePrefix = null;
97
98 7
                    $this->collectionParents[$name] = $parents;
99 7
                }
100
101 7
                $imported->addRequirements($requirements);
102 7
                $imported->addDefaults($defaults);
103 7
                $imported->addOptions($options);
104
105 7
                if (!empty($host)) {
106
                    $imported->setHost($host);
107
                }
108
109 7
                $imported->addPrefix($prefix);
110
111
                // Add name prefix from parent config files
112 7
                $imported = $this->addParentNamePrefix($imported, $namePrefix);
113
114 7
                $collection->addCollection($imported);
115 12
            } elseif (isset($config['pattern']) || isset($config['path'])) {
116
                // the YamlFileLoader of the Routing component only checks for
117
                // the path option
118 5
                if (!isset($config['path'])) {
119
                    $config['path'] = $config['pattern'];
120
121
                    @trigger_error(sprintf('The "pattern" option at "%s" in file "%s" is deprecated. Use the "path" option instead.', $name, $path), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
122
                }
123
124 5
                if ($this->includeFormat) {
125
                    // append format placeholder if not present
126 4
                    if (false === strpos($config['path'], '{_format}')) {
127 4
                        $config['path'] .= '.{_format}';
128 4
                    }
129
130
                    // set format requirement if configured globally
131 4 View Code Duplication
                    if (!isset($config['requirements']['_format']) && !empty($this->formats)) {
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...
132 4
                        $config['requirements']['_format'] = implode('|', array_keys($this->formats));
133 4
                    }
134 4
                }
135
136
                // set the default format if configured
137 5
                if (null !== $this->defaultFormat) {
138 1
                    $config['defaults']['_format'] = $this->defaultFormat;
139 1
                }
140
141 5
                $this->parseRoute($collection, $name, $config, $path);
0 ignored issues
show
Bug introduced by
It seems like $path defined by $this->locator->locate($file) on line 61 can also be of type array; however, Symfony\Component\Routin...ileLoader::parseRoute() 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...
142 5
            } else {
143
                throw new \InvalidArgumentException(sprintf('Unable to parse the "%s" route.', $name));
144
            }
145 12
        }
146
147 12
        return $collection;
148
    }
149
150
    /**
151
     * {@inheritdoc}
152
     */
153 7
    public function supports($resource, $type = null)
154
    {
155 7
        return is_string($resource) &&
156 7
            'yml' === pathinfo($resource, PATHINFO_EXTENSION) &&
157 7
            'rest' === $type;
158
    }
159
160
    /**
161
     * Adds a name prefix to the route name of all collection routes.
162
     *
163
     * @param RouteCollection $collection Route collection
164
     * @param array           $namePrefix NamePrefix to add in each route name of the route collection
165
     *
166
     * @return RouteCollection
167
     */
168 7
    public function addParentNamePrefix(RouteCollection $collection, $namePrefix)
169
    {
170 7
        if (!isset($namePrefix) || ($namePrefix = trim($namePrefix)) === '') {
171 7
            return $collection;
172
        }
173
174 1
        $iterator = $collection->getIterator();
175
176 1
        foreach ($iterator as $key1 => $route1) {
177 1
            $collection->add($namePrefix.$key1, $route1);
178 1
            $collection->remove($key1);
179 1
        }
180
181 1
        return $collection;
182
    }
183
}
184