Browse Source

Include a session on the PSR7 request.

Having access to the session on the request will be handy in middleware
objects as it can be useful to have authentication data available.

Refs #6960
Mark Story 9 years ago
parent
commit
77c8c7e75c

+ 10 - 1
src/Http/ServerRequestFactory.php

@@ -15,6 +15,7 @@
 namespace Cake\Http;
 
 use Cake\Core\Configure;
+use Cake\Network\Session;
 use Cake\Utility\Hash;
 use Zend\Diactoros\ServerRequestFactory as BaseFactory;
 
@@ -39,8 +40,16 @@ abstract class ServerRequestFactory extends BaseFactory
     ) {
         $request = parent::fromGlobals($server, $query, $body, $cookies, $files);
         list($base, $webroot) = static::getBase($request);
+
+        $sessionConfig = (array)Configure::read('Session') + [
+            'defaults' => 'php',
+            'cookiePath' => $webroot
+        ];
+        $session = Session::create($sessionConfig);
         $request = $request->withAttribute('base', $base)
-            ->withAttribute('webroot', $webroot);
+            ->withAttribute('webroot', $webroot)
+            ->withAttribute('session', $session);
+
         if ($base) {
             $request = static::updatePath($base, $request);
         }

+ 1 - 1
tests/TestCase/Http/RequestTransformerTest.php

@@ -259,7 +259,7 @@ class RequestTransformerTest extends TestCase
         $psr = ServerRequestFactory::fromGlobals($server);
         $cake = RequestTransformer::toCake($psr);
 
-        $this->assertEquals('/thisapp', ini_get('session.cookie_path'));
+        $this->assertEquals('/thisapp/', ini_get('session.cookie_path'));
     }
 
     /**

+ 19 - 0
tests/TestCase/Http/ServerRequestFactoryTest.php

@@ -46,6 +46,25 @@ class ServerRequestFactoryTest extends TestCase
     }
 
     /**
+     * Test fromGlobals includes the session
+     *
+     * @return void
+     */
+    public function testFromGlobalsUrlSession()
+    {
+        Configure::write('App.base', '/basedir');
+        $server = [
+            'DOCUMENT_ROOT' => '/cake/repo/branches/1.2.x.x/webroot',
+            'PHP_SELF' => '/index.php',
+            'REQUEST_URI' => '/posts/add',
+        ];
+        $res = ServerRequestFactory::fromGlobals($server);
+        $session = $res->getAttribute('session');
+        $this->assertInstanceOf('Cake\Network\Session', $session);
+        $this->assertEquals('/basedir/', ini_get('session.cookie_path'), 'Needs trailing / for cookie to work');
+    }
+
+    /**
      * Test fromGlobals with App.base defined.
      *
      * @return void