Prechádzať zdrojové kódy

[Routing] throw an exception if route config has unsupported keys

everzet 14 rokov pred
rodič
commit
3fd50ea4e6

+ 29 - 0
src/Symfony/Component/Routing/Loader/YamlFileLoader.php

@@ -24,6 +24,10 @@ use Symfony\Component\Config\Loader\FileLoader;
  */
 class YamlFileLoader extends FileLoader
 {
+    private static $availableKeys = array(
+        'type', 'resource', 'prefix', 'pattern', 'options', 'defaults', 'requirements'
+    );
+
     /**
      * Loads a Yaml file.
      *
@@ -54,6 +58,8 @@ class YamlFileLoader extends FileLoader
         }
 
         foreach ($config as $name => $config) {
+            $config = $this->normalizeRouteConfig($config);
+
             if (isset($config['resource'])) {
                 $type = isset($config['type']) ? $config['type'] : null;
                 $prefix = isset($config['prefix']) ? $config['prefix'] : null;
@@ -118,4 +124,27 @@ class YamlFileLoader extends FileLoader
     {
         return Yaml::load($file);
     }
+
+    /**
+     * Normalize route configuration.
+     *
+     * @param array  $config A resource config
+     *
+     * @return array
+     *
+     * @throws InvalidArgumentException if one of the provided config keys is not supported
+     */
+    private function normalizeRouteConfig(array $config)
+    {
+        foreach ($config as $key => $value) {
+            if (!in_array($key, self::$availableKeys)) {
+                throw new \InvalidArgumentException(sprintf(
+                    'Unsupported config key given: "%s". Expected one of the (%s).',
+                    $key, implode(', ', self::$availableKeys)
+                ));
+            }
+        }
+
+        return $config;
+    }
 }

+ 3 - 0
tests/Symfony/Tests/Component/Routing/Fixtures/nonvalidkeys.yml

@@ -0,0 +1,3 @@
+someroute:
+  resource: path/to/some.yml
+  name_prefix: test_

+ 9 - 0
tests/Symfony/Tests/Component/Routing/Loader/YamlFileLoaderTest.php

@@ -51,4 +51,13 @@ class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase
         $loader = new YamlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
         $loader->load('nonvalid.yml');
     }
+
+    /**
+     * @expectedException \InvalidArgumentException
+     */
+    public function testLoadThrowsExceptionIfArrayHasUnsupportedKeys()
+    {
+        $loader = new YamlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
+        $loader->load('nonvalidkeys.yml');
+    }
 }