/** * Turn payload from structured data into * a string based on the current Mime type. * This uses the auto_serialize option to determine * it's course of action. See serialize method for more. * Renamed from _detectPayload to _serializePayload as of * 2012-02-15. * * Added in support for custom payload serializers. * The serialize_payload_method stuff still holds true though. * @see Request::registerPayloadSerializer() * * @return string * @param mixed $payload */ private function _serializePayload($payload) { if (empty($payload) || $this->serialize_payload_method === self::SERIALIZE_PAYLOAD_NEVER) { return $payload; } // When we are in "smart" mode, don't serialize strings/scalars, assume they are already serialized if ($this->serialize_payload_method === self::SERIALIZE_PAYLOAD_SMART && is_scalar($payload)) { return $payload; } // Use a custom serializer if one is registered for this mime type if (isset($this->payload_serializers['*']) || isset($this->payload_serializers[$this->content_type])) { $key = isset($this->payload_serializers[$this->content_type]) ? $this->content_type : '*'; return call_user_func($this->payload_serializers[$key], $payload); } return Httpful::get($this->content_type)->serialize($payload); }
/** * Parse the response into a clean data structure * (most often an associative array) based on the expected * Mime type. * * @param string $body Http response body * * @return mixed the response parse accordingly */ public function _parse($body) { // If the user decided to forgo the automatic // smart parsing, short circuit. if (!$this->request->auto_parse) { return $body; } // If provided, use custom parsing callback if (isset($this->request->parse_callback)) { return call_user_func($this->request->parse_callback, $body); } // Decide how to parse the body of the response in the following order // 1. If provided, use the mime type specifically set as part of the `Request` // 2. If a MimeHandler is registered for the content type, use it // 3. If provided, use the "parent type" of the mime type from the response // 4. Default to the content-type provided in the response $parse_with = $this->request->expected_type; if (empty($this->request->expected_type)) { $parse_with = Httpful::hasParserRegistered($this->content_type) ? $this->content_type : $this->parent_type; } return Httpful::get($parse_with)->parse($body); }
public function testOverrideXmlHandler() { // Lazy test... $prev = \Httpful\Httpful::get(\Httpful\Mime::XML); $this->assertEquals($prev, new \Httpful\Handlers\XmlHandler()); $conf = array('namespace' => 'http://example.com'); \Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf)); $new = \Httpful\Httpful::get(\Httpful\Mime::XML); $this->assertNotEquals($prev, $new); }
/** * 将json对象解析结构改为数组 */ protected static function setJsonDecodeAsArray() { Httpful::get(Mime::JSON)->init(array('decode_as_array', true)); }