Browse Source

Allow using UriInterface instances with Router::url().

ADmad 6 years ago
parent
commit
aee3340395

+ 2 - 3
src/Controller/Controller.php

@@ -707,9 +707,8 @@ class Controller implements EventListenerInterface, EventDispatcherInterface
     /**
      * Redirects to given $url, after turning off $this->autoRender.
      *
-     * @param string|array $url A string or array-based URL pointing to another location within the app,
-     *     or an absolute URL
-     * @param int $status HTTP status code (eg: 301)
+     * @param string|array|\Psr\Http\Message\UriInterface $url A string, array-based URL or UriInterface instance.
+     * @param int $status HTTP status code. Defaults to `302`.
      * @return \Cake\Http\Response|null
      * @link https://book.cakephp.org/3.0/en/controllers.html#Controller::redirect
      */

+ 4 - 2
src/Routing/Router.php

@@ -646,10 +646,10 @@ class Router
      * - `_name` - Name of route. If you have setup named routes you can use this key
      *   to specify it.
      *
-     * @param string|array|null $url An array specifying any of the following:
+     * @param string|array|\Psr\Http\Message\UriInterface|null $url An array specifying any of the following:
      *   'controller', 'action', 'plugin' additionally, you can provide routed
      *   elements or query string parameters. If string it can be name any valid url
-     *   string.
+     *   string or it can be an UriInterface instance.
      * @param bool $full If true, the full base URL will be prepended to the result.
      *   Default is false.
      * @return string Full translated URL with base path.
@@ -733,6 +733,8 @@ class Router
 
             $output = static::$_collection->match($url, $context);
         } else {
+            $url = (string)$url;
+
             $plainString = (
                 strpos($url, 'javascript:') === 0 ||
                 strpos($url, 'mailto:') === 0 ||

+ 14 - 0
tests/TestCase/Controller/ControllerTest.php

@@ -26,6 +26,7 @@ use Cake\TestSuite\TestCase;
 use PHPUnit\Framework\Error\Notice;
 use TestApp\Controller\Admin\PostsController;
 use TestPlugin\Controller\TestPluginController;
+use Zend\Diactoros\Uri;
 
 /**
  * AppController class
@@ -493,6 +494,19 @@ class ControllerTest extends TestCase
         $this->assertInstanceOf('Cake\Http\Response', $result);
     }
 
+    public function testControllerRedirect()
+    {
+        $Controller = new Controller();
+        $uri = new Uri('/foo/bar');
+        $response = $Controller->redirect($uri);
+        $this->assertEquals('http://localhost/foo/bar', $response->getHeaderLine('Location'));
+
+        $Controller = new Controller();
+        $uri = new Uri('http://cakephp.org/foo/bar');
+        $response = $Controller->redirect($uri);
+        $this->assertEquals('http://cakephp.org/foo/bar', $response->getHeaderLine('Location'));
+    }
+
     /**
      * Generates status codes for redirect test.
      *