|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Genkgo\Mail\Header; |
|
5
|
|
|
|
|
6
|
|
|
use Genkgo\Mail\Stream\OptimalTransferEncodedPhraseStream; |
|
7
|
|
|
use Genkgo\Mail\Stream\OptimalTransferEncodedTextStream; |
|
8
|
|
|
|
|
9
|
|
|
final class OptimalEncodedHeaderValue |
|
10
|
|
|
{ |
|
11
|
|
|
public const FOLDING = "\r\n "; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* @var string |
|
15
|
|
|
*/ |
|
16
|
|
|
private $encoded; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @var string |
|
20
|
|
|
*/ |
|
21
|
|
|
private $encoding = '7bit'; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @param string $value |
|
25
|
|
|
* @param bool $phrase |
|
26
|
|
|
*/ |
|
27
|
150 |
|
public function __construct(string $value, bool $phrase = false) |
|
28
|
|
|
{ |
|
29
|
150 |
|
if ($phrase === true) { |
|
30
|
51 |
|
$encoded = new OptimalTransferEncodedPhraseStream($value, 68, self::FOLDING); |
|
31
|
|
|
|
|
32
|
51 |
|
$this->encoding = $encoded->getMetadata(['transfer-encoding'])['transfer-encoding']; |
|
33
|
|
|
} else { |
|
34
|
123 |
|
$encoded = new OptimalTransferEncodedTextStream($value, 68, self::FOLDING); |
|
35
|
|
|
|
|
36
|
123 |
|
$this->encoding = $encoded->getMetadata(['transfer-encoding'])['transfer-encoding']; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
150 |
|
switch ($this->encoding) { |
|
40
|
150 |
|
case '7bit': |
|
41
|
12 |
|
case '8bit': |
|
42
|
141 |
|
$this->encoded = (string) $encoded; |
|
43
|
141 |
|
break; |
|
44
|
12 |
|
case 'base64': |
|
45
|
8 |
|
$this->encoded = \sprintf('=?%s?B?%s?=', 'UTF-8', (string) $encoded); |
|
46
|
8 |
|
break; |
|
47
|
4 |
|
case 'quoted-printable': |
|
48
|
4 |
|
$this->encoded = \str_replace( |
|
49
|
4 |
|
'=' . self::FOLDING, |
|
50
|
4 |
|
'?=' . self::FOLDING . '=?UTF-8?Q?', |
|
51
|
4 |
|
\sprintf( |
|
52
|
4 |
|
'=?%s?Q?%s?=', |
|
53
|
4 |
|
'UTF-8', |
|
54
|
4 |
|
\preg_replace( |
|
55
|
4 |
|
['/\?/', '/_/', '/(?<!^) /m'], |
|
56
|
4 |
|
['=3F', '=5F', '_'], |
|
57
|
4 |
|
(string) $encoded |
|
58
|
|
|
) |
|
59
|
|
|
) |
|
60
|
|
|
); |
|
61
|
4 |
|
break; |
|
62
|
|
|
default: |
|
63
|
|
|
throw new \UnexpectedValueException('Unknown encoding ' . $this->encoding); |
|
64
|
|
|
} |
|
65
|
150 |
|
} |
|
66
|
|
|
|
|
67
|
|
|
/** |
|
68
|
|
|
* @return string |
|
69
|
|
|
*/ |
|
70
|
150 |
|
public function __toString(): string |
|
71
|
|
|
{ |
|
72
|
150 |
|
return $this->encoded; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
/** |
|
76
|
|
|
* @return string |
|
77
|
|
|
*/ |
|
78
|
41 |
|
public function getEncoding(): string |
|
79
|
|
|
{ |
|
80
|
41 |
|
return $this->encoding; |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
/** |
|
84
|
|
|
* @param string $value |
|
85
|
|
|
* @return OptimalEncodedHeaderValue |
|
86
|
|
|
*/ |
|
87
|
51 |
|
public static function forPhrase(string $value): self |
|
88
|
|
|
{ |
|
89
|
51 |
|
return new self($value, true); |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
|