Completed
Push — master ( 4ab497...db9007 )
by Freek
01:47
created

MailableFactory::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Spatie\MailableTest;
4
5
use Exception;
6
use ReflectionClass;
7
use ReflectionParameter;
8
use Illuminate\Contracts\Mail\Mailable;
9
use Illuminate\Database\Eloquent\Model;
10
11
class MailableFactory
12
{
13
    /**  @var \Spatie\MailableTest\ArgumentValueProvider */
14
    protected $argumentValueProvider;
15
16
    public function __construct(ArgumentValueProvider $argumentValueProvider)
17
    {
18
        $this->argumentValueProvider = $argumentValueProvider;
19
    }
20
21
    public function getInstance(string $mailableClass): Mailable
22
    {
23
        if (! class_exists($mailableClass)) {
24
            throw new Exception("Mailable `{$mailableClass}` does not exist.");
25
        }
26
27
        $argumentValues = $this->getArguments($mailableClass);
28
29
        return new $this->mailableClass(...$argumentValues);
0 ignored issues
show
Bug introduced by
The property mailableClass does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
30
    }
31
32
    public function getArguments(string $mailableClass)
33
    {
34
        $parameters = (new ReflectionClass($mailableClass))
35
            ->getConstructor()
36
            ->getParameters();
37
38
        return collect($parameters)
39
            ->map(function (ReflectionParameter $reflectionParameter) {
40
41
                return $this->argumentValueProvider->getValue(
42
                    $reflectionParameter->getName(),
43
                    $reflectionParameter->getType()->getName()
44
                );
45
            });
46
    }
47
}
48