/** * Static parsing of the request body * * This method extracts parameters from request body * by parsing content and either throws an exception if * the body is invalid XML or returns the decoded array from XML. * * @throws Frapi_Error * @return array|null decoded parameters */ public static function parse($format, $body=null) { switch(strtolower($format)) { case 'json': $jsonBody = json_decode($body, true); if(!is_null($jsonBody)) { return $jsonBody; } break; case 'xml': if(!empty($body)) { $parseResponse = Frapi_Input_XmlParser::arrayFromXml($body); if ($parseResponse instanceof Frapi_Exception) { throw new Frapi_Error('INVALID_REQUEST_BODY', $parseResponse->getMessage(), $parseResponse->getCode()); } return $parseResponse; } break; default: break; } }
/** * Create an Array from XML * * This method sets up the SimpleXMLIterator and starts the parsing * of an xml body to iterate through it and transform it into * an array that can be used by the developers. * * @param string $xml * @return array An array mapped to the passed xml */ public static function arrayFromXml($xml) { // replace namespace defs $xml = str_replace('xmlns=', 'ns=', $xml); // catch libxml errors libxml_use_internal_errors(true); try { $iterator = new SimpleXMLIterator($xml); } catch(Exception $e) { $xmlErrors = libxml_get_errors(); return new Frapi_Exception( 'Xml Parsing Failed', 'INVALID_XML', 400, 'xml_parsing' ); libxml_clear_errors(); } $xmlRoot = $iterator->getName(); $type = $iterator->attributes()->type; // SimpleXML provides the root information on construct self::$_xmlRoot = $iterator->getName(); self::$_responseType = $type; // return the mapped array with the root element as the header return array($xmlRoot => self::_iteratorToArray($iterator)); }