Browse Source

Add argument support for detectors

Jad Bitar 10 years ago
parent
commit
e248f6f54e
2 changed files with 24 additions and 3 deletions
  1. 7 3
      src/Network/Request.php
  2. 17 0
      tests/TestCase/Network/RequestTest.php

+ 7 - 3
src/Network/Request.php

@@ -617,6 +617,9 @@ class Request implements ArrayAccess
      */
     public function is($type)
     {
+        $args = func_get_args();
+        array_shift($args);
+
         if (is_array($type)) {
             $result = array_map([$this, 'is'], $type);
             return count(array_filter($result)) > 0;
@@ -628,7 +631,7 @@ class Request implements ArrayAccess
         }
 
         if (!isset($this->_detectorCache[$type])) {
-            $this->_detectorCache[$type] = $this->_is($type);
+            $this->_detectorCache[$type] = $this->_is($type, $args);
         }
 
         return $this->_detectorCache[$type];
@@ -651,11 +654,12 @@ class Request implements ArrayAccess
      *   this method will return true if the request matches any type.
      * @return bool Whether or not the request is the type you are checking.
      */
-    protected function _is($type)
+    protected function _is($type, $args)
     {
         $detect = static::$_detectors[$type];
         if (is_callable($detect)) {
-            return call_user_func($detect, $this);
+            array_unshift($args, $this);
+            return call_user_func_array($detect, $args);
         }
         if (isset($detect['env']) && $this->_environmentDetector($detect)) {
             return true;

+ 17 - 0
tests/TestCase/Network/RequestTest.php

@@ -58,6 +58,23 @@ class RequestTest extends TestCase
     }
 
     /**
+     * Test custom detector with extra arguments.
+     *
+     * @return void
+     */
+    public function testCustomArgsDetector()
+    {
+        $request = new Request();
+        $request->addDetector('controller', function ($request, $name) {
+            return $request->param('controller') === $name;
+        });
+
+        $request->params = ['controller' => 'cake'];
+        $this->assertTrue($request->is('controller', 'cake'));
+        $this->assertTrue($request->isController('cake'));
+    }
+
+    /**
      * Test the header detector.
      *
      * @return void