Skip to content

Commit 00d9f8d

Browse files
committed
Support withSubdomain on insecure upgrade routes
1 parent 507073d commit 00d9f8d

File tree

2 files changed

+49
-3
lines changed

2 files changed

+49
-3
lines changed

src/Routes/InsecureRequestUpgradeRoute.php

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,42 @@
99

1010
class InsecureRequestUpgradeRoute extends Route
1111
{
12+
protected $_subDomain;
13+
1214
public function __construct()
1315
{
1416
$this->add(FuncCondition::i(function (Context $c) { return !$c->request()->isSecure(true); }));
1517
}
1618

19+
/**
20+
* @param string $subDomain
21+
*
22+
* @return InsecureRequestUpgradeRoute
23+
*/
24+
public static function withSubdomain(string $subDomain = 'www'): InsecureRequestUpgradeRoute
25+
{
26+
$i = new static();
27+
$i->_subDomain = trim($subDomain, '.');
28+
return $i;
29+
}
30+
1731
public function getHandler()
1832
{
1933
return new FuncHandler(
2034
function (Context $c) {
21-
return RedirectResponse::create(
22-
str_replace('http:', 'https:', $c->request()->getUri())
23-
);
35+
36+
if($this->_subDomain)
37+
{
38+
$r = $c->request();
39+
if(null !== $qs = $r->getQueryString())
40+
{
41+
$qs = '?' . $qs;
42+
}
43+
$uri = $r->getBaseUrl() . $r->getPathInfo() . $qs;
44+
return RedirectResponse::create("https://" . $this->_subDomain . $r->urlSprintf(".%d.%t%o") . $uri);
45+
}
46+
47+
return RedirectResponse::create(str_replace('http:', 'https:', $c->request()->getUri()));
2448
}
2549
);
2650
}

tests/Routes/InsecureRequestUpgradeRouteTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,26 @@ public function testHttpsIgnore()
2727
$route = InsecureRequestUpgradeRoute::i();
2828
$this->assertFalse($route->match($ctx));
2929
}
30+
31+
public function testHttpUpgradeWithSubDomainDefault()
32+
{
33+
$ctx = new Context(Request::create('http://google.com/a/b/c/?d=e&f=g'));
34+
$route = InsecureRequestUpgradeRoute::withSubdomain();
35+
$this->assertTrue($route->match($ctx));
36+
/** @var RedirectResponse|null $resp */
37+
$resp = $route->getHandler()->handle($ctx);
38+
$this->assertInstanceOf(RedirectResponse::class, $resp);
39+
$this->assertEquals('https://www.google.com/a/b/c/?d=e&f=g', $resp->getTargetUrl());
40+
}
41+
42+
public function testHttpUpgradeWithSubDomain()
43+
{
44+
$ctx = new Context(Request::create('http://google.com/a/b/c/?d=e&f=g'));
45+
$route = InsecureRequestUpgradeRoute::withSubdomain('secure');
46+
$this->assertTrue($route->match($ctx));
47+
/** @var RedirectResponse|null $resp */
48+
$resp = $route->getHandler()->handle($ctx);
49+
$this->assertInstanceOf(RedirectResponse::class, $resp);
50+
$this->assertEquals('https://secure.google.com/a/b/c/?d=e&f=g', $resp->getTargetUrl());
51+
}
3052
}

0 commit comments

Comments
 (0)