Repository navigation
Expand file tree
/
Copy pathAttachment.php
More file actions
92 lines (73 loc) · 1.88 KB
/
Copy pathAttachment.php
File metadata and controls
92 lines (73 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
declare(strict_types=1);
namespace Igloonet\MailkitApi\DataObjects;
use Igloonet\MailkitApi\Exceptions\Message\AttachmentEmptyContentException;
use Igloonet\MailkitApi\Exceptions\Message\AttachmentFileNotFoundException;
use Igloonet\MailkitApi\Exceptions\Message\AttachmentFileNotReadableException;
final class Attachment
{
/** @var string */
private $name = null;
/** @var string */
private $filePath = null;
/** @var string */
private $content = null;
public function __construct(string $name)
{
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
/**
* @return string
*/
public function getContent(): string
{
if ($this->content !== null) {
return $this->content;
}
if ($this->filePath !== null) {
$resolvedPath = realpath($this->filePath);
if ($resolvedPath === false || !is_file($resolvedPath)) {
throw new AttachmentFileNotFoundException($this->filePath);
}
if (!is_readable($resolvedPath)) {
throw new AttachmentFileNotReadableException($this->filePath);
}
$fileContent = file_get_contents($resolvedPath);
if ($fileContent !== false) {
return $fileContent;
}
}
throw new AttachmentEmptyContentException(
sprintf('Content of attachment %s can not be empty!', $this->name)
);
}
/**
* @param string $filePath
* @param string|null $name
* @return Attachment
*/
public static function fromFile(string $filePath, ?string $name = null): self
{
if (trim($name ?? '') === '') {
$name = pathinfo($filePath, PATHINFO_BASENAME);
}
$attachment = new static($name);
$attachment->filePath = $filePath;
return $attachment;
}
/**
* @param string $content
* @param string $name
* @return Attachment
*/
public static function fromString(string $content, string $name): self
{
$attachment = new static($name);
$attachment->content = $content;
return $attachment;
}
}