1: <?php
2:
3: namespace Charcoal\Email;
4:
5:
6: use \InvalidArgumentException;
7:
8: 9: 10:
11: trait EmailAwareTrait
12: {
13: 14: 15: 16: 17: 18: 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:
32: if (is_string($var)) {
33: $regexp = '/([\w\s\'\"-_]+[\s]+)?(<)?(([\w-\._]+)@((?:[\w-_]+\.)+)([a-zA-Z]{2,4}))?(>)?/u';
34: preg_match($regexp, $var, $out);
35: $arr = [
36: 'email' => (isset($out[3]) ? trim($out[3]) : ''),
37: 'name' => (isset($out[1]) ? trim(trim($out[1]), '\'"') : '')
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: 52: 53: 54: 55: 56:
57: protected function emailFromArray(array $arr)
58: {
59: if (isset($arr['address'])) {
60: $arr['email'] = $arr['address'];
61: unset($arr['address']);
62: }
63:
64: if (!isset($arr['email'])) {
65: throw new InvalidArgumentException(
66: 'The array must contain at least the "address" key.'
67: );
68: }
69:
70: $email = filter_var($arr['email'], FILTER_SANITIZE_EMAIL);
71:
72: if (!isset($arr['name'])) {
73: return $email;
74: }
75:
76: $name = str_replace('"', '', filter_var($arr['name'], FILTER_SANITIZE_STRING));
77: return sprintf('"%s" <%s>', $name, $email);
78: }
79: }
80: