|
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
|
|
|
|