Skip to content

Commit

Permalink
Adding CakeRequest::referer() and test cases.
Browse files Browse the repository at this point in the history
  • Loading branch information
markstory committed Apr 29, 2010
1 parent 64aafd3 commit aab4a94
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
27 changes: 26 additions & 1 deletion cake/libs/cake_request.php
Expand Up @@ -2,7 +2,7 @@
/**
* A class that helps wrap Request information and particulars about a single request.
*
* PHP versions 4 and 5
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
Expand Down Expand Up @@ -164,4 +164,29 @@ public function getClientIp($safe = true) {
}
return trim($ipaddr);
}

/**
* Returns the referer that referred this request.
*
* @param boolean $local Attempt to return a local address. Local addresses do not contain hostnames.
* @return string The referring address for this request.
*/
public function referer($local = false) {
$ref = env('HTTP_REFERER');
$base = '';
if (defined('FULL_BASE_URL')) {
$base = FULL_BASE_URL;
}
if (!empty($ref)) {
if ($local && strpos($ref, $base) === 0) {
$ref = substr($ref, strlen($base));
if ($ref[0] != '/') {
$ref = '/' . $ref;
}
}
return $ref;
}
return '/';
}

}
35 changes: 34 additions & 1 deletion cake/tests/cases/libs/cake_request.test.php
Expand Up @@ -33,7 +33,7 @@ function endTest() {
* @return void
*/
function testConstructionGetParsing() {
$GET = array(
$_GET = array(
'one' => 'param',
'two' => 'banana'
);
Expand Down Expand Up @@ -360,4 +360,37 @@ function testGetClientIp() {
$_SERVER['HTTP_CLIENTADDRESS'] = '10.0.1.2, 10.0.1.1';
$this->assertEqual($request->getClientIP(), '10.0.1.2');
}

/**
* test the referer function.
*
* @return void
*/
function testReferer() {
$request = new CakeRequest();

$_SERVER['HTTP_REFERER'] = 'http://cakephp.org';
$result = $request->referer();
$this->assertIdentical($result, 'http://cakephp.org');

$_SERVER['HTTP_REFERER'] = '';
$result = $request->referer();
$this->assertIdentical($result, '/');

$_SERVER['HTTP_REFERER'] = FULL_BASE_URL . '/some/path';
$result = $request->referer(true);
$this->assertIdentical($result, '/some/path');

$_SERVER['HTTP_REFERER'] = FULL_BASE_URL . '/some/path';
$result = $request->referer();
$this->assertIdentical($result, FULL_BASE_URL . '/some/path');

$_SERVER['HTTP_REFERER'] = FULL_BASE_URL . 'some/path';
$result = $request->referer(true);
$this->assertIdentical($result, '/some/path');

$_SERVER['HTTP_REFERER'] = FULL_BASE_URL . 'recipes/add';
$result = $request->referer(true);
$this->assertIdentical($result, '/recipes/add');
}
}

0 comments on commit aab4a94

Please sign in to comment.