|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Charcoal\Email; |
|
4
|
|
|
|
|
5
|
|
|
// From `PHP` |
|
6
|
|
|
use \InvalidArgumentException; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* For objects that are or interact with emails. |
|
10
|
|
|
*/ |
|
11
|
|
|
trait EmailAwareTrait |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* Convert an email address (RFC822) into a proper array notation. |
|
15
|
|
|
* |
|
16
|
|
|
* @param mixed $var An email array (containing an "email" key and optionally a "name" key). |
|
17
|
|
|
* @throws InvalidArgumentException If the email is invalid. |
|
18
|
|
|
* @return string |
|
19
|
|
|
*/ |
|
20
|
|
|
protected function emailToArray($var) |
|
21
|
|
|
{ |
|
22
|
|
|
if ($var === null) { |
|
23
|
|
|
return null; |
|
24
|
|
|
} |
|
25
|
|
|
if (!is_string($var) && !is_array($var)) { |
|
26
|
|
|
throw new InvalidArgumentException( |
|
27
|
|
|
sprintf('Email address must be an array or a string. (%s given)', gettype($var)) |
|
28
|
|
|
); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
// Assuming nobody's gonna set an email that is just a display name |
|
32
|
|
|
if (is_string($var)) { |
|
33
|
|
|
$regexp = '/([\w\s\'\"]+[\s]+)?(<)?(([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4}))?(>)?/'; |
|
34
|
|
|
preg_match($regexp, $var, $out); |
|
35
|
|
|
$arr = [ |
|
36
|
|
|
'email' => (isset($out[3]) ? trim($out[3]) : ''), |
|
37
|
|
|
'name' => (isset($out[1]) ? trim($out[1], " \t\n\r\0\x0B\"'") : '') |
|
38
|
|
|
]; |
|
39
|
|
|
} else { |
|
40
|
|
|
$arr = $var; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
if (!isset($arr['name'])) { |
|
44
|
|
|
$arr['name'] = ''; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
return $arr; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Convert an email address array to a RFC-822 string notation. |
|
52
|
|
|
* |
|
53
|
|
|
* @param array $arr An email array (containing an "email" key and optionally a "name" key). |
|
54
|
|
|
* @throws InvalidArgumentException If the email array is invalid. |
|
55
|
|
|
* @return string |
|
56
|
|
|
*/ |
|
57
|
|
|
protected function emailFromArray(array $arr) |
|
58
|
|
|
{ |
|
59
|
|
|
if (!isset($arr['email'])) { |
|
60
|
|
|
throw new InvalidArgumentException( |
|
61
|
|
|
'The array must contain at least the "email" key.' |
|
62
|
|
|
); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
$email = filter_var($arr['email'], FILTER_SANITIZE_EMAIL); |
|
66
|
|
|
if (!isset($arr['name'])) { |
|
67
|
|
|
return $email; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
$name = str_replace('"', '', filter_var($arr['name'], FILTER_SANITIZE_STRING)); |
|
71
|
|
|
return sprintf('"%s" <%s>', $name, $email); |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|