Permalink
Browse files

Add interface checks for context objects.

  • Loading branch information...
1 parent ec9f0fc commit 17e3dbfc1302308dd9932719e8564e243142a1a5 @markstory markstory committed Feb 10, 2014
Showing with 32 additions and 11 deletions.
  1. +14 −8 src/View/Helper/FormHelper.php
  2. +18 −3 tests/TestCase/View/Helper/FormHelperTest.php
@@ -22,6 +22,7 @@
use Cake\Utility\Inflector;
use Cake\Utility\Security;
use Cake\View\Form\ArrayContext;
+use Cake\View\Form\ContextInterface;
use Cake\View\Form\EntityContext;
use Cake\View\Form\NullContext;
use Cake\View\Helper;
@@ -204,10 +205,6 @@ protected function _addDefaultContextProviders() {
return new EntityContext($request, $data);
}
});
-
- $this->addContextProvider('_default', function ($request, $data) {
- return new NullContext($request, (array)$data);
- });
}
/**
@@ -2908,20 +2905,29 @@ public function context() {
/**
* Find the matching context provider for the data.
*
- * If no type can be matched the default provider will be returned.
+ * If no type can be matched a NullContext will be returned.
*
* @param mixed $data The data to get a context provider for.
* @return mixed Context provider.
+ * @throws RuntimeException when the context class does not implement the
+ * ContextInterface.
*/
protected function _buildContext($data) {
foreach ($this->_contextProviders as $key => $check) {
$context = $check($this->request, $data);
if ($context) {
- return $context;
+ break;
}
}
- $check = $this->_contextProviders['_default'];
- return $check($this->request, $data);
+ if (!isset($context)) {
+ $context = new NullContext($this->request, $data);
+ }
+ if (!($context instanceof ContextInterface)) {
+ throw new \RuntimeException(
+ 'Context objects must implement Cake\View\Form\ContextInterface'
+ );
+ }
+ return $context;
}
/**
@@ -553,12 +553,27 @@ public function testAddWidgetInvalid() {
*
* @return void
*/
- public function testContextClassMatching() {
+ public function testAddContextProvider() {
$context = 'My data';
$this->Form->addContextProvider('test', function ($request, $data) use ($context) {
$this->assertInstanceOf('Cake\Network\Request', $request);
- $this->assertEquals($context, $data);
- return new \StdObject();
+ $this->assertEquals($context, $data['entity']);
+ return $this->getMock('Cake\View\Form\ContextInterface');
+ });
+ $this->Form->create($context);
+ }
+
+/**
+ * Test adding an invalid context class.
+ *
+ * @expectedException RuntimeException
+ * @expectedExceptionMessage Context objects must implement Cake\View\Form\ContextInterface
+ * @return void
+ */
+ public function testAddContextProviderInvalid() {
+ $context = 'My data';
+ $this->Form->addContextProvider('test', function ($request, $data) use ($context) {
+ return new \StdClass();
});
$this->Form->create($context);
}

0 comments on commit 17e3dbf

Please sign in to comment.