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

MailableFactory   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 50
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getInstance() 0 14 2
A getArguments() 0 15 1
A setRecipient() 0 8 1
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