Browse Source

Merge pull request #11163 from robertpustulka/schemeless-url-fix

Support protocol relative URL in HTTP Client.
Mark Story 8 years ago
parent
commit
2163569d17
2 changed files with 32 additions and 4 deletions
  1. 11 4
      src/Http/Client.php
  2. 21 0
      tests/TestCase/Http/ClientTest.php

+ 11 - 4
src/Http/Client.php

@@ -406,7 +406,8 @@ class Client
                 $locationUrl = $this->buildUrl($location, [], [
                     'host' => $url->getHost(),
                     'port' => $url->getPort(),
-                    'scheme' => $url->getScheme()
+                    'scheme' => $url->getScheme(),
+                    'protocolRelative' => true
                 ]);
 
                 $request = $request->withUri(new Uri($locationUrl));
@@ -452,15 +453,21 @@ class Client
             $url .= $q;
             $url .= is_string($query) ? $query : http_build_query($query);
         }
-        if (preg_match('#^https?://#', $url)) {
-            return $url;
-        }
         $defaults = [
             'host' => null,
             'port' => null,
             'scheme' => 'http',
+            'protocolRelative' => false
         ];
         $options += $defaults;
+
+        if ($options['protocolRelative'] && preg_match('#^//#', $url)) {
+            $url = $options['scheme'] . ':' . $url;
+        }
+        if (preg_match('#^https?://#', $url)) {
+            return $url;
+        }
+
         $defaultPorts = [
             'http' => 80,
             'https' => 443

+ 21 - 0
tests/TestCase/Http/ClientTest.php

@@ -137,6 +137,27 @@ class ClientTest extends TestCase
                 [],
                 'query string data with some already on the url.'
             ],
+            [
+                'http://example.com/test.html',
+                '//test.html',
+                [],
+                [
+                    'scheme' => 'http',
+                    'host' => 'example.com',
+                    'protocolRelative' => false
+                ],
+                'url with a double slash',
+            ],
+            [
+                'http://example.com/test.html',
+                '//example.com/test.html',
+                [],
+                [
+                    'scheme' => 'http',
+                    'protocolRelative' => true
+                ],
+                'protocol relative url',
+            ],
         ];
     }