Skip to content

Commit

Permalink
Update to Redirector class and DataListDataSource class to change red…
Browse files Browse the repository at this point in the history
…irect cache to be an associative array to improve performance.

In order to improve performance for redirect lookup, instead of a standard array being generated an associative array (keyed on the 'from' URL) is generated which allows a direct check rather than needing to iterate through all values which can be inefficient, especially when there is a large number (and also considering this would be done on each page request).
  • Loading branch information
timhiggs committed Mar 13, 2016
1 parent cdebf97 commit 62aff52
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
15 changes: 14 additions & 1 deletion src/DataSource/DataListDataSource.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Heyday\Redirects\DataSource;

use Heyday\Redirects\CacheableDataSourceInterface;
use Heyday\Redirects\Redirect;
use Heyday\Redirects\TransformerInterface;

class DataListDataSource implements CacheableDataSourceInterface
Expand All @@ -24,11 +25,23 @@ public function __construct(\DataList $list, TransformerInterface $transformer)
}

/**
* In order to improve performance for a larger number of redirects, instead of a standard array being generated
* an associative array (keyed on the 'from' URL) is generated which allows a direct check rather than needing
* to iterate through a large list (especially considering this would be done on each page request).
*
* @return \Heyday\Redirects\Redirect[]
*/
public function get()
{
return array_map([$this->transformer, 'transform'], $this->list->toArray());
$data = array();

/* @var \Heyday\Redirects\Redirect $redirect */
foreach (array_map([$this->transformer, 'transform'], $this->list->toArray()) as $redirect) {
// Format the URL so it will match the SS_HTTPRequest request URL
$data[Redirect::formatUrl($redirect->getFrom())] = $redirect;
}

return $data;
}

/**
Expand Down
9 changes: 6 additions & 3 deletions src/Redirector.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,17 @@ public function __construct(DataSourceInterface $dataSource)
*/
public function getRedirectForRequest(\SS_HTTPRequest $request)
{
$url = $request->getURL();
// Format the URL as the key will have been formatted
$url = Redirect::formatUrl($request->getURL());
$dataSource = $this->dataSource->get();

foreach ($this->dataSource->get() as $redirect) {
// Check if there's a key for the URL
if (isset($dataSource[$url])) {
$redirect = $dataSource[$url];
if ($redirect->match($url)) {
return $redirect;
}
}

return false;
}

Expand Down

0 comments on commit 62aff52

Please sign in to comment.