Skip to content

Commit

Permalink
Improve content-type detection
Browse files Browse the repository at this point in the history
  • Loading branch information
Nathan Macnamara committed Aug 27, 2015
1 parent 67d295b commit fd7322d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 9 deletions.
39 changes: 30 additions & 9 deletions src/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}

/**
Expand All @@ -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.
*
Expand Down
9 changes: 9 additions & 0 deletions tests/XMLTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
Expand Down

0 comments on commit fd7322d

Please sign in to comment.