Completed
Push — master ( a73d41...46f3eb )
by Mathieu
06:08 queued 33s
created

EmailAwareTrait::getParser()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Charcoal\Email;
6
7
use InvalidArgumentException;
8
9
use Charcoal\Email\Services\Parser;
10
11
/**
12
 * For objects that are or interact with emails.
13
 */
14
trait EmailAwareTrait
15
{
16
    /**
17
     * @var Parser
18
     */
19
    private $parser;
20
21
    /**
22
     * @param Parser $parser Email parser service.
23
     * @return void
24
     */
25
    protected function setParser(Parser $parser): void
26
    {
27
        $this->parser = $parser;
28
    }
29
30
    /**
31
     * @return Parser
32
     */
33
    protected function getParser(): Parser
34
    {
35
        if ($this->parser === null) {
36
            $this->parser = new Parser();
37
        }
38
        return $this->parser;
39
    }
40
41
    /**
42
     * @param mixed $email An email value (either a string or an array).
43
     * @throws InvalidArgumentException If the email is invalid.
44
     * @return string
45
     */
46
    protected function parseEmail($email): string
47
    {
48
        return $this->getParser()->parse($email);
49
    }
50
51
    /**
52
     * Convert an email address (RFC822) into a proper array notation.
53
     *
54
     * @param  mixed $var An email array (containing an "email" key and optionally a "name" key).
55
     * @throws InvalidArgumentException If the email is invalid.
56
     * @return array|null
57
     */
58
    protected function emailToArray($var) : ?array
59
    {
60
        return $this->getParser()->emailToArray($var);
61
    }
62
63
    /**
64
     * Convert an email address array to a RFC-822 string notation.
65
     *
66
     * @param  array $arr An email array (containing an "email" key and optionally a "name" key).
67
     * @throws InvalidArgumentException If the email array is invalid.
68
     * @return string
69
     */
70
    protected function emailFromArray(array $arr) : string
71
    {
72
        return $this->getParser()->emailFromArray($arr);
73
    }
74
}
75