Completed
Push — master ( 74377e...8a54fd )
by Freek
01:59
created

MailableFactory::setRecipient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 2
1
<?php
2
3
namespace Spatie\MailableTest;
4
5
use Exception;
6
use ReflectionClass;
7
use ReflectionParameter;
8
use Illuminate\Mail\Mailable;
9
10
class MailableFactory
11
{
12
    /**  @var \Spatie\MailableTest\ArgumentValueProvider */
13
    protected $argumentValueProvider;
14
15
    public function __construct(ArgumentValueProvider $argumentValueProvider)
16
    {
17
        $this->argumentValueProvider = $argumentValueProvider;
18
    }
19
20
    public function getInstance(string $mailableClass, string $toEmail): Mailable
21
    {
22
        if (! class_exists($mailableClass)) {
23
            throw new Exception("Mailable `{$mailableClass}` does not exist.");
24
        }
25
26
        $argumentValues = $this->getArguments($mailableClass);
27
28
        $mailableInstance =  new $mailableClass(...$argumentValues);
29
30
        $mailableInstance = $this->setRecipient($mailableInstance, $toEmail);
31
32
        return $mailableInstance;
33
    }
34
35
    public function getArguments(string $mailableClass)
36
    {
37
        $parameters = (new ReflectionClass($mailableClass))
38
            ->getConstructor()
39
            ->getParameters();
40
41
        return collect($parameters)
42
            ->map(function (ReflectionParameter $reflectionParameter) {
43
44
                return $this->argumentValueProvider->getValue(
45
                    $reflectionParameter->getName(),
46
                    $reflectionParameter->getType()->getName()
47
                );
48
            });
49
    }
50
51
    protected function setRecipient(Mailable $mailableInstance, string $toEmail): Mailable
52
    {
53
        $mailableInstance->to($toEmail);
54
        $mailableInstance->cc([]);
55
        $mailableInstance->bcc([]);
56
57
        return $mailableInstance;
58
    }
59
}
60