Browse Source

Read content type in a more compatible way.

Not all webservers set CONTENT_TYPE. The built-in PHP webserver for
example sets HTTP_CONTENT_TYPE instead. Add a public method to the
request object to smooth over this difference.

Refs #6051
Mark Story 11 years ago
parent
commit
56634c792f
2 changed files with 31 additions and 1 deletions
  1. 15 1
      src/Network/Request.php
  2. 16 0
      tests/TestCase/Network/RequestTest.php

+ 15 - 1
src/Network/Request.php

@@ -276,7 +276,7 @@ class Request implements \ArrayAccess
     {
         $method = $this->env('REQUEST_METHOD');
         if (in_array($method, ['PUT', 'DELETE', 'PATCH']) &&
-            strpos($this->env('CONTENT_TYPE'), 'application/x-www-form-urlencoded') === 0
+            strpos($this->contentType(), 'application/x-www-form-urlencoded') === 0
         ) {
             $data = $this->input();
             parse_str($data, $data);
@@ -473,6 +473,20 @@ class Request implements \ArrayAccess
     }
 
     /**
+     * Get the content type used in this request.
+     *
+     * @return string
+     */
+    public function contentType()
+    {
+        $type = $this->env('CONTENT_TYPE');
+        if ($type) {
+            return $type;
+        }
+        return $this->env('HTTP_CONTENT_TYPE');
+    }
+
+    /**
      * Returns the instance of the Session object for this request
      *
      * If a session object is passed as first argument it will be set as

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

@@ -2399,6 +2399,22 @@ XML;
     }
 
     /**
+     * Test the content type method.
+     *
+     * @return void
+     */
+    public function testContentType()
+    {
+        $_SERVER['HTTP_CONTENT_TYPE'] = 'application/json';
+        $request = Request::createFromGlobals();
+        $this->assertEquals('application/json', $request->contentType());
+
+        $_SERVER['CONTENT_TYPE'] = 'application/xml';
+        $request = Request::createFromGlobals();
+        $this->assertEquals('application/xml', $request->contentType(), 'prefer non http header.');
+    }
+
+    /**
      * loadEnvironment method
      *
      * @param array $env