A String Is Not an Email
When a method takes string $email, the type tells you nothing. Any string fits the signature, so each method that receives one has to re-check whether it is a valid address. The check gets copied into subscribe(), send(), invite() and import(), and the day one of them skips it, a malformed address reaches your mail queue.
Don't do this:
PHP
<?php
declare(strict_types=1);
namespace App\Notifications;
use InvalidArgumentException;
final class SubscriberService
{
public function subscribe(string $email): void
{
if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Invalid email');
}
// ... and the same check again in send(), invite(), import()
}
}Do this instead:
PHP
<?php
declare(strict_types=1);
namespace App\Notifications;
use InvalidArgumentException;
final readonly class Email
{
public function __construct(public string $value)
{
if (! filter_var($value, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException("Invalid email: {$value}");
}
}
}
final class SubscriberService
{
public function subscribe(Email $email): void
{
// no filter_var() here: an Email is already valid
// ...
}
}subscribe(Email $email) cannot be called with an invalid address, because an Email cannot be constructed from one. The check lives in one constructor instead of each method, and holding an Email is proof the value already passed it. The check covers only what FILTER_VALIDATE_EMAIL accepts, so a rule such as "no disposable domains" goes in the same constructor.