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

MailableFactory::getArgumentValue()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.6737
c 0
b 0
f 0
cc 5
eloc 11
nc 5
nop 2
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