Skip to content

Commit

Permalink
restored the cache, only if no additional arguments are passed
Browse files Browse the repository at this point in the history
  • Loading branch information
mirko-pagliai committed Aug 15, 2016
1 parent 4685551 commit 1f9eef0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/Network/Request.php
Expand Up @@ -134,6 +134,13 @@ class Request implements ArrayAccess
'json' => ['accept' => ['application/json'], 'param' => '_ext', 'value' => 'json'],
'xml' => ['accept' => ['application/xml', 'text/xml'], 'param' => '_ext', 'value' => 'xml'],
];

/**
* Instance cache for results of is(something) calls
*
* @var array
*/
protected $_detectorCache = [];

/**
* Copy of php://input. Since this stream can only be read once in most SAPI's
Expand Down Expand Up @@ -640,9 +647,27 @@ public function is($type)
if (!isset(static::$_detectors[$type])) {
return false;
}

if (empty($args)) {
if (!isset($this->_detectorCache[$type])) {
$this->_detectorCache[$type] = $this->_is($type);
}

return $this->_detectorCache[$type];
}

return $this->_is($type, $args);
}

/**
* Clears the instance detector cache, used by the is() function
*
* @return void
*/
public function clearDetectorCache()
{
$this->_detectorCache = [];
}

/**
* Worker for the public is() function
Expand Down Expand Up @@ -1272,6 +1297,7 @@ public function env($key, $value = null, $default = null)
{
if ($value !== null) {
$this->_environment[$key] = $value;
$this->clearDetectorCache();

return $this;
}
Expand Down
5 changes: 5 additions & 0 deletions tests/TestCase/Network/RequestTest.php
Expand Up @@ -1014,20 +1014,25 @@ public function testAddDetector()
Request::addDetector('index', ['param' => 'action', 'value' => 'index']);

$request->params['action'] = 'index';
$request->clearDetectorCache();
$this->assertTrue($request->isIndex());

$request->params['action'] = 'add';
$request->clearDetectorCache();
$this->assertFalse($request->isIndex());

Request::addDetector('callme', [$this, 'detectCallback']);
$request->return = true;
$request->clearDetectorCache();
$this->assertTrue($request->isCallMe());

Request::addDetector('extension', ['param' => '_ext', 'options' => ['pdf', 'png', 'txt']]);
$request->params['_ext'] = 'pdf';
$request->clearDetectorCache();
$this->assertTrue($request->is('extension'));

$request->params['_ext'] = 'exe';
$request->clearDetectorCache();
$this->assertFalse($request->isExtension());
}

Expand Down

0 comments on commit 1f9eef0

Please sign in to comment.