Locker\Helpers\Attachments::setAttachments PHP Method

setAttachments() static public method

Get statements and attachments from submitted content
static public setAttachments ( $content_type, $content ) : array
$content_type
$content
return array
    static function setAttachments($content_type, $content)
    {
        $return = ['body' => '', 'attachments' => []];
        $sha_hashes = [];
        $boundary = static::getBoundary($content_type);
        // Fetch each part of the multipart document
        $parts = array_slice(explode($boundary, $content), 1);
        $raw_headers = $body = '';
        foreach ($parts as $count => $part) {
            // Stops at the end of the file.
            if (substr($part, 0, 2) == "--") {
                break;
            }
            // Determines the delimiter.
            $delim = strpos($part, "\r\n") !== false ? "\r\n" : "\n";
            $delim = strpos($part, $delim . $delim) === false ? "\n" : $delim;
            // Separate body contents from headers
            $part = ltrim($part, $delim);
            list($raw_headers, $body) = explode($delim . $delim, $part, 2);
            $headers = static::getHeaders($raw_headers, $delim);
            if ($count == 0) {
                if (!isset($headers['content-type']) || $headers['content-type'] !== 'application/json') {
                    throw new Exceptions\Exception('Statements must make up the first part of the body.');
                }
                $return['body'] = $body;
            } else {
                static::validateHeaders($headers, $sha_hashes);
                $return['attachments'][$count] = (object) ['hash' => $headers['x-experience-api-hash'], 'content_type' => $headers['content-type'], 'content' => $body];
            }
        }
        return $return;
    }

Usage Example

 /**
  * Deals with multipart requests.
  * @return ['content' => $content, 'attachments' => $attachments].
  */
 private function getParts()
 {
     $content = \LockerRequest::getContent();
     $contentType = \LockerRequest::header('Content-Type');
     $types = explode(';', $contentType, 2);
     $mimeType = count($types) >= 1 ? $types[0] : $types;
     if ($mimeType == 'multipart/mixed') {
         $components = Attachments::setAttachments($contentType, $content);
         // Returns 'formatting' error.
         if (empty($components)) {
             throw new Exceptions\Exception('There is a problem with the formatting of your submitted content.');
         }
         // Returns 'no attachment' error.
         if (!isset($components['attachments'])) {
             throw new Exceptions\Exception('There were no attachments.');
         }
         $content = $components['body'];
         $attachments = $components['attachments'];
     } else {
         $attachments = [];
     }
     return ['content' => $content, 'attachments' => $attachments];
 }