diff --git a/src/Parser.php b/src/Parser.php index 27004bb..955a99c 100644 --- a/src/Parser.php +++ b/src/Parser.php @@ -166,10 +166,7 @@ private function process_mask($mask) */ public function payload($format = '') { - if (!empty($format)) - if (isset($this->supported_formats[$format])) - return $this->{$this->supported_formats[$format]}($this->getPayload()); - return $this->{$this->getFormat()}($this->getPayload()); + return $this->{$this->getFormat($format)}($this->getPayload()); } /** @@ -187,22 +184,46 @@ public function all() * * @return string Return the short format code (xml, json, ...). */ - public function getFormat() + public function getFormat($format = '') { + if (! empty($format)) { + return $this->processContentType($format); + } + if (isset($_SERVER['CONTENT_TYPE'])) { - if (isset($this->supported_formats[$_SERVER['CONTENT_TYPE']])) - return $this->supported_formats[$_SERVER['CONTENT_TYPE']]; + $type = $this->processContentType($_SERVER['CONTENT_TYPE']); + if ($type !== false) return $type; } + if (isset($_SERVER['HTTP_CONTENT_TYPE'])) { - if (isset($this->supported_formats[$_SERVER['HTTP_CONTENT_TYPE']])) - return $this->supported_formats[$_SERVER['HTTP_CONTENT_TYPE']]; + $type = $this->processContentType($_SERVER['HTTP_CONTENT_TYPE']); + if ($type !== false) return $type; } return 'json'; } + /** + * Process the content-type values + * + * @param string $contentType Content-Type raw string + * + * @return bool|string + */ + private function processContentType($contentType) + { + foreach (explode(';', $contentType) as $type) { + $type = strtolower(trim($type)); + if (isset($this->supported_formats[$type])) { + return $this->supported_formats[$type]; + } + } + + return false; + } + /** * Return the payload data from the HTTP post request. * diff --git a/tests/XMLTest.php b/tests/XMLTest.php index acb49c5..86308a8 100644 --- a/tests/XMLTest.php +++ b/tests/XMLTest.php @@ -104,6 +104,15 @@ public function format_detection_xml() $_SERVER['HTTP_CONTENT_TYPE'] = "application/xml"; $this->assertEquals('xml', $parser->getFormat()); + $_SERVER['HTTP_CONTENT_TYPE'] = "application/xml; charset=utf8"; + $this->assertEquals('xml', $parser->getFormat()); + + $_SERVER['HTTP_CONTENT_TYPE'] = "charset=utf8; application/xml"; + $this->assertEquals('xml', $parser->getFormat()); + + $_SERVER['HTTP_CONTENT_TYPE'] = "APPLICATION/XML"; + $this->assertEquals('xml', $parser->getFormat()); + $_SERVER['HTTP_CONTENT_TYPE'] = "text/xml"; $this->assertEquals('xml', $parser->getFormat()); }