Your current implementation for masking email addresses seems well thought out and should work for the scenarios you've described. However, let's review it and ensure there are no potential issues or improvements that can be made.
Code Review and Suggestions
-
Stringable Usage: You're using the
Stringableclass effectively to chain methods, which is great for readability and maintainability. -
Masking Logic: The logic for masking the local part (before the
@) and the domain part (after the@) is clear and should work as expected. You handle different lengths of the local part well. -
Edge Cases: Consider edge cases such as:
- Emails with very short local parts or domain names.
- Emails with subdomains (e.g.,
[email protected]).
-
Error Handling: Ensure that the input is a valid email address before processing. You might want to add a simple validation step to check if the input is a valid email format.
-
Performance: The current implementation should perform well for typical use cases. However, if you expect to process a large number of emails, consider profiling the performance.
Here's a slightly refined version of your mixin with added validation:
class MaskEmailMixin
{
public function maskEmail(): callable
{
return function (string $email): Stringable {
// Basic email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException("Invalid email address.");
}
return Str::of($email)
->before('@')
// Mask the handle:
->when(
fn (Stringable $str): bool => $str->length() >= 5,
fn (Stringable $str): Stringable => $str->mask('*', 2, -2),
fn (Stringable $str): Stringable => $str->when(
fn (Stringable $str): bool => $str->length() >= 2,
fn (Stringable $str): Stringable => $str->mask('*', 1),
fn (Stringable $str): Stringable => $str->mask('*', 0),
),
)
->append('@')
// Mask the host name
->append(
Str::of(Str::after($email, '@'))
->beforeLast('.')
->mask('*', 2)
)
->append('.')
->append(Str::afterLast($email, '.'));
};
}
}
Additional Considerations
- Testing: Make sure to test your function with a variety of email formats, including edge cases like very short emails, emails with subdomains, and internationalized domain names.
- Security: While masking helps obscure the email, ensure that any logging or error messages do not inadvertently expose sensitive information.
This should give you a robust solution for masking emails in your application.