/** * @covers \Cougar\RestService\RestService::body */ public function testBodyXmlAsArray() { global $_BODY; $xml = new \SimpleXMLElement("<unit_test/>"); $xml->addChild("key", "value"); $_BODY = $xml->asXML(); $this->assertEquals(Xml::toArray($xml), $this->object->body("array")); }
/** * @covers \Cougar\Util\Xml::toArray * @depends testToXmlWithAssociativeArrayWithObject */ public function testToObjectWithAssociativeArrayWithObject() { $object = new \stdClass(); $object->property = "value"; $array = array("a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5, "object" => $object); $xml = Xml::toXml($array); $array["object"] = (array) $array["object"]; $object = Xml::toArray($xml); $this->assertEquals($array, $object); }
/** * Returns the body of the request, optionally parsing it as a specified * type of object. These are: * * XML - Parse the body as XML and return as a SimpleXML object * OBJECT - Parse the body as a JSON, XML or PHP serialized object and * return as an object * ARRAY - Parse the body as a JSON or XML object and return as an assoc. * array * PHP - Parse the body as serialized PHP data * * If parsing fails the call will throw a BadRequestException. * * If no parse type is specified, the body will be returned as a string. * * @history * 2013.09.30: * (AT) Initial release * 2014.08:06: * (AT) Allow conversion of XML to object or array, or PHP to object * * @version 2014.08.06 * @author (AT) Alberto Trevino, Brigham Young Univ. <*****@*****.**> * * @param string $parse_type xml|object|array|php * @throws \Cougar\Exceptions\BadRequestException * @return mixed Body */ public function body($parse_type = null) { if ($this->body === null) { # Get the body if ($this->__testMode) { # In test mode, read the body from the $_BODY variable global $_BODY; $this->body = trim($_BODY); } else { $this->body = trim(file_get_contents("php://input")); } } # See if we will be parsing the data if ($this->body) { switch (strtolower($parse_type)) { case "xml": return new \SimpleXMLElement($this->body); break; case "object": try { return Xml::toObject(new \SimpleXMLElement($this->body)); } catch (\Exception $e) { try { return unserialize($this->body); } catch (\Exception $e) { $object = json_decode($this->body); if ($object === null) { throw new BadRequestException("Body must be a valid JSON, XML or " . "serialized PHP object"); } return $object; } } break; case "array": try { return Xml::toArray(new \SimpleXMLElement($this->body)); } catch (\Exception $e) { $object = json_decode($this->body, true); if ($object === null) { throw new BadRequestException("Body must be a valid JSON or XML object"); } return $object; } break; case "php": return unserialize($this->body); break; default: return $this->body; break; } } else { return $this->body; } }