Skip to content

Commit

Permalink
RequestFactory: optimized script path detection performance, thx @Jan…
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Dec 27, 2014
1 parent 06cc6f4 commit 4c002b4
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 10 deletions.
17 changes: 7 additions & 10 deletions src/Http/RequestFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,24 +81,21 @@ public function createHttpRequest()
}

// path & query
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
$requestUrl = Strings::replace($requestUrl, $this->urlFilters['url']);
$tmp = explode('?', $requestUrl, 2);
$path = Strings::fixEncoding(Strings::replace($tmp[0], $this->urlFilters['path']));
$url->setPath($path);
$url->setQuery(isset($tmp[1]) ? $tmp[1] : '');

// detect script path
$path .= '/';
$script = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] . '/' : '/';
$max = min(strlen($path), strlen($script));
for ($i = 0; $i < $max; $i++) {
if ($path[$i] !== $script[$i]) {
break;
} elseif ($path[$i] === '/') {
$url->setScriptPath(substr($url->getPath(), 0, $i + 1));
}
$script = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : '';
if ($path !== $script) {
$max = min(strlen($path), strlen($script));
for ($i = 0; $i < $max && $path[$i] === $script[$i]; $i++);
$path = $i ? substr($path, 0, strrpos($path, '/', $i - $max - 1) + 1) : '/';
}
$url->setScriptPath($path);

// GET, POST, COOKIE
$useFilter = (!in_array(ini_get('filter.default'), array('', 'unsafe_raw')) || ini_get('filter.default_flags'));
Expand Down
40 changes: 40 additions & 0 deletions tests/Http/RequestFactory.scriptPath.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,43 @@ test(function() use ($factory) {

Assert::same( '/blog/', $factory->createHttpRequest()->getUrl()->getScriptPath() );
});


test(function() use ($factory) {
$_SERVER = array(
'REQUEST_URI' => '/',
'SCRIPT_NAME' => 'c:\\index.php',
);

Assert::same( '/', $factory->createHttpRequest()->getUrl()->getScriptPath() );
});


test(function() use ($factory) {
$_SERVER = array(
'REQUEST_URI' => NULL,
'SCRIPT_NAME' => 'c:\\index.php',
);

Assert::same( '/', $factory->createHttpRequest()->getUrl()->getScriptPath() );
});


test(function() use ($factory) {
$_SERVER = array(
'REQUEST_URI' => '/',
'SCRIPT_NAME' => NULL,
);

Assert::same( '/', $factory->createHttpRequest()->getUrl()->getScriptPath() );
});


test(function() use ($factory) {
$_SERVER = array(
'REQUEST_URI' => NULL,
'SCRIPT_NAME' => NULL,
);

Assert::same( '/', $factory->createHttpRequest()->getUrl()->getScriptPath() );
});

0 comments on commit 4c002b4

Please sign in to comment.