Completed
Branch master (7dba2f)
by Alejandro
06:12
created

EmailBuilder::buildOptions()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
c 0
b 0
f 0
rs 8.6845
cc 4
eloc 13
nc 4
nop 3
1
<?php
2
declare(strict_types=1);
3
4
namespace AcMailer\Model;
5
6
use AcMailer\Exception;
7
use Zend\Stdlib\ArrayUtils;
8
9
class EmailBuilder implements EmailBuilderInterface
10
{
11
    /**
12
     * @var array
13
     */
14
    private $emailsConfig;
15
16
    public function __construct(array $emailsConfig)
17
    {
18
        $this->emailsConfig = $emailsConfig;
19
        // Always make the identifier Email be valid, in order to build any kind of anonymous email
20
        $this->emailsConfig[Email::class] = [];
21
    }
22
23
    /**
24
     * @param string $name
25
     * @param array $options
26
     * @return Email
27
     * @throws Exception\EmailNotFoundException
28
     * @throws Exception\InvalidArgumentException
29
     */
30
    public function build(string $name, array $options = []): Email
31
    {
32
        return new Email($this->buildOptions($name, $options));
33
    }
34
35
    private function buildOptions(string $name, array $options, array &$alreadyExtendedEmails = []): array
36
    {
37
        if (! isset($this->emailsConfig[$name])) {
38
            throw Exception\EmailNotFoundException::fromName($name);
39
        }
40
41
        // Recursively extend emails
42
        $options = ArrayUtils::merge($this->emailsConfig[$name], $options);
43
        if (! isset($options['extends'])) {
44
            return $options;
45
        }
46
47
        // Get the email from which to extend, and ensure it has not been processed yet, to prevent an infinite loop
48
        $emailToExtend = $options['extends'];
49
        if (\in_array($emailToExtend, $alreadyExtendedEmails, true)) {
50
            throw new Exception\InvalidArgumentException(
51
                'It wasn\'t possible to create an email due to circular inheritance. Review "extends".'
52
            );
53
        }
54
        $alreadyExtendedEmails[] = $emailToExtend;
55
        unset($options['extends']);
56
57
        return ArrayUtils::merge($this->buildOptions($emailToExtend, [], $alreadyExtendedEmails), $options);
58
    }
59
}
60