浏览代码

[BrowserKit] added a way to automatically follow redirects

Fabien Potencier 15 年之前
父节点
当前提交
1194520b83

+ 18 - 1
src/Symfony/Components/BrowserKit/Client.php

@@ -38,6 +38,7 @@ abstract class Client
   protected $crawler;
   protected $insulated;
   protected $redirect;
+  protected $followRedirects;
 
   /**
    * Constructor.
@@ -52,6 +53,17 @@ abstract class Client
     $this->history = null === $history ? new History() : $history;
     $this->cookieJar = null === $cookieJar ? new CookieJar() : $cookieJar;
     $this->insulated = false;
+    $this->followRedirects = true;
+  }
+
+  /**
+   * Sets whether to automatically follow redirects or not.
+   *
+   * @param Boolean $followRedirect Whether to follow redirects
+   */
+  public function followRedirects($followRedirect = true)
+  {
+    $this->followRedirects = (Boolean) $followRedirect;
   }
 
   /**
@@ -206,6 +218,11 @@ abstract class Client
 
     $this->redirect = $response->getHeader('Location');
 
+    if ($this->followRedirects && $this->redirect)
+    {
+      return $this->crawler = $this->followRedirect();
+    }
+
     return $this->crawler = $this->createCrawlerFromContent($request->getUri(), $response->getContent(), $response->getHeader('Content-Type'));
   }
 
@@ -301,7 +318,7 @@ abstract class Client
    */
   public function followRedirect()
   {
-    if (null === $this->redirect)
+    if (empty($this->redirect))
     {
       throw new \LogicException('The request was not redirected.');
     }

+ 2 - 0
src/Symfony/Components/RequestHandler/Test/Client.php

@@ -46,6 +46,8 @@ class Client extends BaseClient
     $this->testers = array();
 
     parent::__construct($server, $history, $cookieJar);
+
+    $this->followRedirects = false;
   }
 
   /**

+ 7 - 0
tests/Symfony/Tests/Components/BrowserKit/ClientTest.php

@@ -223,6 +223,7 @@ RETURN;
   public function testFollowRedirect()
   {
     $client = new TestClient();
+    $client->followRedirects(false);
     $client->request('GET', 'http://www.example.com/foo/foobar');
 
     try
@@ -240,6 +241,12 @@ RETURN;
     $client->followRedirect();
 
     $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows a redirect if any');
+
+    $client = new TestClient();
+    $client->setNextResponse(new Response('', 200, array('Location' => 'http://www.example.com/redirected')));
+    $client->request('GET', 'http://www.example.com/foo/foobar');
+
+    $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() automatically follows redirects if followRedirects is true');
   }
 
   public function testBack()