浏览代码

Improved class support for filter factory

core23 8 年之前
父节点
当前提交
6b3c160ee8
共有 2 个文件被更改,包括 28 次插入4 次删除
  1. 6 4
      Filter/FilterFactory.php
  2. 22 0
      Tests/Filter/FilterFactoryTest.php

+ 6 - 4
Filter/FilterFactory.php

@@ -51,14 +51,16 @@ class FilterFactory implements FilterFactoryInterface
 
         $id = isset($this->types[$type]) ? $this->types[$type] : false;
 
-        if (!$id) {
+        if ($id) {
+            $filter = $this->container->get($id);
+        } elseif (class_exists($type)) {
+            $filter = new $type();
+        } else {
             throw new \RuntimeException(sprintf('No attached service to type named `%s`', $type));
         }
 
-        $filter = $this->container->get($id);
-
         if (!$filter instanceof FilterInterface) {
-            throw new \RuntimeException(sprintf('The service `%s` must implement `FilterInterface`', $id));
+            throw new \RuntimeException(sprintf('The service `%s` must implement `FilterInterface`', $type));
         }
 
         $filter->initialize($name, $options);

+ 22 - 0
Tests/Filter/FilterFactoryTest.php

@@ -37,6 +37,28 @@ class FilterFactoryTest extends \PHPUnit_Framework_TestCase
         $filter->create('test', 'mytype');
     }
 
+    /**
+     * @expectedException RuntimeException
+     */
+    public function testUnknownClassType()
+    {
+        $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
+
+        $filter = new FilterFactory($container, array());
+        $filter->create('test', 'Sonata\AdminBundle\Form\Type\Filter\FooType');
+    }
+
+    /**
+     * @expectedException RuntimeException
+     */
+    public function testClassType()
+    {
+        $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
+
+        $filter = new FilterFactory($container, array());
+        $filter->create('test', 'Sonata\AdminBundle\Form\Type\Filter\DefaultType');
+    }
+
     /**
      * @expectedException RuntimeException
      */