|
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
|
|
|
use Zend\Stdlib\ArrayUtils; |
|
11
|
|
|
|
|
12
|
|
|
class ArrayAttachmentParser implements AttachmentParserInterface |
|
13
|
|
|
{ |
|
14
|
|
|
use AttachmentHelperTrait; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @param string|resource|array|Mime\Part $attachment |
|
18
|
|
|
* @param string|null $attachmentName |
|
19
|
|
|
* @return Mime\Part |
|
20
|
|
|
* @throws InvalidArgumentException |
|
21
|
|
|
* @throws InvalidAttachmentException |
|
22
|
|
|
*/ |
|
23
|
|
|
public function parse($attachment, string $attachmentName = null): Mime\Part |
|
24
|
|
|
{ |
|
25
|
|
|
if (! \is_array($attachment)) { |
|
26
|
|
|
throw InvalidAttachmentException::fromExpectedType('array'); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
// Set default values for certain properties in the Mime\Part object |
|
30
|
|
|
$attachment = ArrayUtils::merge([ |
|
31
|
|
|
'encoding' => Mime\Mime::ENCODING_BASE64, |
|
32
|
|
|
'disposition' => Mime\Mime::DISPOSITION_ATTACHMENT, |
|
33
|
|
|
], $attachment); |
|
34
|
|
|
|
|
35
|
|
|
// Map a Mime\Part object with the array properties |
|
36
|
|
|
$part = new Mime\Part(); |
|
37
|
|
|
foreach ($attachment as $property => $value) { |
|
38
|
|
|
$method = $this->buildSetter($property); |
|
39
|
|
|
if (\method_exists($part, $method)) { |
|
40
|
|
|
$part->{$method}($value); |
|
41
|
|
|
} |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
return $this->applyNameToPart($part, $attachmentName); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
private function buildSetter(string $property): string |
|
48
|
|
|
{ |
|
49
|
|
|
return 'set' . str_replace('_', ' ', $property); |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|