ResourceAttachmentParser::parse()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 9
nc 3
nop 2
1
<?php
2
declare(strict_types=1);
3
4
namespace AcMailer\Attachment\Parser;
5
6
use AcMailer\Attachment\Helper\AttachmentHelperTrait;
7
use AcMailer\Exception\InvalidAttachmentException;
8
use Zend\Mime;
9
use Zend\Mime\Exception\InvalidArgumentException;
10
11
class ResourceAttachmentParser implements AttachmentParserInterface
12
{
13
    use AttachmentHelperTrait;
14
15
    /**
16
     * @param string|resource|array|Mime\Part $attachment
17
     * @param string|null $attachmentName
18
     * @return Mime\Part
19
     * @throws InvalidArgumentException
20
     * @throws InvalidAttachmentException
21
     */
22
    public function parse($attachment, string $attachmentName = null): Mime\Part
23
    {
24
        if (! \is_resource($attachment)) {
25
            throw InvalidAttachmentException::fromExpectedType('resource');
26
        }
27
28
        $resourceData = \stream_get_meta_data($attachment);
29
        $name = $attachmentName ?? (isset($resourceData['uri']) ? \basename($resourceData['uri']) : null);
30
        $part = new Mime\Part($attachment);
31
32
        // Make sure encoding and disposition have a default value
33
        $part->encoding = Mime\Mime::ENCODING_BASE64;
34
        $part->disposition = Mime\Mime::DISPOSITION_ATTACHMENT;
35
36
        return $this->applyNameToPart($part, $name);
37
    }
38
}
39