FilePathAttachmentParser::parse()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 9
nc 2
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 FilePathAttachmentParser implements AttachmentParserInterface
12
{
13
    use AttachmentHelperTrait;
14
15
    /**
16
     * @var \finfo
17
     */
18
    private $finfo;
19
20
    public function __construct(\finfo $finfo = null)
21
    {
22
        $this->finfo = $finfo ?: new \finfo(\FILEINFO_MIME_TYPE);
23
    }
24
25
    /**
26
     * @param string|resource|array|Mime\Part $attachment
27
     * @param string|null $attachmentName
28
     * @return Mime\Part
29
     * @throws InvalidArgumentException
30
     * @throws InvalidAttachmentException
31
     */
32
    public function parse($attachment, string $attachmentName = null): Mime\Part
33
    {
34
        if (! \is_string($attachment) || ! \is_file($attachment)) {
35
            throw InvalidAttachmentException::fromExpectedType('file path');
36
        }
37
38
        $part = new Mime\Part(\fopen($attachment, 'r+b'));
39
        $part->type = $this->finfo->file($attachment);
40
41
        // Make sure encoding and disposition have a default value
42
        $part->encoding = Mime\Mime::ENCODING_BASE64;
43
        $part->disposition = Mime\Mime::DISPOSITION_ATTACHMENT;
44
45
        // If the attachment name is not defined, use the attachment's \basename
46
        $name = $attachmentName ?? \basename($attachment);
47
        return $this->applyNameToPart($part, $name);
48
    }
49
}
50