Skip to content

Commit

Permalink
Detect domains correctly in Director sub-calls
Browse files Browse the repository at this point in the history
Previously it relied on the PHP-level $_SERVER variable; now it will use
the HTTPRequest so it works correctly in more situations.
  • Loading branch information
nicole-ashley committed Jun 12, 2019
1 parent ee96159 commit 46a8635
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Middleware/InitStateMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ protected function detectSubsiteId(HTTPRequest $request)
return (int) $request->getSession()->get('SubsiteID');
}

$subsiteIdFromDomain = Subsite::getSubsiteIDForDomain();
$subsiteIdFromDomain = Subsite::getSubsiteIDForDomain($request->getHost());
if ($subsiteIdFromDomain !== null) {
return (int) $subsiteIdFromDomain;
}
Expand Down
80 changes: 80 additions & 0 deletions tests/php/InitStateMiddlewareTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

namespace SilverStripe\Subsites\Tests;

use SilverStripe\Control\HTTPRequest;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Subsites\Middleware\InitStateMiddleware;
use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\Subsites\State\SubsiteState;

class InitStateMiddlewareTest extends BaseSubsiteTest
{
protected static $fixture_file = 'SubsiteTest.yml';

/**
* Original value of $_REQUEST
*
* @var array
*/
protected $origServer = [];

protected function setUp()
{
parent::setUp();

$this->origServer = $_SERVER;
}

protected function tearDown()
{
$_SERVER = $this->origServer;

parent::tearDown();
}

public function testDomainDetectionViaServerHeaders()
{
$_SERVER['HTTP_HOST'] = 'one.example.org';

$this->getMiddleware()->process($this->getRequest(), $this->getCallback());

$expectedSubsite = $this->objFromFixture(Subsite::class, 'domaintest1');
$this->assertEquals($expectedSubsite->ID, $this->getState()->getSubsiteId());
}

public function testDomainDetectionViaRequestOverridesServerHeaders()
{
$_SERVER['HTTP_HOST'] = 'one.example.org';

$this->getMiddleware()->process($this->getRequest('two.mysite.com'), $this->getCallback());

$expectedSubsite = $this->objFromFixture(Subsite::class, 'domaintest2');
$this->assertEquals($expectedSubsite->ID, $this->getState()->getSubsiteId());
}

protected function getMiddleware()
{
return new InitStateMiddleware();
}

protected function getRequest($domain = null)
{
$request = new HTTPRequest('GET', '/test/url');
if ($domain) {
$request->addHeader('host', $domain);
}
return $request;
}

protected function getCallback()
{
return function () {
};
}

protected function getState()
{
return Injector::inst()->get(SubsiteState::class);
}
}

0 comments on commit 46a8635

Please sign in to comment.