for testing and deploying your application
for finding and fixing issues
for empowering human code reviews
<?php
namespace Spatie\MailableTest;
use Exception;
use ReflectionClass;
use ReflectionParameter;
use Illuminate\Contracts\Mail\Mailable;
use Illuminate\Database\Eloquent\Model;
class MailableFactory
{
/** @var \Spatie\MailableTest\ArgumentValueProvider */
protected $argumentValueProvider;
public function __construct(ArgumentValueProvider $argumentValueProvider)
$this->argumentValueProvider = $argumentValueProvider;
}
public function getInstance(string $mailableClass): Mailable
if (! class_exists($mailableClass)) {
throw new Exception("Mailable `{$mailableClass}` does not exist.");
$argumentValues = $this->getArguments($mailableClass);
return new $this->mailableClass(...$argumentValues);
mailableClass
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;
public function getArguments(string $mailableClass)
$parameters = (new ReflectionClass($mailableClass))
->getConstructor()
->getParameters();
return collect($parameters)
->map(function (ReflectionParameter $reflectionParameter) {
return $this->argumentValueProvider->getValue(
$reflectionParameter->getName(),
$reflectionParameter->getType()->getName()
);
});
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: