rafalmasiarek / contact-form
Lightweight, pluggable contact form service with hooks, validators and PSR-7-friendly helpers.
Requires
- php: ^8.0
- psr/http-message: ^1.1 || ^2.0
Requires (Dev)
None
Suggests
- monolog/monolog: ^3.0
- phpmailer/phpmailer: ^6.9
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-17 23:37:22 UTC
README
Lightweight, framework-agnostic contact form service for PHP. It gives you a tiny, pluggable pipeline (hooks + validators), a simple DTO for requests, and transport-agnostic email sending (PHPMailer SMTP or native mail()), with example wiring for MailHog. Works with Composer or a standalone autoloader.
Namespace:
rafalmasiarek\ContactForm(PSR‑4 autoload). PHP: ^8.0
License
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files, to deal in the Software
without restriction.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
Source: https://opensource.org/licenses/MIT
See LICENSE for full details.
Authors
Highlights
- Small & decoupled: no hard HTTP coupling; returns a simple array you can turn into any response.
- Pluggable pipeline: run validators (as callables) and hooks (before/after validation, after send, on failure).
- Clean data model: ContactData DTO + OutboundEmail builder.
- Transports: PHPMailer adapter (SMTP) or native mail() sender.
- i18n-friendly messages: resolve human texts via codes with ArrayMessageResolver.
- PSR-7 friendly: easy to slot into Slim, Laminas, etc.
- IP/UA resolution: built-in
DefaultIpResolverfor raw PHP; inject your ownIpResolverInterfacebehind a proxy. - Batteries included examples: demo app with MailHog Docker, simple math CAPTCHA (hook + validator), required fields + email validators, IP annotation hook.
Namespace:
rafalmasiarek\ContactForm(PSR‑4 autoload).
PHP: ^8.0
Installation
composer require rafalmasiarek/contact-form
# or use a local path repo during development
If you use the PHPMailer adapter:
composer require phpmailer/phpmailer:^6.9
Quickstart
git clone https://github.com/rafalmasiarek/php-contact-form.git php-contactform
cd php-contactform/examples
docker compose up -d
# open http://localhost:8080
Using with composer
The repo ships a PSR-4 style autoload.php. Point it at src/ (and optional lib/ folders for hooks/validators) and require it in your front controller.
require __DIR__ . '/../autoload.php'; // or examples/lib/contactform/autoload.php
Example wiring (simplified)
$cfg = require __DIR__ . '/../config.php'; $resolver = new ArrayMessageResolver([ 'OK_SENT' => ['message' => 'Message sent', 'http' => 200], 'ERR_VALIDATION' => ['message' => 'Validation error', 'http' => 422], 'ERR_SEND_FAILED' => ['message' => 'Message could not be sent.', 'http' => 500], ]); // optional: register default messages for custom validators ContactForm\Validators\MathCaptchaValidator::registerDefaultMessages($resolver); $service = (new ContactFormService()) ->setMessageResolver($resolver) ->setHooks([ new ContactForm\Hook\AnnotateIpHook(), new ContactForm\Hook\MathCaptchaHook( field: $cfg['captcha']['field'], metaKey: $cfg['captcha']['meta_key'] ), ]) ->setValidators([ 'required' => ContactForm\Validators\FieldsValidator::required(['name','email','message']), 'email' => ContactForm\Validators\FieldsValidator::email('email', 'strict'), 'captcha' => ContactForm\Validators\MathCaptchaValidator::validate( field: $cfg['captcha']['field'], sessionKey: $cfg['captcha']['session_key'], oneShot: (bool)$cfg['captcha']['one_shot'] ), ]); // Pick a sender: PHPMailer if available, otherwise native mail() $sender = class_exists(\PHPMailer\PHPMailer\PHPMailer::class) ? new \rafalmasiarek\ContactForm\Mail\PhpMailerEmailSender($cfg['smtp']) : new \rafalmasiarek\ContactForm\Mail\NativeMailSender( from: $cfg['smtp']['from'], fromName: $cfg['smtp']['from_name'], to: $cfg['smtp']['to'], replyTo: null ); $service->setEmailSender($sender); // Build data and process $data = new \rafalmasiarek\ContactForm\Model\ContactData( name: $_POST['name'] ?? '', email: $_POST['email'] ?? '', message: $_POST['message'] ?? '', subject: $_POST['subject'] ?? '', phone: $_POST['phone'] ?? '', meta: [] ); echo json_encode($service->process($data));
IP / User-Agent resolution
The service automatically resolves client IP and User-Agent as a fallback when they are not provided via withContext().
Raw PHP (no proxy) — works out of the box, DefaultIpResolver reads from $_SERVER['REMOTE_ADDR']:
$service = new ContactFormService($smtp); // DefaultIpResolver is used automatically — no config needed
Behind a proxy (Nginx, Cloudflare, load balancer) — inject your own implementation that validates trusted proxy ranges before trusting forwarded headers:
$service = (new ContactFormService($smtp)) ->withIpResolver(new MyPsr7IpResolver($request));
PSR-7 apps (Slim, Laminas) — pass the already-resolved IP via withContext(); this always takes priority over the resolver:
$service = (new ContactFormService($smtp)) ->withContext([ 'client' => [ 'ip' => $request->getAttribute('client_ip'), 'ua' => $request->getHeaderLine('User-Agent'), ], ]);
IpResolverInterface lives in Contracts/; DefaultIpResolver in Support/.
PSR‑7 / Middlewares
Add a middleware in your app that resolves the real client IP and pass it via withContext().
Hooks
Implement ContactFormHook with any of these optional methods:
onBeforeValidate(ContactDataHook $dto)onAfterValidate(ContactDataHook $dto, string $validatorLabel)onBeforeSend(ContactDataHook $dto)onAfterSend(ContactDataHook $dto, string $transportMessageId)
All hook errors are swallowed by default to protect the main flow.
Use EmailSenderInterface abstraction; provided adapters:
PhpMailerEmailSenderInterface(depends onphpmailer/phpmailer)
OutboundEmail encapsulates the rendered message.
Messages
MessageResolverInterface decouples symbolic codes from UI strings.
ArrayMessageResolver is a simple in‑memory map with optional HTTP codes.
Validation
Any callable validator is accepted. Library provides helper DTO ContactDataValidator to keep the code tidy.
Versioning & BC
- Namespace is stable:
rafalmasiarek\ContactForm. - All classes are PSR‑4 autoloaded from
/src. DefaultContactTemplatemoved fromCore\toSupport\— update yourusestatements if you reference it directly.
Index
Classes
Codes—rafalmasiarek\ContactForm\CoreContactDataHook—rafalmasiarek\ContactForm\CoreContactFormService—rafalmasiarek\ContactForm\CoreValidationException—rafalmasiarek\ContactForm\CoreNativeMailSender—rafalmasiarek\ContactForm\MailPhpMailerEmailSender—rafalmasiarek\ContactForm\MailPhpMailerTransportException—rafalmasiarek\ContactForm\MailContactData—rafalmasiarek\ContactForm\ModelOutboundEmail—rafalmasiarek\ContactForm\ModelArrayMessageResolver—rafalmasiarek\ContactForm\SupportContactDataValidator—rafalmasiarek\ContactForm\SupportDefaultContactTemplate—rafalmasiarek\ContactForm\SupportDefaultIpResolver—rafalmasiarek\ContactForm\SupportNullLogger—rafalmasiarek\ContactForm\Support
Interfaces
AttemptLoggerInterface—rafalmasiarek\ContactForm\ContractsContactFormHookInterface—rafalmasiarek\ContactForm\ContractsEmailSenderInterface—rafalmasiarek\ContactForm\ContractsEmailTemplateInterface—rafalmasiarek\ContactForm\ContractsErrorCodeProviderInterface—rafalmasiarek\ContactForm\ContractsIpResolverInterface—rafalmasiarek\ContactForm\ContractsMessageResolverInterface—rafalmasiarek\ContactForm\Contracts
AttemptLoggerInterface
interface — rafalmasiarek\ContactForm\Contracts\AttemptLoggerInterface · source
Minimal logging contract used by the service. You can adapt a PSR-3 logger by implementing this interface.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
info() |
public | void |
Log an informational message. |
warning() |
public | void |
Log a warning message. |
error() |
public | void |
Log an error message. |
info()
AttemptLoggerInterface info()
public function info(string $message, array $context): void
Log an informational message.
| Param | Type | Description |
|---|---|---|
$message |
string |
— |
$context |
array<string, mixed> |
— |
warning()
AttemptLoggerInterface warning()
public function warning(string $message, array $context): void
Log a warning message.
| Param | Type | Description |
|---|---|---|
$message |
string |
— |
$context |
array<string, mixed> |
— |
error()
AttemptLoggerInterface error()
public function error(string $message, array $context): void
Log an error message.
| Param | Type | Description |
|---|---|---|
$message |
string |
— |
$context |
array<string, mixed> |
— |
ContactFormHookInterface
interface — rafalmasiarek\ContactForm\Contracts\ContactFormHookInterface · source
Lifecycle hooks for the contact form pipeline. Hooks receive a read-write façade ({@see ContactDataHook}) that exposes the live {@see ContactData}. Use hooks to normalize/enrich the payload, add diagnostics, or perform side effects (metrics, auditing, etc.). IMPORTANT: - Hooks may mutate data via ContactDataHook. - Validators must operate on the read-only snapshot ({@see ContactDataValidator}).
| Method | Visibility | Returns | Summary |
|---|---|---|---|
onBeforeValidate() |
public | void |
Invoked just before validators are executed. You may mutate the payload (e.g., normalize fields, enrich meta) or throw to abort. |
onAfterValidate() |
public | void |
NEW: Invoked after all validators have succeeded, but before the email is rendered and sent. This is the right place to annotate body/meta based on validator outputs (available in $validatorsMeta) without repeating the validator's work. The $validatorsMeta bag is what the service collected under: $service->meta['validators'] (per-validator namespace) Example shape: [ 'csrfValidator' => ['status'=>'ok', ...], 'emailValidator' => ['status'=>'ok', ...], 'threatScan' => ['status'=>'pass', 'summary'=>{...}], ... ] |
onAfterSend() |
public | void |
Invoked after a successful send. |
onSendFailure() |
public | void |
Invoked if the send operation fails with an exception. |
onBeforeValidate()
ContactFormHookInterface onBeforeValidate()
public function onBeforeValidate(ContactDataHook $d): void
Invoked just before validators are executed. You may mutate the payload (e.g., normalize fields, enrich meta) or throw to abort.
| Param | Type | Description |
|---|---|---|
$d |
ContactDataHook |
Read-write access to the live ContactData. |
| Throws | When |
|---|---|
\Throwable |
To abort the pipeline with a custom reason. |
onAfterValidate()
ContactFormHookInterface onAfterValidate()
public function onAfterValidate(ContactDataHook $d, array $validatorsMeta): void
NEW: Invoked after all validators have succeeded, but before the email is rendered and sent. This is the right place to annotate body/meta based on validator outputs (available in $validatorsMeta) without repeating the validator's work. The $validatorsMeta bag is what the service collected under: $service->meta['validators'] (per-validator namespace) Example shape: [ 'csrfValidator' => ['status'=>'ok', ...], 'emailValidator' => ['status'=>'ok', ...], 'threatScan' => ['status'=>'pass', 'summary'=>{...}], ... ]
| Param | Type | Description |
|---|---|---|
$d |
ContactDataHook |
Read-write access to the live ContactData. |
$validatorsMeta |
array<string, mixed> |
Aggregated meta produced by validators. |
onAfterSend()
ContactFormHookInterface onAfterSend()
public function onAfterSend(ContactDataHook $d, string $messageId): void
Invoked after a successful send.
| Param | Type | Description |
|---|---|---|
$d |
ContactDataHook |
Read-write access to the live ContactData. |
$messageId |
string |
Optional transport message id (if any). |
onSendFailure()
ContactFormHookInterface onSendFailure()
public function onSendFailure(ContactDataHook $d, \Throwable $e): void
Invoked if the send operation fails with an exception.
| Param | Type | Description |
|---|---|---|
$d |
ContactDataHook |
Read-write access to the live ContactData. |
$e |
\Throwable |
The failure exception. |
EmailSenderInterface
interface — rafalmasiarek\ContactForm\Contracts\EmailSenderInterface · source
Contract for sending outbound emails. Implementations may use any transport (SMTP, API, sendmail, etc.).
| Method | Visibility | Returns | Summary |
|---|---|---|---|
send() |
public | bool |
Send an email message. Implementations should throw on transport/config errors. |
send()
EmailSenderInterface send()
public function send(OutboundEmail $email): bool
Send an email message. Implementations should throw on transport/config errors.
| Param | Type | Description |
|---|---|---|
$email |
OutboundEmail |
The message to send. |
Returns: bool — True on success; false otherwise.
| Throws | When |
|---|---|
\Throwable |
On transport or configuration failure. |
EmailTemplateInterface
interface — rafalmasiarek\ContactForm\Contracts\EmailTemplateInterface · source
Contract for rendering email bodies from ContactData. Implementations are responsible for producing the HTML and plain-text bodies shown in outbound messages. They may freely use $d->meta to include additional context (IP, UA, referer, country, etc.) previously attached by hooks in the application layer.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
renderHtml() |
public | string |
Render the HTML body for an outbound email. |
renderText() |
public | string|null |
Render the plain-text body for an outbound email. Return null to allow the caller to auto-fallback to a text version generated from the HTML body (e.g., via strip_tags()). |
renderHtml()
EmailTemplateInterface renderHtml()
public function renderHtml(ContactData $d): string
Render the HTML body for an outbound email.
| Param | Type | Description |
|---|---|---|
$d |
ContactData |
Contact form data, including optional meta. |
Returns: string — HTML markup for the message body.
renderText()
EmailTemplateInterface renderText()
public function renderText(ContactData $d): ?string
Render the plain-text body for an outbound email. Return null to allow the caller to auto-fallback to a text version generated from the HTML body (e.g., via strip_tags()).
| Param | Type | Description |
|---|---|---|
$d |
ContactData |
Contact form data, including optional meta. |
Returns: string\|null — Text body or null to let caller fallback.
ErrorCodeProviderInterface
interface — rafalmasiarek\ContactForm\Contracts\ErrorCodeProviderInterface · source
Contracts for exceptions that carry a stable machine-readable error code. Implement this on your validators/hooks/transport exceptions so that the ContactFormService can return consistent: ['ok' => false, 'code' => 'ERR_FOO', 'message' => '...']
| Method | Visibility | Returns | Summary |
|---|---|---|---|
getErrorCode() |
public | string |
Return a stable symbolic code, e.g. "ERR_EMAIL_INVALID". |
getMessageContext() |
public | array<int|string, mixed> |
Optional printf/vsprintf context passed to the message resolver. |
getErrorCode()
ErrorCodeProviderInterface getErrorCode()
public function getErrorCode(): string
Return a stable symbolic code, e.g. "ERR_EMAIL_INVALID".
Returns: string
getMessageContext()
ErrorCodeProviderInterface getMessageContext()
public function getMessageContext(): array
Optional printf/vsprintf context passed to the message resolver.
Returns: array<int\|string, mixed> — Positional or named context values.
IpResolverInterface
interface — rafalmasiarek\ContactForm\Contracts\IpResolverInterface · source
Abstraction for resolving client IP and User-Agent from the current request. The default implementation reads from $_SERVER and is suitable for raw PHP without reverse proxies. Behind a proxy (Nginx, Cloudflare, load balancer) inject your own implementation that validates trusted proxy ranges before trusting forwarded headers.
See: \rafalmasiarek\ContactForm\Support\DefaultIpResolver
| Method | Visibility | Returns | Summary |
|---|---|---|---|
resolveClientIp() |
public | string|null |
Resolve the best-effort client IP address. |
resolveUserAgent() |
public | string|null |
Resolve the User-Agent header. |
resolveClientIp()
IpResolverInterface resolveClientIp()
public function resolveClientIp(): ?string
Resolve the best-effort client IP address.
Returns: string\|null — Client IP if available; otherwise null.
resolveUserAgent()
IpResolverInterface resolveUserAgent()
public function resolveUserAgent(): ?string
Resolve the User-Agent header.
Returns: string\|null — User-Agent if available; otherwise null.
MessageResolverInterface
interface — rafalmasiarek\ContactForm\Contracts\MessageResolverInterface · source
Resolves a human-friendly message and (optionally) structured metadata for a code. Implementations may support structured descriptors including HTTP/app error codes.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
resolve() |
public | string |
Resolve a UI-friendly message for a given code. |
describe() |
public | array{message: string, http?: int, errco?: int} |
Describe a code with optional metadata used by the API layer. Keys: - message (string) Human-readable message - http (int) Suggested HTTP status (API may default if missing) - errco (int) Numeric application error code |
extend() |
public | void |
Extend/override code mappings. Values may be either: - string → message only - array{message?:string|int, msg?:string, errstr?:string, http?:int, status?:int, errco?:int, code?:int} (keys are normalized; errco/http/status/code are accepted) |
resolve()
MessageResolverInterface resolve()
public function resolve(string $code, array $context): string
Resolve a UI-friendly message for a given code.
| Param | Type | Description |
|---|---|---|
$code |
string |
Stable symbolic code (OK_* / ERR_*). |
$context |
array<int|string, mixed> |
Optional vsprintf context. |
Returns: string
describe()
MessageResolverInterface describe()
public function describe(string $code): array
Describe a code with optional metadata used by the API layer. Keys: - message (string) Human-readable message - http (int) Suggested HTTP status (API may default if missing) - errco (int) Numeric application error code
| Param | Type | Description |
|---|---|---|
$code |
string |
— |
Returns: array{message: string, http?: int, errco?: int}
extend()
MessageResolverInterface extend()
public function extend(array $map): void
Extend/override code mappings. Values may be either: - string → message only - array{message?:string|int, msg?:string, errstr?:string, http?:int, status?:int, errco?:int, code?:int} (keys are normalized; errco/http/status/code are accepted)
| Param | Type | Description |
|---|---|---|
$map |
array<string, string|array<string, mixed>> |
— |
Codes
final class — rafalmasiarek\ContactForm\Core\Codes · source
Centralized list of stable symbolic codes used by the core service. Transport-specific codes (e.g., SMTP) must live inside the transport implementation to avoid leaking implementation details globally.
ContactDataHook
final class — rafalmasiarek\ContactForm\Core\ContactDataHook · source
Thin read-write façade around the live {@see ContactData} DTO plus a lightweight context bag for hooks. This wrapper intentionally exposes only a single accessor {@see data()} to keep the contract simple and explicit: hooks can freely read and modify the underlying mutable ContactData object. Hooks can mutate the DTO via data() and read request context (e.g. raw body) via body() / ctx(). Rationale: - Makes the "hook API surface" explicit (hooks operate on a wrapper). - Keeps validators separate (they should use a read-only snapshot). Example: public function onBeforeValidate(ContactDataHook $d): void { $data = $d->data(); $data->name = trim($data->name); $data->meta['normalized'] = true; }
Depends on: ContactData
| Property | Type | Visibility | Description |
|---|---|---|---|
$data |
ContactData |
private | — |
$context |
array<string, mixed> |
private | Arbitrary, read-only context for hooks (e.g. ["body"=>[...], "ip"=>...]). |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
data() |
public | ContactData |
Access the underlying mutable DTO. |
body() |
public | array<mixed> |
Convenience: return the original parsed request body (if provided). |
ctx() |
public | mixed |
Generic context accessor. |
__construct()
ContactDataHook __construct()
public function __construct(ContactData $data, array $context)
| Param | Type | Description |
|---|---|---|
$data |
ContactData |
— |
$context |
array<string, mixed> |
Optional extras like ['body'=>array, ...] |
data()
ContactDataHook data()
public function data(): ContactData
Access the underlying mutable DTO.
Returns: ContactData
body()
ContactDataHook body()
public function body(): array
Convenience: return the original parsed request body (if provided).
Returns: array<mixed>
ctx()
ContactDataHook ctx()
public function ctx(string $key, $default):
Generic context accessor.
| Param | Type | Description |
|---|---|---|
$key |
string |
— |
$default |
mixed |
— |
Returns: mixed
ContactFormService
final class — rafalmasiarek\ContactForm\Core\ContactFormService · source
Lightweight, pluggable contact form service. Responsibilities: - Runs user-provided validators (callables) that may throw on error. - Renders an HTML email from {@see ContactData}. - Sends the message via an injected {@see EmailSenderInterface} (or a lazy PHPMailer sender if SMTP config is provided). - Logs structured events using {@see AttemptLoggerInterface}. - Retrieves request metadata (IP/UA) via {@see IpResolverInterface}. Notes: - The service returns a simple array payload, not an HTTP response. - External checks (CSRF / reCAPTCHA / geoblocking) should happen upstream. - Message text is resolved from a symbolic code via {@see MessageResolverInterface}.
Depends on: AttemptLoggerInterface, EmailSenderInterface, EmailTemplateInterface, MessageResolverInterface, IpResolverInterface
| Property | Type | Visibility | Description |
|---|---|---|---|
$validators |
array<string, callable(ContactDataValidator): (void|array<string, mixed>)> |
private | List of validator callables executed before sending. Each validator receives ContactData and may throw to abort. |
$logger |
AttemptLoggerInterface |
private | Logger implementation (defaults to {@see NullLogger}). |
$context |
array<string, mixed> |
private | — |
$hooks |
ContactFormHookInterface[] |
private | Hooks executed around the send pipeline. Methods may optionally return arrays with meta which will be collected. |
$hooksBeforeGlobal |
ContactFormHookInterface[] |
private | Hooks run globally before any validator |
$hooksBeforeByValidator |
array<string, ContactFormHookInterface[]> |
private | Hooks run before specific validator label |
$hooksAfterGlobal |
ContactFormHookInterface[] |
private | Hooks run once after all validators |
$hooksAfterByValidator |
array<string, ContactFormHookInterface[]> |
private | Hooks run right after specific validator label |
$emailSender |
EmailSenderInterface|null |
private | Optional sender; falls back to PHPMailer sender if SMTP config is provided. |
$template |
EmailTemplateInterface|null |
private | Optional template used to generate the HTML and plain-text bodies. |
$smtpConfig |
array<string, mixed>|null |
private | SMTP configuration used to lazily construct a default PHPMailer sender when no custom {@see EmailSenderInterface} is injected. |
$messages |
MessageResolverInterface |
private | Message resolver for code → text mapping. |
$ipResolver |
IpResolverInterface|null |
private | Optional IP/UA resolver used as fallback when client context is not provided via withContext(). |
$meta |
array<string, mixed> |
private | Aggregated meta bag collected from validators, hooks and request data. |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
withRequestBody() |
public | $this |
Store the original parsed request body for hook access. |
withContext() |
public | $this |
(Optional) Generic context setter to add client/server/request info. |
withIpResolver() |
public | $this |
Inject a custom IP/UA resolver used as fallback when client context is absent. If not set, {@see DefaultIpResolver} is used (reads from $_SERVER, no proxy headers). Behind a reverse proxy inject your own implementation that validates trusted ranges. The resolver is only consulted when 'client.ip' or 'client.ua' are missing from the context provided via {@see withContext()}. Explicit context always takes priority. |
setValidators() |
public | $this |
Replace the full validator set. Accepted forms: - ['label' => callable] - [callable, callable] (labels auto-derived) |
addValidator() |
public | $this |
Add a single validator callable (optionally with a fixed name). |
setLogger() |
public | $this |
Set a custom logger. |
setHook() |
public | $this |
Backward-compat: set a single hook (overwrites existing). Prefer setHooks()/addHook() for multiple hooks. |
setHooks() |
public | $this |
Replace all hooks at once (order preserved). Each item may be: - ContactFormHookInterface instance (global: before-all & after-all), - array spec: [ ContactFormHookInterface $hook, 'beforeValidator' => string|string[]|null, 'afterValidator' => string|string[]|null ] Empty array [] for before/after means "global" in that phase. |
addHook() |
public | $this |
Append a hook (executed after existing ones). |
setEmailSender() |
public | $this |
Inject a custom email sender implementation. |
setSmtpConfig() |
public | $this |
Replace SMTP configuration (used only if no custom sender is injected). |
setMessageResolver() |
public | $this |
Inject a custom message resolver (for i18n / per-project copy). |
process() |
public | array{ok: bool, code: string, message: string, meta: array<string, mixed>} |
Execute the full submission pipeline. Return shape (intentionally minimal): - on success: ['ok' => true, 'code' => 'OK_SENT', 'message' => ..., 'meta' => {...}] - on error: ['ok' => false, 'code' => 'ERR_* / custom', 'message' => ..., 'meta' => {...}] Meta contains outputs from validators and hooks (if they return arrays), as well as basic request metadata (ip/ua) when available. |
makeDefaultSender() |
private | EmailSenderInterface|null |
Lazily construct the default PHPMailer-based sender if SMTP config is present. |
success() |
private | array{ok: true, code: string, message: string, meta: array<string, mixed>} |
Build a success response envelope. |
fail() |
private | array{ok: false, code: string, message: string, meta: array<string, mixed>} |
Build a failure response envelope. |
callableLabel() |
private | string |
Best-effort, human-readable label for a callable validator (for meta). |
validatorKey() |
private | string |
Derive a stable, human-friendly key for a validator callable. Examples: - [ClassName, 'method'] => "ClassName.method" with namespace stripped - Closure => "closure." - "function_name" string => "function_name" - fallback => "callable" Small cosmetics: - Strip leading "ContactForm" and trailing "Validator" to shorten common names. |
recordValidatorMeta() |
private | void |
Persist per-validator meta under meta['validators'][$key]. The stored shape is a flat associative array, e.g.: meta['validators']['csrf.validate'] = [ 'status' => 'ok'|'fail', 'error_code' => '...', 'field' => '...', 'meta' => [...], ... (any extra fields emitted by the validator) ] |
__construct()
ContactFormService __construct()
public function __construct(?array $smtpConfig)
| Param | Type | Description |
|---|---|---|
$smtpConfig |
array<string, mixed>|null |
Optional SMTP config for lazy PHPMailer sender. |
withRequestBody()
ContactFormService withRequestBody()
public function withRequestBody(array $body): self
Store the original parsed request body for hook access.
| Param | Type | Description |
|---|---|---|
$body |
array |
— |
Returns: $this
withContext()
ContactFormService withContext()
public function withContext(array $ctx): self
(Optional) Generic context setter to add client/server/request info.
| Param | Type | Description |
|---|---|---|
$ctx |
array<string, mixed> |
— |
Returns: $this
withIpResolver()
ContactFormService withIpResolver()
public function withIpResolver(IpResolverInterface $resolver): self
Inject a custom IP/UA resolver used as fallback when client context is absent. If not set, {@see DefaultIpResolver} is used (reads from $_SERVER, no proxy headers). Behind a reverse proxy inject your own implementation that validates trusted ranges. The resolver is only consulted when 'client.ip' or 'client.ua' are missing from the context provided via {@see withContext()}. Explicit context always takes priority.
| Param | Type | Description |
|---|---|---|
$resolver |
IpResolverInterface |
— |
Returns: $this
setValidators()
ContactFormService setValidators()
public function setValidators(array $validators): self
Replace the full validator set. Accepted forms: - ['label' => callable] - [callable, callable] (labels auto-derived)
| Param | Type | Description |
|---|---|---|
$validators |
array<string|int, callable> |
— |
Returns: $this
addValidator()
ContactFormService addValidator()
public function addValidator(callable $validator, ?string $name): self
Add a single validator callable (optionally with a fixed name).
| Param | Type | Description |
|---|---|---|
$validator |
callable(ContactDataValidator): (void|array<string, mixed>) |
— |
$name |
string|null |
— |
Returns: $this
setLogger()
ContactFormService setLogger()
public function setLogger(AttemptLoggerInterface $logger): self
Set a custom logger.
| Param | Type | Description |
|---|---|---|
$logger |
AttemptLoggerInterface |
— |
Returns: $this
setHook()
ContactFormService setHook()
Deprecated — Use setHooks() or addHook() instead.
public function setHook(ContactFormHookInterface $hook): self
Backward-compat: set a single hook (overwrites existing). Prefer setHooks()/addHook() for multiple hooks.
| Param | Type | Description |
|---|---|---|
$hook |
ContactFormHookInterface |
— |
Returns: $this
setHooks()
ContactFormService setHooks()
public function setHooks(array $hooks): self
Replace all hooks at once (order preserved). Each item may be: - ContactFormHookInterface instance (global: before-all & after-all), - array spec: [ ContactFormHookInterface $hook, 'beforeValidator' => string|string[]|null, 'afterValidator' => string|string[]|null ] Empty array [] for before/after means "global" in that phase.
| Param | Type | Description |
|---|---|---|
$hooks |
array<int, ContactFormHookInterface|array> |
— |
Returns: $this
addHook()
ContactFormService addHook()
public function addHook(ContactFormHookInterface $hook): self
Append a hook (executed after existing ones).
| Param | Type | Description |
|---|---|---|
$hook |
ContactFormHookInterface |
— |
Returns: $this
setEmailSender()
ContactFormService setEmailSender()
public function setEmailSender(EmailSenderInterface $sender): self
Inject a custom email sender implementation.
| Param | Type | Description |
|---|---|---|
$sender |
EmailSenderInterface |
— |
Returns: $this
setSmtpConfig()
ContactFormService setSmtpConfig()
public function setSmtpConfig(?array $smtp): self
Replace SMTP configuration (used only if no custom sender is injected).
| Param | Type | Description |
|---|---|---|
$smtp |
array<string, mixed>|null |
— |
Returns: $this
setMessageResolver()
ContactFormService setMessageResolver()
public function setMessageResolver(MessageResolverInterface $resolver): self
Inject a custom message resolver (for i18n / per-project copy).
| Param | Type | Description |
|---|---|---|
$resolver |
MessageResolverInterface |
— |
Returns: $this
process()
ContactFormService process()
public function process(ContactData $data): array
Execute the full submission pipeline. Return shape (intentionally minimal): - on success: ['ok' => true, 'code' => 'OK_SENT', 'message' => ..., 'meta' => {...}] - on error: ['ok' => false, 'code' => 'ERR_* / custom', 'message' => ..., 'meta' => {...}] Meta contains outputs from validators and hooks (if they return arrays), as well as basic request metadata (ip/ua) when available.
| Param | Type | Description |
|---|---|---|
$data |
ContactData |
Submitted contact data. |
Returns: array{ok: bool, code: string, message: string, meta: array<string, mixed>}
makeDefaultSender()
ContactFormService makeDefaultSender()
private function makeDefaultSender(): ?EmailSenderInterface
Lazily construct the default PHPMailer-based sender if SMTP config is present.
Returns: EmailSenderInterface\|null
success()
ContactFormService success()
private function success(string $code, string $message, array $meta): array
Build a success response envelope.
| Param | Type | Description |
|---|---|---|
$code |
string |
Stable symbolic code, e.g. Codes::OK_SENT |
$message |
string |
Human-friendly message resolved by the resolver. |
$meta |
array<string, mixed> |
Aggregated meta to return to the caller. |
Returns: array{ok: true, code: string, message: string, meta: array<string, mixed>}
fail()
ContactFormService fail()
private function fail(string $code, string $message, array $meta): array
Build a failure response envelope.
| Param | Type | Description |
|---|---|---|
$code |
string |
Stable symbolic code, e.g. 'ERR_EMAIL_INVALID' or transport-specific (e.g. PhpMailerEmailSender::ERR_SMTP_AUTH). |
$message |
string |
Human-friendly message resolved by the resolver. |
$meta |
array<string, mixed> |
Aggregated meta to return to the caller. |
Returns: array{ok: false, code: string, message: string, meta: array<string, mixed>}
callableLabel()
ContactFormService callableLabel()
private function callableLabel(callable $cb): string
Best-effort, human-readable label for a callable validator (for meta).
| Param | Type | Description |
|---|---|---|
$cb |
callable |
— |
Returns: string
validatorKey()
ContactFormService validatorKey()
private function validatorKey(callable $cb): string
Derive a stable, human-friendly key for a validator callable. Examples: - [ClassName, 'method'] => "ClassName.method" with namespace stripped - Closure => "closure." - "function_name" string => "function_name" - fallback => "callable" Small cosmetics: - Strip leading "ContactForm" and trailing "Validator" to shorten common names.
| Param | Type | Description |
|---|---|---|
$cb |
callable |
— |
Returns: string
recordValidatorMeta()
ContactFormService recordValidatorMeta()
private function recordValidatorMeta(callable $validator, array $meta): void
Persist per-validator meta under meta['validators'][$key]. The stored shape is a flat associative array, e.g.: meta['validators']['csrf.validate'] = [ 'status' => 'ok'|'fail', 'error_code' => '...', 'field' => '...', 'meta' => [...], ... (any extra fields emitted by the validator) ]
| Param | Type | Description |
|---|---|---|
$validator |
callable |
The validator that produced meta. |
$meta |
array<string, mixed> |
The metadata to store. |
ValidationException
final class — rafalmasiarek\ContactForm\Core\ValidationException · source
Generic validation exception for contact form validators. - $code: short, machine-readable error code (e.g. EMAIL_INVALID, NAME_REQUIRED) - $field: optional field name related to the error (e.g. "email") - $meta: optional extra details (remain internal / for logging)
extends \RuntimeException
Depends on: \Throwable
| Property | Type | Visibility | Description |
|---|---|---|---|
$errorCode |
string |
private | — |
$field |
string|null |
private | — |
$meta |
array<string, mixed> |
private | — |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
getErrorCode() |
public | string |
Machine-readable error code (e.g., EMAIL_INVALID). |
getField() |
public | ?string |
Field name related to the validation error, if any. |
getMeta() |
public | array |
Extra details (for logging/diagnostics). |
__construct()
ValidationException __construct()
public function __construct(string $errorCode, ?string $field, string $message, array $meta, int $code, ?\Throwable $previous)
| Param | Type | Description |
|---|---|---|
$errorCode |
string |
Machine-readable code, e.g. 'EMAIL_INVALID' |
$field |
string|null |
Related field name, e.g. 'email' |
$message |
string |
Optional human message (defaults to $errorCode) |
$meta |
array<string, mixed> |
Optional extra details for logs/diagnostics |
$code |
int |
Native exception code |
$previous |
\Throwable|null |
Previous exception |
getErrorCode()
ValidationException getErrorCode()
public function getErrorCode(): string
Machine-readable error code (e.g., EMAIL_INVALID).
Returns: string
getField()
ValidationException getField()
public function getField(): ?string
Field name related to the validation error, if any.
Returns: ?string
getMeta()
ValidationException getMeta()
public function getMeta(): array
Extra details (for logging/diagnostics).
Returns: array
NativeMailSender
final class — rafalmasiarek\ContactForm\Mail\NativeMailSender · source
Class NativeMailSender Lightweight email sender using PHP's native {@see mail()} function. When to use: - You have a working sendmail-compatible binary on the system (e.g., sendmail, msmtp, mhsendmail) and PHP is configured to use it. - Simple messages without attachments are sufficient. Limitations: - No attachment support (PHP's mail() requires manual MIME boundaries). - Requires proper sendmail_path in php.ini or container setup. Docker + MailHog tip: - Install msmtp in your PHP image and set: sendmail_path = "/usr/bin/msmtp -t" - Point msmtp to MailHog (host: mailhog, port: 1025). Example: $sender = new NativeMailSender( from: 'no-reply@example.test', fromName: 'ContactForm Demo', to: 'inbox@example.test', replyTo: null ); $messageId = $sender->send($outboundEmail);
implements EmailSenderInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
send() |
public | bool |
Send the email using PHP's native mail(). Pulls subject and body from OutboundEmail via getters if available, otherwise falls back to public properties (subject, bodyHtml, bodyText, body). |
encodeHeader() |
private | string |
Encode header value using RFC 2047 (UTF-8, Base64). |
domainFromEmail() |
private | string|null |
Extract domain part from an email address. |
__construct()
NativeMailSender __construct()
public function __construct(string $from, string $fromName, string $to, ?string $replyTo)
| Param | Type | Description |
|---|---|---|
$from |
string |
Envelope/sender email, used in "From" header. |
$fromName |
string |
Human-readable sender name (RFC 2047 encoded). |
$to |
string |
Primary recipient (comma-separated list supported by mail()). |
$replyTo |
string|null |
Optional Reply-To address (e.g., user email from a contact form). |
send()
NativeMailSender send()
public function send(OutboundEmail $email): bool
Send the email using PHP's native mail(). Pulls subject and body from OutboundEmail via getters if available, otherwise falls back to public properties (subject, bodyHtml, bodyText, body).
| Param | Type | Description |
|---|---|---|
$email |
OutboundEmail |
— |
Returns: bool — True on success, false otherwise.
| Throws | When |
|---|---|
\RuntimeException |
If mail() returns false (misconfiguration or transport failure). |
encodeHeader()
NativeMailSender encodeHeader()
private function encodeHeader(string $value): string
Encode header value using RFC 2047 (UTF-8, Base64).
| Param | Type | Description |
|---|---|---|
$value |
string |
— |
Returns: string — Encoded header value safe for non-ASCII.
domainFromEmail()
NativeMailSender domainFromEmail()
private function domainFromEmail(string $email): ?string
Extract domain part from an email address.
| Param | Type | Description |
|---|---|---|
$email |
string |
— |
Returns: string\|null — Domain part or null if not available.
PhpMailerEmailSender
final class — rafalmasiarek\ContactForm\Mail\PhpMailerEmailSender · source
Email sender implementation using PHPMailer with SMTP transport. All PHPMailer/SMTP-specific concerns live here: - local ERR_SMTP_* codes (as public constants), - mapping PHPMailer errors to those codes, - default human messages for those codes (registerDefaultMessages()). The service layer only relies on ErrorCodeProviderInterface; it never references SMTP symbols directly.
implements EmailSenderInterface
| Property | Type | Visibility | Description |
|---|---|---|---|
$smtp |
array{host: string, username?: string, password?: string, port?: int, secure?: string, from: string, from_name?: string, to: string} |
private | SMTP configuration. Keys: - host (string) – SMTP host (required) - username (string) – SMTP username (optional) - password (string) – SMTP password (optional) - port (int) – SMTP port (default: 587) - secure (string) – 'tls' or 'ssl' (optional) - from (string) – From address (required) - from_name (string) – From name (optional) - to (string) – Recipient address (required) |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
send() |
public | bool |
Send the outbound email using PHPMailer and SMTP. |
registerDefaultMessages() |
public static | void |
Register default human-readable messages for this transport's ERR_SMTP_* codes. Call this once when wiring your resolver (you may still override any texts per project/locale). |
mapSmtpError() |
private static | array{code: string, ctx: array} |
Map PHPMailer's ErrorInfo/Exception message into a stable ERR_SMTP_* code. |
__construct()
PhpMailerEmailSender __construct()
public function __construct(array $smtp)
| Param | Type | Description |
|---|---|---|
$smtp |
array{host: string, username?: string, password?: string, port?: int, secure?: string, from: string, from_name?: string, to: string} |
— |
send()
PhpMailerEmailSender send()
public function send(OutboundEmail $email): bool
Send the outbound email using PHPMailer and SMTP.
| Param | Type | Description |
|---|---|---|
$email |
OutboundEmail |
Email message details. |
Returns: bool — True on success, false otherwise.
| Throws | When |
|---|---|
\RuntimeException |
If PHPMailer is not installed. |
PhpMailerTransportException |
On SMTP transport failure with a stable ERR_SMTP_* code. |
\Throwable |
On non-SMTP configuration/runtime failures. |
registerDefaultMessages()
PhpMailerEmailSender registerDefaultMessages()
public static function registerDefaultMessages(ArrayMessageResolver $resolver): void
Register default human-readable messages for this transport's ERR_SMTP_* codes. Call this once when wiring your resolver (you may still override any texts per project/locale).
| Param | Type | Description |
|---|---|---|
$resolver |
ArrayMessageResolver |
— |
mapSmtpError()
PhpMailerEmailSender mapSmtpError()
private static function mapSmtpError(string $errorInfo, string $exceptionMessage): array
Map PHPMailer's ErrorInfo/Exception message into a stable ERR_SMTP_* code.
| Param | Type | Description |
|---|---|---|
$errorInfo |
string |
PHPMailer::$ErrorInfo (may be empty) |
$exceptionMessage |
string |
Exception message from PHPMailer\Exception |
Returns: array{code: string, ctx: array}
PhpMailerTransportException
final class — rafalmasiarek\ContactForm\Mail\PhpMailerTransportException · source
Local SMTP transport exception for PHPMailer sender. This exception stays private to the PHPMailer implementation file, implements ErrorCodeProvider and exposes a stable ERR_SMTP_* code.
implements ErrorCodeProviderInterface · extends \RuntimeException
Depends on: \Throwable
| Property | Type | Visibility | Description |
|---|---|---|---|
$ctx |
array<int|string, mixed> |
private | — |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
getErrorCode() |
public | string |
— |
getMessageContext() |
public | array |
— |
__construct()
PhpMailerTransportException __construct()
public function __construct(string $errorCode, array $ctx, ?\Throwable $prev)
| Param | Type | Description |
|---|---|---|
$errorCode |
string |
Stable code (ERR_SMTP_*) |
$ctx |
array<int|string, mixed> |
Optional resolver context |
$prev |
\Throwable|null |
Previous exception |
getErrorCode()
PhpMailerTransportException getErrorCode()
public function getErrorCode(): string
Returns: string
getMessageContext()
PhpMailerTransportException getMessageContext()
public function getMessageContext(): array
Returns: array
ContactData
final class — rafalmasiarek\ContactForm\Model\ContactData · source
Mutable DTO carrying contact form payload through the pipeline. Semantics: - Top-level properties (name, email, subject, message, phone) are common fields. - body: user-visible, safe-to-expose fields that may be rendered into the email. - meta: internal/diagnostic fields (CSRF, attemptId, ip, ua, flags, scan results, etc.). Templates should only render from top-level properties and body. meta MUST be considered internal and never rendered directly. All properties are intentionally public for simplicity in hooks and templates.
| Property | Type | Visibility | Description |
|---|---|---|---|
$name |
string |
public | — |
$email |
string |
public | — |
$subject |
string |
public | — |
$message |
string |
public | — |
$phone |
string |
public | — |
$body |
array<string, scalar|array|object|null> |
public | User-visible, safe-to-expose fields to be included in the email. Example: company, topic, orderId, preferredTime, etc. |
$meta |
array<string, mixed> |
public | Internal fields used by the service, hooks, and validators. Example: csrf_token, attemptId, refId, ip, ua, threatScan, flags, attachments, etc. |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
__construct()
ContactData __construct()
public function __construct(string $name, string $email, string $message, string $subject, string $phone, array $body, array $meta)
| Param | Type | Description |
|---|---|---|
$name |
string |
— |
$email |
string |
— |
$message |
string |
— |
$subject |
string |
— |
$phone |
string |
— |
$body |
array<string, scalar|array|object|null> |
— |
$meta |
array<string, mixed> |
— |
OutboundEmail
final class — rafalmasiarek\ContactForm\Model\OutboundEmail · source
Value object representing an outbound email ready to be sent. Instances are typically built via {@see OutboundEmail::fromContactData()}, which uses an {@see EmailTemplateInterface} to render bodies and maps basic address fields from SMTP config and ContactData. IMPORTANT: - Templates receive a sanitized ContactData (top-level fields + body only). - The internal meta bag from {@see ContactData} is never passed to templates or rendered into the message.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
fromContactData() |
public static | self |
Factory that builds a ready-to-send email from ContactData using a template. Address resolution: - to: $smtp['to'] if present, otherwise $d->meta['deliver_to'] if present, otherwise empty string - from: $smtp['from'] if present, otherwise $d->email - reply-to: $d->email if present, otherwise same as "from" Templating: - The template receives a sanitized ContactData with meta cleared. - body remains available for user-visible extras. |
__construct()
OutboundEmail __construct()
public function __construct(string $to, string $from, string $replyTo, string $subject, string $htmlBody, ?string $textBody, array $attachments)
| Param | Type | Description |
|---|---|---|
$to |
string |
Recipient email address. |
$from |
string |
Sender email address (envelope/from header). |
$replyTo |
string |
Reply-To email address. |
$subject |
string |
Message subject. |
$htmlBody |
string |
HTML body content. |
$textBody |
string|null |
Optional text body; null means "use fallback". |
$attachments |
list<array{path: string, name?: string}> |
Files to attach. |
fromContactData()
OutboundEmail fromContactData()
public static function fromContactData(ContactData $d, array $smtp, ?EmailTemplateInterface $tpl, array $attachments): self
Factory that builds a ready-to-send email from ContactData using a template. Address resolution: - to: $smtp['to'] if present, otherwise $d->meta['deliver_to'] if present, otherwise empty string - from: $smtp['from'] if present, otherwise $d->email - reply-to: $d->email if present, otherwise same as "from" Templating: - The template receives a sanitized ContactData with meta cleared. - body remains available for user-visible extras.
| Param | Type | Description |
|---|---|---|
$d |
ContactData |
Contact form data. |
$smtp |
array{to?: string, from?: string} |
Minimal SMTP mapping (only 'to' and 'from' are read here). |
$tpl |
EmailTemplateInterface|null |
Template to render bodies; default template if null. |
$attachments |
list<array{path: string, name?: string}> |
Optional attachments. |
Returns: self
ArrayMessageResolver
final class — rafalmasiarek\ContactForm\Support\ArrayMessageResolver · source
ArrayMessageResolver Lightweight message resolver with optional suggested HTTP status. Descriptor format (internal storage): [ 'message' => string, // human-friendly text 'http' => int?, // optional suggested HTTP status ] Backward-compatible inputs accepted by extend()/constructor: - string → treated as ['message' => ] - array with keys: * 'message' | 'msg' | 'errstr' | 'title' → normalized to 'message' * 'http' | 'status' → normalized to 'http' * any 'errco' provided is IGNORED (we no longer store numeric app codes)
implements MessageResolverInterface
| Property | Type | Visibility | Description |
|---|---|---|---|
$map |
array<string, array{message: string, http?: int}> |
private | — |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
resolve() |
public | string |
Resolve code to a human-friendly message. Unknown codes fall back to the unexpected-error message. |
describe() |
public | array{message: string, http?: int} |
Describe a code (message + optional suggested HTTP). Unknown codes fall back to the ERR_UNEXPECTED descriptor — never the raw code string, which would otherwise leak an internal identifier as if it were a human-readable message. |
all() |
public | array<string, array{message: string, http?: int}> |
Return all registered descriptors keyed by error code. |
extend() |
public | void |
Merge descriptors into resolver (normalizing flexible input). |
normalizeDescriptor() |
private | array{message: string, http?: int} |
Normalize flexible input into a strict descriptor used internally. Accepted inputs: - string → ['message' => ] - array → keys normalized: * 'message' | 'msg' | 'errstr' | 'title' → 'message' * 'http' | 'status' → 'http' (int) * 'errco' is ignored (no longer stored) |
__construct()
ArrayMessageResolver __construct()
public function __construct(array $map)
| Param | Type | Description |
|---|---|---|
$map |
array<string, string|array<string, mixed>> |
— |
resolve()
ArrayMessageResolver resolve()
public function resolve(string $code, array $context): string
Resolve code to a human-friendly message. Unknown codes fall back to the unexpected-error message.
| Param | Type | Description |
|---|---|---|
$code |
string |
— |
$context |
array<int|string> |
Values for vsprintf() placeholders (optional). |
Returns: string
describe()
ArrayMessageResolver describe()
public function describe(string $code): array
Describe a code (message + optional suggested HTTP). Unknown codes fall back to the ERR_UNEXPECTED descriptor — never the raw code string, which would otherwise leak an internal identifier as if it were a human-readable message.
| Param | Type | Description |
|---|---|---|
$code |
string |
— |
Returns: array{message: string, http?: int}
all()
ArrayMessageResolver all()
public function all(): array
Return all registered descriptors keyed by error code.
Returns: array<string, array{message: string, http?: int}>
extend()
ArrayMessageResolver extend()
public function extend(array $map): void
Merge descriptors into resolver (normalizing flexible input).
| Param | Type | Description |
|---|---|---|
$map |
array<string, string|array<string, mixed>> |
— |
normalizeDescriptor()
ArrayMessageResolver normalizeDescriptor()
private function normalizeDescriptor(string $code, string|array $value): array
Normalize flexible input into a strict descriptor used internally. Accepted inputs: - string → ['message' => ] - array → keys normalized: * 'message' | 'msg' | 'errstr' | 'title' → 'message' * 'http' | 'status' → 'http' (int) * 'errco' is ignored (no longer stored)
| Param | Type | Description |
|---|---|---|
$code |
string |
— |
$value |
string|array<string, mixed> |
— |
Returns: array{message: string, http?: int}
ContactDataValidator
final class — rafalmasiarek\ContactForm\Support\ContactDataValidator · source
Immutable, read-only snapshot view of {@see ContactData} for validators. This class is intended to be constructed via {@see ContactDataValidator::from()} immediately before running the validation pipeline. It captures the current state of the mutable {@see ContactData} into an immutable structure so that: - Hooks can still freely mutate the live {@see ContactData} object. - Validators operate on a stable, read-only snapshot, preventing accidental writes. Notes: - All scalar fields are copied to strings (empty string when missing). - {@see getMeta()} returns a defensive (deep) copy to avoid external mutation. - There are no setters by design; only accessor methods are exposed. Typical usage: $snapshot = ContactDataValidator::from($contactData); $email = $snapshot->getEmail(); // read-only
See: ContactData
| Property | Type | Visibility | Description |
|---|---|---|---|
$name |
string |
private | Contact person's display name as provided by the submitter. Always a string; empty string when absent. |
$email |
string |
private | Sender's email address (unvalidated raw input). Always a string; empty string when absent. |
$subject |
string |
private | Message subject/title supplied by the user. Always a string; empty string when absent. |
$message |
string |
private | Main message body supplied by the user. Always a string; empty string when absent. |
$phone |
string |
private | Optional phone number supplied by the user (raw, unnormalized). Always a string; empty string when absent. |
$meta |
array<string, mixed> |
private | Arbitrary metadata captured from {@see ContactData::$meta}. This is a deep-copied array to prevent external mutation of nested structures. |
$body |
array<string, mixed> |
private | Arbitrary body captured from {@see ContactData::$body}. This is a deep-copied array to prevent external mutation of nested structures. |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
from() |
public static | self |
Create an immutable, read-only snapshot from the mutable {@see ContactData}. Each scalar field is normalized to a string (empty string when not set), and {@see ContactData::$meta} is deep-copied to ensure immutability. |
deepCopyArray() |
private static | array<string, mixed> |
Recursively copy an array to produce a defensive clone. This prevents validators or downstream consumers from mutating nested metadata structures by reference. |
getName() |
public | string |
Get the submitter's name (read-only). |
getEmail() |
public | string |
Get the submitter's email address (read-only, unvalidated). |
getSubject() |
public | string |
Get the message subject/title (read-only). |
getMessage() |
public | string |
Get the message body (read-only). |
getPhone() |
public | string |
Get the phone number (read-only, unnormalized). |
getMeta() |
public | array<string, mixed> |
Get a defensive (deep) copy of the metadata bag. Modifications to the returned array will NOT affect the internal snapshot. |
getBody() |
public | array<string, mixed> |
Get a defensive (deep) copy of the body bag. Modifications to the returned array will NOT affect the internal snapshot. |
from()
ContactDataValidator from()
public static function from(ContactData $d): self
Create an immutable, read-only snapshot from the mutable {@see ContactData}. Each scalar field is normalized to a string (empty string when not set), and {@see ContactData::$meta} is deep-copied to ensure immutability.
| Param | Type | Description |
|---|---|---|
$d |
ContactData |
Mutable DTO to snapshot. |
Returns: self — Read-only snapshot for validators.
deepCopyArray()
ContactDataValidator deepCopyArray()
private static function deepCopyArray(array $a): array
Recursively copy an array to produce a defensive clone. This prevents validators or downstream consumers from mutating nested metadata structures by reference.
| Param | Type | Description |
|---|---|---|
$a |
array<string, mixed> |
Source array. |
Returns: array<string, mixed> — Deep copy of the source array.
getName()
ContactDataValidator getName()
public function getName(): string
Get the submitter's name (read-only).
Returns: string — Non-null string (may be empty).
getEmail()
ContactDataValidator getEmail()
public function getEmail(): string
Get the submitter's email address (read-only, unvalidated).
Returns: string — Non-null string (may be empty).
getSubject()
ContactDataValidator getSubject()
public function getSubject(): string
Get the message subject/title (read-only).
Returns: string — Non-null string (may be empty).
getMessage()
ContactDataValidator getMessage()
public function getMessage(): string
Get the message body (read-only).
Returns: string — Non-null string (may be empty).
getPhone()
ContactDataValidator getPhone()
public function getPhone(): string
Get the phone number (read-only, unnormalized).
Returns: string — Non-null string (may be empty).
getMeta()
ContactDataValidator getMeta()
public function getMeta(): array
Get a defensive (deep) copy of the metadata bag. Modifications to the returned array will NOT affect the internal snapshot.
Returns: array<string, mixed> — Deep-copied metadata.
getBody()
ContactDataValidator getBody()
public function getBody(): array
Get a defensive (deep) copy of the body bag. Modifications to the returned array will NOT affect the internal snapshot.
Returns: array<string, mixed> — Deep-copied metadata.
DefaultContactTemplate
final class — rafalmasiarek\ContactForm\Support\DefaultContactTemplate · source
Default email template used when no custom template is provided. Rendering rules for extra fields: - We render only from $d->body (user-visible extras). $d->meta is never rendered. Channel-aware values in $d->body: - If a value is an array with channels: * ['html'] — non-empty string → render label then inject raw HTML block. * ['text'] — non-empty string → render label then print escaped text (
in HTML; plain in TEXT). - If a value is a scalar → render as a simple key/value pair with escaping. - Any other shapes are skipped silently to avoid noisy output.implements
EmailTemplateInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
renderHtml() |
public | string |
Render the HTML body for the contact message. |
renderText() |
public | string|null |
Render the plain-text alternative for the contact message. |
renderHtml()
DefaultContactTemplate renderHtml()
public function renderHtml(ContactData $d): string
Render the HTML body for the contact message.
| Param | Type | Description |
|---|---|---|
$d |
ContactData |
Contact data to render (sanitized by the caller; meta is not used here). |
Returns: string — HTML content.
renderText()
DefaultContactTemplate renderText()
public function renderText(ContactData $d): ?string
Render the plain-text alternative for the contact message.
| Param | Type | Description |
|---|---|---|
$d |
ContactData |
Contact data to render (sanitized by the caller; meta is not used here). |
Returns: string\|null — Text content; null to omit the text part (we always return a string here).
DefaultIpResolver
final class — rafalmasiarek\ContactForm\Support\DefaultIpResolver · source
Default resolver that reads client IP and User-Agent directly from $_SERVER. Uses only REMOTE_ADDR — does not trust X-Forwarded-For or similar headers. Suitable for raw PHP deployments without a reverse proxy in front. Behind a proxy (Nginx, Cloudflare, load balancer) inject your own implementation that validates trusted proxy ranges before trusting forwarded headers.
implements IpResolverInterface
| Property | Type | Visibility | Description |
|---|---|---|---|
$server |
array<string, mixed> |
private | — |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | — | — |
resolveClientIp() |
public | ?string |
— |
resolveUserAgent() |
public | ?string |
— |
__construct()
DefaultIpResolver __construct()
public function __construct(array $server)
| Param | Type | Description |
|---|---|---|
$server |
array<string, mixed> |
Optional server params. Defaults to $_SERVER. |
resolveClientIp()
DefaultIpResolver resolveClientIp()
public function resolveClientIp(): ?string
Returns: ?string
resolveUserAgent()
DefaultIpResolver resolveUserAgent()
public function resolveUserAgent(): ?string
Returns: ?string
NullLogger
final class — rafalmasiarek\ContactForm\Support\NullLogger · source
No-op logger implementation. Useful as a safe default when you do not need logging.
implements AttemptLoggerInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
info() |
public | void |
— |
warning() |
public | void |
— |
error() |
public | void |
— |
info()
NullLogger info()
public function info(string $message, array $context): void
| Param | Type | Description |
|---|---|---|
$message |
string |
— |
$context |
array |
— |
warning()
NullLogger warning()
public function warning(string $message, array $context): void
| Param | Type | Description |
|---|---|---|
$message |
string |
— |
$context |
array |
— |