/** * Parses multipart response body as an array of ApiResponse objects * @return ApiResponse[] * @throws Exception */ public function multipart() { if (empty($this->_multiparts)) { $this->_multiparts = array(); if (!$this->isContentType('multipart/mixed')) { throw new Exception('Response is not multipart'); } // Step 1. Get boundary preg_match('/boundary=([^";]+)/i', $this->getContentType(), $matches); if (empty($matches[1])) { throw new Exception('Boundary not found'); } $boundary = $matches[1]; // Step 2. Split by boundary and remove first and last parts if needed $parts = explode('--' . $boundary . '', $this->text()); //TODO Handle as stream if (empty($parts[0])) { array_shift($parts); } if (trim($parts[count($parts) - 1]) == '--') { array_pop($parts); } if (count($parts) == 0) { throw new Exception('No parts found'); } // Step 3. Create status info object $statusInfoPart = array_shift($parts); $statusInfoObj = new self(null, self::createResponse(trim($statusInfoPart), $this->response()->getStatusCode())); $statusInfo = $statusInfoObj->json()->response; // Step 4. Parse all parts into Response objects foreach ($parts as $i => $part) { $partInfo = $statusInfo[$i]; $this->_multiparts[] = new self(null, self::createResponse(trim($part), $partInfo->status)); } } return $this->_multiparts; }