Browse Source

Merge pull request #10501 from cleptric/env-getter-setter

Split ServerRequest::env() into getter/setter
Mark Story 9 years ago
parent
commit
fb318f222b

+ 3 - 3
src/Auth/BasicAuthenticate.php

@@ -73,8 +73,8 @@ class BasicAuthenticate extends BaseAuthenticate
      */
     public function getUser(ServerRequest $request)
     {
-        $username = $request->env('PHP_AUTH_USER');
-        $pass = $request->env('PHP_AUTH_PW');
+        $username = $request->getEnv('PHP_AUTH_USER');
+        $pass = $request->getEnv('PHP_AUTH_PW');
 
         if (!is_string($username) || $username === '' || !is_string($pass) || $pass === '') {
             return false;
@@ -106,7 +106,7 @@ class BasicAuthenticate extends BaseAuthenticate
      */
     public function loginHeaders(ServerRequest $request)
     {
-        $realm = $this->getConfig('realm') ?: $request->env('SERVER_NAME');
+        $realm = $this->getConfig('realm') ?: $request->getEnv('SERVER_NAME');
 
         return sprintf('WWW-Authenticate: Basic realm="%s"', $realm);
     }

+ 3 - 3
src/Auth/DigestAuthenticate.php

@@ -120,7 +120,7 @@ class DigestAuthenticate extends BasicAuthenticate
         $password = $user[$field];
         unset($user[$field]);
 
-        $hash = $this->generateResponseHash($digest, $password, $request->env('ORIGINAL_REQUEST_METHOD'));
+        $hash = $this->generateResponseHash($digest, $password, $request->getEnv('ORIGINAL_REQUEST_METHOD'));
         if ($digest['response'] === $hash) {
             return $user;
         }
@@ -136,7 +136,7 @@ class DigestAuthenticate extends BasicAuthenticate
      */
     protected function _getDigest(ServerRequest $request)
     {
-        $digest = $request->env('PHP_AUTH_DIGEST');
+        $digest = $request->getEnv('PHP_AUTH_DIGEST');
         if (empty($digest) && function_exists('apache_request_headers')) {
             $headers = apache_request_headers();
             if (!empty($headers['Authorization']) && substr($headers['Authorization'], 0, 7) === 'Digest ') {
@@ -215,7 +215,7 @@ class DigestAuthenticate extends BasicAuthenticate
      */
     public function loginHeaders(ServerRequest $request)
     {
-        $realm = $this->_config['realm'] ?: $request->env('SERVER_NAME');
+        $realm = $this->_config['realm'] ?: $request->getEnv('SERVER_NAME');
 
         $options = [
             'realm' => $realm,

+ 1 - 1
src/Error/BaseErrorHandler.php

@@ -329,7 +329,7 @@ abstract class BaseErrorHandler
     {
         $message = "\nRequest URL: " . $request->getRequestTarget();
 
-        $referer = $request->env('HTTP_REFERER');
+        $referer = $request->getEnv('HTTP_REFERER');
         if ($referer) {
             $message .= "\nReferer URL: " . $referer;
         }

+ 66 - 27
src/Http/ServerRequest.php

@@ -351,7 +351,7 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
      */
     protected function _processPost($data)
     {
-        $method = $this->env('REQUEST_METHOD');
+        $method = $this->getEnv('REQUEST_METHOD');
         $override = false;
 
         if (in_array($method, ['PUT', 'DELETE', 'PATCH']) &&
@@ -506,12 +506,12 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
      */
     public function contentType()
     {
-        $type = $this->env('CONTENT_TYPE');
+        $type = $this->getEnv('CONTENT_TYPE');
         if ($type) {
             return $type;
         }
 
-        return $this->env('HTTP_CONTENT_TYPE');
+        return $this->getEnv('HTTP_CONTENT_TYPE');
     }
 
     /**
@@ -550,12 +550,12 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
      */
     public function clientIp()
     {
-        if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_FOR')) {
-            $ipaddr = preg_replace('/(?:,.*)/', '', $this->env('HTTP_X_FORWARDED_FOR'));
-        } elseif ($this->trustProxy && $this->env('HTTP_CLIENT_IP')) {
-            $ipaddr = $this->env('HTTP_CLIENT_IP');
+        if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_FOR')) {
+            $ipaddr = preg_replace('/(?:,.*)/', '', $this->getEnv('HTTP_X_FORWARDED_FOR'));
+        } elseif ($this->trustProxy && $this->getEnv('HTTP_CLIENT_IP')) {
+            $ipaddr = $this->getEnv('HTTP_CLIENT_IP');
         } else {
-            $ipaddr = $this->env('REMOTE_ADDR');
+            $ipaddr = $this->getEnv('REMOTE_ADDR');
         }
 
         return trim($ipaddr);
@@ -570,7 +570,7 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
      */
     public function referer($local = false)
     {
-        $ref = $this->env('HTTP_REFERER');
+        $ref = $this->getEnv('HTTP_REFERER');
 
         $base = Configure::read('App.fullBaseUrl') . $this->webroot;
         if (!empty($ref) && !empty($base)) {
@@ -730,7 +730,7 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
      */
     protected function _acceptHeaderDetector($detect)
     {
-        $acceptHeaders = explode(',', $this->env('HTTP_ACCEPT'));
+        $acceptHeaders = explode(',', $this->getEnv('HTTP_ACCEPT'));
         foreach ($detect['accept'] as $header) {
             if (in_array($header, $acceptHeaders)) {
                 return true;
@@ -749,7 +749,7 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
     protected function _headerDetector($detect)
     {
         foreach ($detect['header'] as $header => $value) {
-            $header = $this->env('http_' . $header);
+            $header = $this->getEnv('http_' . $header);
             if ($header !== null) {
                 if (!is_string($value) && !is_bool($value) && is_callable($value)) {
                     return call_user_func($value, $header);
@@ -793,15 +793,15 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
     {
         if (isset($detect['env'])) {
             if (isset($detect['value'])) {
-                return $this->env($detect['env']) == $detect['value'];
+                return $this->getEnv($detect['env']) == $detect['value'];
             }
             if (isset($detect['pattern'])) {
-                return (bool)preg_match($detect['pattern'], $this->env($detect['env']));
+                return (bool)preg_match($detect['pattern'], $this->getEnv($detect['env']));
             }
             if (isset($detect['options'])) {
                 $pattern = '/' . implode('|', $detect['options']) . '/i';
 
-                return (bool)preg_match($pattern, $this->env($detect['env']));
+                return (bool)preg_match($pattern, $this->getEnv($detect['env']));
             }
         }
 
@@ -977,7 +977,7 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
     {
         $name = $this->normalizeHeaderName($name);
 
-        return $this->env($name);
+        return $this->getEnv($name);
     }
 
     /**
@@ -1128,7 +1128,7 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
      */
     public function method()
     {
-        return $this->env('REQUEST_METHOD');
+        return $this->getEnv('REQUEST_METHOD');
     }
 
     /**
@@ -1147,7 +1147,7 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
      */
     public function getMethod()
     {
-        return $this->env('REQUEST_METHOD');
+        return $this->getEnv('REQUEST_METHOD');
     }
 
     /**
@@ -1222,11 +1222,11 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
      */
     public function host()
     {
-        if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_HOST')) {
-            return $this->env('HTTP_X_FORWARDED_HOST');
+        if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_HOST')) {
+            return $this->getEnv('HTTP_X_FORWARDED_HOST');
         }
 
-        return $this->env('HTTP_HOST');
+        return $this->getEnv('HTTP_HOST');
     }
 
     /**
@@ -1236,11 +1236,11 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
      */
     public function port()
     {
-        if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PORT')) {
-            return $this->env('HTTP_X_FORWARDED_PORT');
+        if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_PORT')) {
+            return $this->getEnv('HTTP_X_FORWARDED_PORT');
         }
 
-        return $this->env('SERVER_PORT');
+        return $this->getEnv('SERVER_PORT');
     }
 
     /**
@@ -1252,11 +1252,11 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
      */
     public function scheme()
     {
-        if ($this->trustProxy && $this->env('HTTP_X_FORWARDED_PROTO')) {
-            return $this->env('HTTP_X_FORWARDED_PROTO');
+        if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_PROTO')) {
+            return $this->getEnv('HTTP_X_FORWARDED_PROTO');
         }
 
-        return $this->env('HTTPS') ? 'https' : 'http';
+        return $this->getEnv('HTTPS') ? 'https' : 'http';
     }
 
     /**
@@ -1723,7 +1723,7 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
         }
 
         // Lazily populate this data as it is generally not used.
-        preg_match('/^HTTP\/([\d.]+)$/', $this->env('SERVER_PROTOCOL'), $match);
+        preg_match('/^HTTP\/([\d.]+)$/', $this->getEnv('SERVER_PROTOCOL'), $match);
         $protocol = '1.1';
         if (isset($match[1])) {
             $protocol = $match[1];
@@ -1754,9 +1754,48 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
     }
 
     /**
+     * Get a value from the request's environment data.
+     * Fallback to using env() if the key is not set in the $environment property.
+     *
+     * @param string $key The key you want to read from.
+     * @param string|null $default Default value when trying to retrieve an environment
+     *   variable's value that does not exist.
+     * @return string|null Either the environment value, or null if the value doesn't exist.
+     */
+    public function getEnv($key, $default = null)
+    {
+        $key = strtoupper($key);
+        if (!array_key_exists($key, $this->_environment)) {
+            $this->_environment[$key] = env($key);
+        }
+
+        return $this->_environment[$key] !== null ? $this->_environment[$key] : $default;
+    }
+
+    /**
+     * Update the request with a new environment data element.
+     *
+     * Returns an updated request object. This method returns
+     * a *new* request object and does not mutate the request in-place.
+     *
+     * @param string $key The key you want to write to.
+     * @param string $value Value to set
+     * @return static
+     */
+    public function withEnv($key, $value)
+    {
+        $new = clone $this;
+        $new->_environment[$key] = $value;
+        $new->clearDetectorCache();
+
+        return $new;
+    }
+
+    /**
      * Get/Set value from the request's environment data.
      * Fallback to using env() if key not set in $environment property.
      *
+     * @deprecated 3.5.0 Use getEnv()/withEnv() instead.
      * @param string $key The key you want to read/write from/to.
      * @param string|null $value Value to set. Default null.
      * @param string|null $default Default value when trying to retrieve an environment

+ 1 - 1
src/Routing/Filter/AssetFilter.php

@@ -133,7 +133,7 @@ class AssetFilter extends DispatcherFilter
         $compressionEnabled = $response->compress();
         if ($response->type($ext) === $ext) {
             $contentType = 'application/octet-stream';
-            $agent = $request->env('HTTP_USER_AGENT');
+            $agent = $request->getEnv('HTTP_USER_AGENT');
             if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
                 $contentType = 'application/octetstream';
             }

+ 34 - 0
tests/TestCase/Http/ServerRequestTest.php

@@ -3535,6 +3535,40 @@ XML;
     }
 
     /**
+     * Test withEnv()
+     *
+     * @return void
+     */
+    public function testWithEnv()
+    {
+        $request = new ServerRequest();
+
+        $newRequest = $request->withEnv('HTTP_HOST', 'cakephp.org');
+        $this->assertNotSame($request, $newRequest);
+        $this->assertSame('cakephp.org', $newRequest->getEnv('HTTP_HOST'));
+    }
+
+    /**
+     * Test getEnv()
+     *
+     * @return void
+     */
+    public function testGetEnv()
+    {
+        $request = new ServerRequest();
+
+        //Test default null
+        $this->assertNull($request->getEnv('Foo'));
+
+        //Test default set
+        $this->assertSame('Bar', $request->getEnv('Foo', 'Bar'));
+
+        //Test env() fallback
+        $_SERVER['TEST'] = 'ing';
+        $this->assertSame('ing', $request->getEnv('test'));
+    }
+
+    /**
      * Data provider for emulated property tests.
      *
      * @return array