Browse Source

Merge pull request #9573 from cakephp/psr7-helpers

Use PSR7 request methods in helpers
José Lorenzo Rodríguez 9 years ago
parent
commit
9e94d95624

+ 8 - 8
src/Network/Request.php

@@ -1423,13 +1423,13 @@ class Request implements ArrayAccess, ServerRequestInterface
      * will be created for you.
      *
      * @param string|null $name Dot separated name of the value to read/write
+     * @param mixed ...$args The data to set (deprecated)
      * @return mixed|$this Either the value being read, or this so you can chain consecutive writes.
      */
-    public function data($name = null)
+    public function data($name = null, ...$args)
     {
-        $args = func_get_args();
-        if (count($args) === 2) {
-            $this->data = Hash::insert($this->data, $name, $args[1]);
+        if (count($args) === 1) {
+            $this->data = Hash::insert($this->data, $name, $args[0]);
 
             return $this;
         }
@@ -1447,14 +1447,14 @@ class Request implements ArrayAccess, ServerRequestInterface
      * Use `withParam` instead.
      *
      * @param string $name The name of the parameter to get.
+     * @param mixed ...$args Value to set (deprecated).
      * @return mixed|$this The value of the provided parameter. Will
      *   return false if the parameter doesn't exist or is falsey.
      */
-    public function param($name)
+    public function param($name, ...$args)
     {
-        $args = func_get_args();
-        if (count($args) === 2) {
-            $this->params = Hash::insert($this->params, $name, $args[1]);
+        if (count($args) === 1) {
+            $this->params = Hash::insert($this->params, $name, $args[0]);
 
             return $this;
         }

+ 10 - 12
src/View/Helper/FormHelper.php

@@ -480,8 +480,8 @@ class FormHelper extends Helper
 
         $actionDefaults = [
             'plugin' => $this->plugin,
-            'controller' => $this->request->params['controller'],
-            'action' => $this->request->params['action'],
+            'controller' => $this->request->param('controller'),
+            'action' => $this->request->param('action'),
         ];
 
         $action = (array)$options['url'] + $actionDefaults;
@@ -520,17 +520,17 @@ class FormHelper extends Helper
      */
     protected function _csrfField()
     {
-        if (!empty($this->request['_Token']['unlockedFields'])) {
-            foreach ((array)$this->request['_Token']['unlockedFields'] as $unlocked) {
+        if ($this->request->param('_Token.unlockedFields')) {
+            foreach ((array)$this->request->param('_Token.unlockedFields') as $unlocked) {
                 $this->_unlockedFields[] = $unlocked;
             }
         }
-        if (empty($this->request->params['_csrfToken'])) {
+        if (!$this->request->param('_csrfToken')) {
             return '';
         }
 
         return $this->hidden('_csrfToken', [
-            'value' => $this->request->params['_csrfToken'],
+            'value' => $this->request->param('_csrfToken'),
             'secure' => static::SECURE_SKIP
         ]);
     }
@@ -550,9 +550,7 @@ class FormHelper extends Helper
     {
         $out = '';
 
-        if ($this->requestType !== 'get' &&
-            !empty($this->request['_Token'])
-        ) {
+        if ($this->requestType !== 'get' && $this->request->param('_Token')) {
             $out .= $this->secure($this->fields, $secureAttributes);
             $this->fields = [];
             $this->_unlockedFields = [];
@@ -585,7 +583,7 @@ class FormHelper extends Helper
      */
     public function secure(array $fields = [], array $secureAttributes = [])
     {
-        if (empty($this->request['_Token'])) {
+        if (!$this->request->param('_Token')) {
             return '';
         }
         $debugSecurity = Configure::read('debug');
@@ -982,7 +980,7 @@ class FormHelper extends Helper
             if (!$isCreate) {
                 $actionName = __d('cake', 'Edit %s');
             }
-            $modelName = Inflector::humanize(Inflector::singularize($this->request->params['controller']));
+            $modelName = Inflector::humanize(Inflector::singularize($this->request->param('controller')));
             $legend = sprintf($actionName, $modelName);
         }
 
@@ -2461,7 +2459,7 @@ class FormHelper extends Helper
     protected function _initInputField($field, $options = [])
     {
         if (!isset($options['secure'])) {
-            $options['secure'] = !empty($this->request->params['_Token']);
+            $options['secure'] = (bool)$this->request->param('_Token');
         }
         $context = $this->_getContext();
 

+ 10 - 10
src/View/Helper/PaginatorHelper.php

@@ -99,11 +99,11 @@ class PaginatorHelper extends Helper
     {
         parent::__construct($View, $config);
 
-        $query = $this->request->query;
+        $query = $this->request->getQueryParams();
         unset($query['page'], $query['limit'], $query['sort'], $query['direction']);
         $this->config(
             'options.url',
-            array_merge($this->request->params['pass'], ['?' => $query])
+            array_merge($this->request->param('pass'), ['?' => $query])
         );
     }
 
@@ -118,11 +118,11 @@ class PaginatorHelper extends Helper
         if (empty($model)) {
             $model = $this->defaultModel();
         }
-        if (!isset($this->request->params['paging']) || empty($this->request->params['paging'][$model])) {
+        if (!$this->request->param('paging') || !$this->request->param('paging.' . $model)) {
             return [];
         }
 
-        return $this->request->params['paging'][$model];
+        return $this->request->param('paging.' . $model);
     }
 
     /**
@@ -152,19 +152,19 @@ class PaginatorHelper extends Helper
     public function options(array $options = [])
     {
         if (!empty($options['paging'])) {
-            if (!isset($this->request->params['paging'])) {
+            if (!$this->request->param('paging')) {
                 $this->request->params['paging'] = [];
             }
-            $this->request->params['paging'] = $options['paging'] + $this->request->params['paging'];
+            $this->request->params['paging'] = $options['paging'] + $this->request->param('paging');
             unset($options['paging']);
         }
         $model = $this->defaultModel();
 
         if (!empty($options[$model])) {
-            if (!isset($this->request->params['paging'][$model])) {
+            if (!$this->request->param('paging.' . $model)) {
                 $this->request->params['paging'][$model] = [];
             }
-            $this->request->params['paging'][$model] = $options[$model] + $this->request->params['paging'][$model];
+            $this->request->params['paging'][$model] = $options[$model] + $this->request->param('paging.' . $model);
             unset($options[$model]);
         }
         $this->_config['options'] = array_filter($options + $this->_config['options']);
@@ -595,10 +595,10 @@ class PaginatorHelper extends Helper
         if ($this->_defaultModel) {
             return $this->_defaultModel;
         }
-        if (empty($this->request->params['paging'])) {
+        if (!$this->request->param('paging')) {
             return null;
         }
-        list($this->_defaultModel) = array_keys($this->request->params['paging']);
+        list($this->_defaultModel) = array_keys($this->request->param('paging'));
 
         return $this->_defaultModel;
     }

+ 4 - 4
src/View/Helper/UrlHelper.php

@@ -203,7 +203,7 @@ class UrlHelper extends Helper
         $timestampEnabled = $stamp === 'force' || ($stamp === true && Configure::read('debug'));
         if ($timestampEnabled && strpos($path, '?') === false) {
             $filepath = preg_replace(
-                '/^' . preg_quote($this->request->webroot, '/') . '/',
+                '/^' . preg_quote($this->request->getAttribute('webroot'), '/') . '/',
                 '',
                 urldecode($path)
             );
@@ -237,7 +237,7 @@ class UrlHelper extends Helper
     {
         $asset = explode('?', $file);
         $asset[1] = isset($asset[1]) ? '?' . $asset[1] : null;
-        $webPath = $this->request->webroot . $asset[0];
+        $webPath = $this->request->getAttribute('webroot') . $asset[0];
         $file = $asset[0];
 
         if (!empty($this->theme)) {
@@ -249,12 +249,12 @@ class UrlHelper extends Helper
             }
 
             if (file_exists(Configure::read('App.wwwRoot') . $theme . $file)) {
-                $webPath = $this->request->webroot . $theme . $asset[0];
+                $webPath = $this->request->getAttribute('webroot') . $theme . $asset[0];
             } else {
                 $themePath = Plugin::path($this->theme);
                 $path = $themePath . 'webroot/' . $file;
                 if (file_exists($path)) {
-                    $webPath = $this->request->webroot . $theme . $asset[0];
+                    $webPath = $this->request->getAttribute('webroot') . $theme . $asset[0];
                 }
             }
         }

+ 2 - 2
src/View/JsonView.php

@@ -111,8 +111,8 @@ class JsonView extends SerializedView
             if ($this->viewVars['_jsonp'] === true) {
                 $jsonpParam = 'callback';
             }
-            if (isset($this->request->query[$jsonpParam])) {
-                $return = sprintf('%s(%s)', h($this->request->query[$jsonpParam]), $return);
+            if ($this->request->query($jsonpParam)) {
+                $return = sprintf('%s(%s)', h($this->request->query($jsonpParam)), $return);
                 $this->response->type('js');
             }
         }

+ 10 - 14
src/View/View.php

@@ -109,7 +109,7 @@ class View implements EventDispatcherInterface
      * Current passed params. Passed to View from the creating Controller for convenience.
      *
      * @var array
-     * @deprecated 3.1.0 Use `$this->request->params['pass']` instead.
+     * @deprecated 3.1.0 Use `$this->request->param('pass')` instead.
      */
     public $passedArgs = [];
 
@@ -330,18 +330,14 @@ class View implements EventDispatcherInterface
             }
         }
         $this->eventManager($eventManager);
-        $this->request = $request;
-        $this->response = $response;
+        $this->request = $request ?: Router::getRequest(true);
+        $this->response = $response ?: new Response();
         if (empty($this->request)) {
-            $this->request = Router::getRequest(true);
-        }
-        if (empty($this->request)) {
-            $this->request = new Request();
-            $this->request->base = '';
-            $this->request->here = $this->request->webroot = '/';
-        }
-        if (empty($this->response)) {
-            $this->response = new Response();
+            $this->request = new Request([
+                'base' => '',
+                'url' => '',
+                'webroot' => '/'
+            ]);
         }
         $this->Blocks = new ViewBlock();
         $this->initialize();
@@ -1230,8 +1226,8 @@ class View implements EventDispatcherInterface
     protected function _getSubPaths($basePath)
     {
         $paths = [$basePath];
-        if (!empty($this->request->params['prefix'])) {
-            $prefixPath = explode('/', $this->request->params['prefix']);
+        if ($this->request->param('prefix')) {
+            $prefixPath = explode('/', $this->request->param('prefix'));
             $path = '';
             foreach ($prefixPath as $prefixPart) {
                 $path .= Inflector::camelize($prefixPart) . DIRECTORY_SEPARATOR;

+ 32 - 29
tests/TestCase/View/Helper/FormHelperTest.php

@@ -139,16 +139,18 @@ class FormHelperTest extends TestCase
         Configure::write('Config.language', 'eng');
         Configure::write('App.base', '');
         Configure::write('App.namespace', 'Cake\Test\TestCase\View\Helper');
-        Configure::delete('Asset');
         $this->View = new View();
 
         $this->Form = new FormHelper($this->View);
-        $request = new Request('articles/add');
-        $request->here = '/articles/add';
-        $request['controller'] = 'articles';
-        $request['action'] = 'add';
-        $request->webroot = '';
-        $request->base = '';
+        $request = new Request([
+            'webroot' => '',
+            'base' => '',
+            'url' => '/articles/add',
+            'params' => [
+                'controller' => 'articles',
+                'action' => 'add',
+            ]
+        ]);
         $this->Form->Url->request = $this->Form->request = $request;
 
         $this->dateRegex = [
@@ -690,14 +692,15 @@ class FormHelperTest extends TestCase
         $encoding = strtolower(Configure::read('App.encoding'));
 
         $this->Form->request->here = '/articles/edit/1';
-        $this->Form->request['action'] = 'edit';
+        $this->Form->request->params['action'] = 'edit';
 
         $this->article['defaults']['id'] = 1;
 
         $result = $this->Form->create($this->article);
         $expected = [
             'form' => [
-                'method' => 'post', 'action' => '/articles/edit/1',
+                'method' => 'post',
+                'action' => '/articles/edit/1',
                 'accept-charset' => $encoding
             ],
             'div' => ['style' => 'display:none;'],
@@ -716,7 +719,7 @@ class FormHelperTest extends TestCase
     {
         $encoding = strtolower(Configure::read('App.encoding'));
 
-        $this->Form->request['action'] = 'delete';
+        $this->Form->request->params['action'] = 'delete';
         $this->Form->request->here = '/articles/delete/10';
         $this->Form->request->base = '';
         $result = $this->Form->create($this->article);
@@ -733,7 +736,7 @@ class FormHelperTest extends TestCase
 
         $this->article['defaults'] = ['id' => 1];
         $this->Form->request->here = '/articles/edit/1';
-        $this->Form->request['action'] = 'delete';
+        $this->Form->request->params['action'] = 'delete';
         $result = $this->Form->create($this->article, ['url' => ['action' => 'edit']]);
         $expected = [
             'form' => [
@@ -747,7 +750,7 @@ class FormHelperTest extends TestCase
         ];
         $this->assertHtml($expected, $result);
 
-        $this->Form->request['action'] = 'add';
+        $this->Form->request->params['action'] = 'add';
         $result = $this->Form->create($this->article, ['url' => ['action' => 'publish']]);
         $expected = [
             'form' => [
@@ -770,7 +773,7 @@ class FormHelperTest extends TestCase
         ];
         $this->assertHtml($expected, $result);
 
-        $this->Form->request['controller'] = 'Pages';
+        $this->Form->request->params['controller'] = 'Pages';
         $result = $this->Form->create($this->article, ['url' => ['action' => 'signup']]);
         $expected = [
             'form' => [
@@ -814,7 +817,7 @@ class FormHelperTest extends TestCase
         Router::connect('/login', ['controller' => 'users', 'action' => 'login']);
         $encoding = strtolower(Configure::read('App.encoding'));
 
-        $this->Form->request['controller'] = 'users';
+        $this->Form->request->params['controller'] = 'users';
 
         $result = $this->Form->create(false, ['url' => ['action' => 'login']]);
         $expected = [
@@ -1008,7 +1011,7 @@ class FormHelperTest extends TestCase
     public function testGetFormWithFalseModel()
     {
         $encoding = strtolower(Configure::read('App.encoding'));
-        $this->Form->request['controller'] = 'contact_test';
+        $this->Form->request->params['controller'] = 'contact_test';
         $result = $this->Form->create(false, [
             'type' => 'get', 'url' => ['controller' => 'contact_test']
         ]);
@@ -1656,11 +1659,11 @@ class FormHelperTest extends TestCase
      */
     public function testFormSecurityInputUnlockedFields()
     {
-        $this->Form->request['_Token'] = [
+        $this->Form->request->params['_Token'] = [
             'unlockedFields' => ['first_name', 'address']
         ];
         $this->Form->create();
-        $this->assertEquals($this->Form->request['_Token']['unlockedFields'], $this->Form->unlockField());
+        $this->assertEquals($this->Form->request->params['_Token']['unlockedFields'], $this->Form->unlockField());
 
         $this->Form->hidden('Addresses.id', ['value' => '123456']);
         $this->Form->text('Addresses.title');
@@ -1728,11 +1731,11 @@ class FormHelperTest extends TestCase
      */
     public function testFormSecurityInputUnlockedFieldsDebugSecurityTrue()
     {
-        $this->Form->request['_Token'] = [
+        $this->Form->request->params['_Token'] = [
             'unlockedFields' => ['first_name', 'address']
         ];
         $this->Form->create();
-        $this->assertEquals($this->Form->request['_Token']['unlockedFields'], $this->Form->unlockField());
+        $this->assertEquals($this->Form->request->params['_Token']['unlockedFields'], $this->Form->unlockField());
 
         $this->Form->hidden('Addresses.id', ['value' => '123456']);
         $this->Form->text('Addresses.title');
@@ -1799,11 +1802,11 @@ class FormHelperTest extends TestCase
      */
     public function testFormSecurityInputUnlockedFieldsDebugSecurityDebugFalse()
     {
-        $this->Form->request['_Token'] = [
+        $this->Form->request->params['_Token'] = [
             'unlockedFields' => ['first_name', 'address']
         ];
         $this->Form->create();
-        $this->assertEquals($this->Form->request['_Token']['unlockedFields'], $this->Form->unlockField());
+        $this->assertEquals($this->Form->request->params['_Token']['unlockedFields'], $this->Form->unlockField());
 
         $this->Form->hidden('Addresses.id', ['value' => '123456']);
         $this->Form->text('Addresses.title');
@@ -1851,11 +1854,11 @@ class FormHelperTest extends TestCase
      */
     public function testFormSecurityInputUnlockedFieldsDebugSecurityFalse()
     {
-        $this->Form->request['_Token'] = [
+        $this->Form->request->params['_Token'] = [
             'unlockedFields' => ['first_name', 'address']
         ];
         $this->Form->create();
-        $this->assertEquals($this->Form->request['_Token']['unlockedFields'], $this->Form->unlockField());
+        $this->assertEquals($this->Form->request->params['_Token']['unlockedFields'], $this->Form->unlockField());
 
         $this->Form->hidden('Addresses.id', ['value' => '123456']);
         $this->Form->text('Addresses.title');
@@ -2251,7 +2254,7 @@ class FormHelperTest extends TestCase
      */
     public function testDisableSecurityUsingForm()
     {
-        $this->Form->request['_Token'] = [
+        $this->Form->request->params['_Token'] = [
             'disabledFields' => []
         ];
         $this->Form->create();
@@ -2276,7 +2279,7 @@ class FormHelperTest extends TestCase
      */
     public function testUnlockFieldAddsToList()
     {
-        $this->Form->request['_Token'] = [
+        $this->Form->request->params['_Token'] = [
             'unlockedFields' => []
         ];
         $this->Form->unlockField('Contact.name');
@@ -2293,7 +2296,7 @@ class FormHelperTest extends TestCase
      */
     public function testUnlockFieldRemovingFromFields()
     {
-        $this->Form->request['_Token'] = [
+        $this->Form->request->params['_Token'] = [
             'unlockedFields' => []
         ];
         $this->Form->create($this->article);
@@ -2315,7 +2318,7 @@ class FormHelperTest extends TestCase
      */
     public function testResetUnlockFields()
     {
-        $this->Form->request['_Token'] = [
+        $this->Form->request->params['_Token'] = [
             'key' => 'testKey',
             'unlockedFields' => []
         ];
@@ -2338,7 +2341,7 @@ class FormHelperTest extends TestCase
      */
     public function testSecuredFormUrlIgnoresHost()
     {
-        $this->Form->request['_Token'] = ['key' => 'testKey'];
+        $this->Form->request->params['_Token'] = ['key' => 'testKey'];
 
         $expected = '0ff0c85cd70584d8fd18fa136846d22c66c21e2d%3A';
         $this->Form->create($this->article, [
@@ -2367,7 +2370,7 @@ class FormHelperTest extends TestCase
      */
     public function testSecuredFormUrlHasHtmlAndIdentifer()
     {
-        $this->Form->request['_Token'] = ['key' => 'testKey'];
+        $this->Form->request->params['_Token'] = ['key' => 'testKey'];
 
         $expected = 'ece0693fb1b19ca116133db1832ac29baaf41ce5%3A';
         $res = $this->Form->create($this->article, [

+ 4 - 3
tests/TestCase/View/Helper/HtmlHelperTest.php

@@ -61,12 +61,13 @@ class HtmlHelperTest extends TestCase
             ->setMethods(['append'])
             ->getMock();
         $this->Html = new HtmlHelper($this->View);
-        $this->Html->request = new Request();
-        $this->Html->request->webroot = '';
+        $this->Html->request = new Request([
+            'webroot' => '',
+        ]);
         $this->Html->Url->request = $this->Html->request;
 
-        Configure::write('App.namespace', 'TestApp');
         Plugin::load(['TestTheme']);
+        Configure::write('App.namespace', 'TestApp');
         Configure::write('Asset.timestamp', false);
     }
 

+ 8 - 9
tests/TestCase/View/Helper/PaginatorHelperTest.php

@@ -59,7 +59,6 @@ class PaginatorHelperTest extends TestCase
             ]
         ]);
 
-        Configure::write('Routing.prefixes', []);
         Router::reload();
         Router::connect('/:controller/:action/*');
         Router::connect('/:plugin/:controller/:action/*');
@@ -142,7 +141,7 @@ class PaginatorHelperTest extends TestCase
         ]);
 
         $this->Paginator->options(['url' => ['param']]);
-        $this->Paginator->request['paging'] = [
+        $this->Paginator->request->params['paging'] = [
             'Article' => [
                 'current' => 9,
                 'count' => 62,
@@ -2389,7 +2388,7 @@ class PaginatorHelperTest extends TestCase
      */
     public function testWithOnePage()
     {
-        $this->Paginator->request['paging'] = [
+        $this->Paginator->request->params['paging'] = [
             'Article' => [
                 'page' => 1,
                 'current' => 2,
@@ -2411,7 +2410,7 @@ class PaginatorHelperTest extends TestCase
      */
     public function testWithZeroPages()
     {
-        $this->Paginator->request['paging'] = [
+        $this->Paginator->request->params['paging'] = [
             'Article' => [
                 'page' => 0,
                 'current' => 0,
@@ -2436,7 +2435,7 @@ class PaginatorHelperTest extends TestCase
      */
     public function testMetaPage0()
     {
-        $this->Paginator->request['paging'] = [
+        $this->Paginator->request->params['paging'] = [
             'Article' => [
                 'page' => 1,
                 'prevPage' => false,
@@ -2457,7 +2456,7 @@ class PaginatorHelperTest extends TestCase
      */
     public function testMetaPage1()
     {
-        $this->Paginator->request['paging'] = [
+        $this->Paginator->request->params['paging'] = [
             'Article' => [
                 'page' => 1,
                 'prevPage' => false,
@@ -2478,7 +2477,7 @@ class PaginatorHelperTest extends TestCase
      */
     public function testMetaPage1InlineFalse()
     {
-        $this->Paginator->request['paging'] = [
+        $this->Paginator->request->params['paging'] = [
             'Article' => [
                 'page' => 1,
                 'prevPage' => false,
@@ -2500,7 +2499,7 @@ class PaginatorHelperTest extends TestCase
      */
     public function testMetaPage1Last()
     {
-        $this->Paginator->request['paging'] = [
+        $this->Paginator->request->params['paging'] = [
             'Article' => [
                 'page' => 2,
                 'prevPage' => true,
@@ -2522,7 +2521,7 @@ class PaginatorHelperTest extends TestCase
      */
     public function testMetaPage10Last()
     {
-        $this->Paginator->request['paging'] = [
+        $this->Paginator->request->params['paging'] = [
             'Article' => [
                 'page' => 5,
                 'prevPage' => true,