Completed
Pull Request — 2.x (#2251)
by Christian
03:46 queued 12s
created

RestYamlCollectionLoader::addParentNamePrefix()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 8
cts 8
cp 1
rs 9.7666
c 0
b 0
f 0
cc 4
nc 3
nop 2
crap 4
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 1
@trigger_error(sprintf('The %s\RestYamlCollectionLoader class is deprecated since FOSRestBundle 2.8.', __NAMESPACE__), 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...
15
16
use FOS\RestBundle\Routing\RestRouteCollection;
17
use Symfony\Component\Config\FileLocatorInterface;
18
use Symfony\Component\Config\Resource\FileResource;
19
use Symfony\Component\Routing\Loader\YamlFileLoader;
20
use Symfony\Component\Routing\RouteCollection;
21
use Symfony\Component\Yaml\Exception\ParseException;
22
use Symfony\Component\Yaml\Yaml;
23
24
/**
25
 * RestYamlCollectionLoader YAML file collections loader.
26
 *
27
 * @deprecated since 2.8
28
 */
29
class RestYamlCollectionLoader extends YamlFileLoader
30
{
31
    protected $collectionParents = [];
32
    private $processor;
33
    private $includeFormat;
34
    private $formats;
35
    private $defaultFormat;
36
37
    /**
38
     * @param string[] $formats
39
     */
40 21 View Code Duplication
    public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
41
        FileLocatorInterface $locator,
42
        RestRouteProcessor $processor,
43
        bool $includeFormat = true,
44
        array $formats = [],
45
        string $defaultFormat = null
46
    ) {
47 21
        parent::__construct($locator);
48
49 21
        $this->processor = $processor;
50 21
        $this->includeFormat = $includeFormat;
51 21
        $this->formats = $formats;
52 21
        $this->defaultFormat = $defaultFormat;
53 21
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58 17
    public function load($file, $type = null)
59
    {
60 17
        $path = $this->locator->locate($file);
61
62
        try {
63 17
            $config = Yaml::parse(file_get_contents($path));
64 1
        } catch (ParseException $e) {
65 1
            throw new \InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML.', $path), 0, $e);
66
        }
67
68 16
        $collection = new RouteCollection();
69 16
        $collection->addResource(new FileResource($path));
0 ignored issues
show
Bug introduced by
It seems like $path defined by $this->locator->locate($file) on line 60 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...
70
71
        // empty file
72 16
        if (null === $config) {
73 1
            return $collection;
74
        }
75
76
        // not an array
77 15
        if (!is_array($config)) {
78 1
            throw new \InvalidArgumentException(sprintf('The file "%s" must contain a Yaml mapping (an array).', $path));
79
        }
80
81
        // process routes and imports
82 14
        foreach ($config as $name => $config) {
83 14
            if (isset($config['resource'])) {
84 8
                $resource = $config['resource'];
85 8
                $prefix = isset($config['prefix']) ? $config['prefix'] : null;
86 8
                $namePrefix = isset($config['name_prefix']) ? $config['name_prefix'] : null;
87 8
                $parent = isset($config['parent']) ? $config['parent'] : null;
88 8
                $type = isset($config['type']) ? $config['type'] : null;
89 8
                $host = isset($config['host']) ? $config['host'] : null;
90 8
                $requirements = isset($config['requirements']) ? $config['requirements'] : [];
91 8
                $defaults = isset($config['defaults']) ? $config['defaults'] : [];
92 8
                $options = isset($config['options']) ? $config['options'] : [];
93 8
                $currentDir = dirname($path);
94
95 8
                $parents = [];
96 8 View Code Duplication
                if (!empty($parent)) {
97 1
                    if (!isset($this->collectionParents[$parent])) {
98 1
                        throw new \InvalidArgumentException(sprintf('Cannot find parent resource with name %s', $parent));
99
                    }
100
101
                    $parents = $this->collectionParents[$parent];
102
                }
103
104 7
                $imported = $this->processor->importResource($this, $resource, $parents, $prefix, $namePrefix, $type, $currentDir);
105
106 3
                if ($imported instanceof RestRouteCollection) {
107 3
                    $parents[] = ($prefix ? $prefix.'/' : '').$imported->getSingularName();
108 3
                    $prefix = null;
109 3
                    $namePrefix = null;
110
111 3
                    $this->collectionParents[$name] = $parents;
112
                }
113
114 3
                $imported->addRequirements($requirements);
115 3
                $imported->addDefaults($defaults);
116 3
                $imported->addOptions($options);
117
118 3
                if (!empty($host)) {
119
                    $imported->setHost($host);
120
                }
121
122 3
                $imported->addPrefix((string) $prefix);
123
124
                // Add name prefix from parent config files
125 3
                $imported = $this->addParentNamePrefix($imported, $namePrefix);
126
127 3
                $collection->addCollection($imported);
0 ignored issues
show
Documentation introduced by
$imported is of type object<Symfony\Component\Routing\RouteCollection>, but the function expects a object<self>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
128 6
            } elseif (isset($config['pattern']) || isset($config['path'])) {
129
                // the YamlFileLoader of the Routing component only checks for
130
                // the path option
131 6
                if (!isset($config['path'])) {
132 1
                    $config['path'] = $config['pattern'];
133
134 1
                    @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...
135
                }
136
137 6
                if ($this->includeFormat) {
138
                    // append format placeholder if not present
139 5
                    if (false === strpos($config['path'], '{_format}')) {
140 5
                        $config['path'] .= '.{_format}';
141
                    }
142
143
                    // set format requirement if configured globally
144 5
                    if (!isset($config['requirements']['_format']) && !empty($this->formats)) {
145 5
                        $config['requirements']['_format'] = implode('|', array_keys($this->formats));
146
                    }
147
                }
148
149
                // set the default format if configured
150 6
                if (null !== $this->defaultFormat) {
151 1
                    $config['defaults']['_format'] = $this->defaultFormat;
152
                }
153
154 6
                $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 60 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...
155
            } else {
156
                throw new \InvalidArgumentException(sprintf('Unable to parse the "%s" route.', $name));
157
            }
158
        }
159
160 9
        return $collection;
161
    }
162
163
    /**
164
     * {@inheritdoc}
165
     */
166 10
    public function supports($resource, $type = null)
167
    {
168 10
        return 'rest' === $type && is_string($resource) &&
169 10
            in_array(pathinfo($resource, PATHINFO_EXTENSION), array('yaml', 'yml'), true);
170
    }
171
172
    /**
173
     * @param string $namePrefix
174
     *
175
     * @return RouteCollection
176
     */
177 3
    public function addParentNamePrefix(RouteCollection $collection, $namePrefix)
178
    {
179 3
        if (!isset($namePrefix) || '' === ($namePrefix = trim($namePrefix))) {
180 3
            return $collection;
181
        }
182
183 1
        $iterator = $collection->getIterator();
184
185 1
        foreach ($iterator as $key1 => $route1) {
186 1
            $collection->add($namePrefix.$key1, $route1);
187 1
            $collection->remove($key1);
188
        }
189
190 1
        return $collection;
191
    }
192
}
193