From 00d9f8dea746191959b98b66de5ff8c6f2701739 Mon Sep 17 00:00:00 2001 From: Brooke Bryan Date: Fri, 7 Jan 2022 15:49:48 +0000 Subject: [PATCH] Support withSubdomain on insecure upgrade routes --- src/Routes/InsecureRequestUpgradeRoute.php | 30 +++++++++++++++++-- .../InsecureRequestUpgradeRouteTest.php | 22 ++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/src/Routes/InsecureRequestUpgradeRoute.php b/src/Routes/InsecureRequestUpgradeRoute.php index fd09e87..465cedd 100644 --- a/src/Routes/InsecureRequestUpgradeRoute.php +++ b/src/Routes/InsecureRequestUpgradeRoute.php @@ -9,18 +9,42 @@ class InsecureRequestUpgradeRoute extends Route { + protected $_subDomain; + public function __construct() { $this->add(FuncCondition::i(function (Context $c) { return !$c->request()->isSecure(true); })); } + /** + * @param string $subDomain + * + * @return InsecureRequestUpgradeRoute + */ + public static function withSubdomain(string $subDomain = 'www'): InsecureRequestUpgradeRoute + { + $i = new static(); + $i->_subDomain = trim($subDomain, '.'); + return $i; + } + public function getHandler() { return new FuncHandler( function (Context $c) { - return RedirectResponse::create( - str_replace('http:', 'https:', $c->request()->getUri()) - ); + + if($this->_subDomain) + { + $r = $c->request(); + if(null !== $qs = $r->getQueryString()) + { + $qs = '?' . $qs; + } + $uri = $r->getBaseUrl() . $r->getPathInfo() . $qs; + return RedirectResponse::create("https://" . $this->_subDomain . $r->urlSprintf(".%d.%t%o") . $uri); + } + + return RedirectResponse::create(str_replace('http:', 'https:', $c->request()->getUri())); } ); } diff --git a/tests/Routes/InsecureRequestUpgradeRouteTest.php b/tests/Routes/InsecureRequestUpgradeRouteTest.php index 0f7d992..580ffbc 100644 --- a/tests/Routes/InsecureRequestUpgradeRouteTest.php +++ b/tests/Routes/InsecureRequestUpgradeRouteTest.php @@ -27,4 +27,26 @@ public function testHttpsIgnore() $route = InsecureRequestUpgradeRoute::i(); $this->assertFalse($route->match($ctx)); } + + public function testHttpUpgradeWithSubDomainDefault() + { + $ctx = new Context(Request::create('http://google.com/a/b/c/?d=e&f=g')); + $route = InsecureRequestUpgradeRoute::withSubdomain(); + $this->assertTrue($route->match($ctx)); + /** @var RedirectResponse|null $resp */ + $resp = $route->getHandler()->handle($ctx); + $this->assertInstanceOf(RedirectResponse::class, $resp); + $this->assertEquals('https://www.google.com/a/b/c/?d=e&f=g', $resp->getTargetUrl()); + } + + public function testHttpUpgradeWithSubDomain() + { + $ctx = new Context(Request::create('http://google.com/a/b/c/?d=e&f=g')); + $route = InsecureRequestUpgradeRoute::withSubdomain('secure'); + $this->assertTrue($route->match($ctx)); + /** @var RedirectResponse|null $resp */ + $resp = $route->getHandler()->handle($ctx); + $this->assertInstanceOf(RedirectResponse::class, $resp); + $this->assertEquals('https://secure.google.com/a/b/c/?d=e&f=g', $resp->getTargetUrl()); + } }