73 lines
2.3 KiB
PHP
73 lines
2.3 KiB
PHP
<?php
|
|||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Normalize the fields accepted by a client contact form.
|
||
|
|
*
|
||
|
|
* Empty optional values are represented as null and the primary flag is a bool.
|
||
|
|
*/
|
||
|
|
function normalize_client_contact(array $input): array
|
||
|
|
{
|
||
|
|
$email = trim((string)($input['email'] ?? ''));
|
||
|
|
$phone = trim((string)($input['phone'] ?? ''));
|
||
|
|
|
||
|
|
return [
|
||
|
|
'name' => trim((string)($input['name'] ?? '')),
|
||
|
|
'email' => $email === '' ? null : strtolower($email),
|
||
|
|
'phone' => $phone === '' ? null : $phone,
|
||
|
|
'is_primary' => normalize_client_contact_primary($input['is_primary'] ?? $input['primary'] ?? false),
|
||
|
|
];
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Validate and normalize a client contact in one reusable operation.
|
||
|
|
*/
|
||
|
|
function validate_client_contact(array $input): array
|
||
|
|
{
|
||
|
|
$contact = normalize_client_contact($input);
|
||
|
|
$errors = [];
|
||
|
|
|
||
|
|
if ($contact['name'] === '') {
|
||
|
|
$errors['name'] = 'Contact name is required.';
|
||
|
|
} elseif (mb_strlen($contact['name']) > 120) {
|
||
|
|
$errors['name'] = 'Contact name must be 120 characters or fewer.';
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($contact['email'] !== null && filter_var($contact['email'], FILTER_VALIDATE_EMAIL) === false) {
|
||
|
|
$errors['email'] = 'Contact email must be a valid email address.';
|
||
|
|
} elseif ($contact['email'] !== null && mb_strlen($contact['email']) > 190) {
|
||
|
|
$errors['email'] = 'Contact email must be 190 characters or fewer.';
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($contact['phone'] !== null && mb_strlen($contact['phone']) > 60) {
|
||
|
|
$errors['phone'] = 'Contact phone must be 60 characters or fewer.';
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!is_bool($contact['is_primary'])) {
|
||
|
|
$errors['is_primary'] = 'Primary contact flag must be boolean.';
|
||
|
|
$contact['is_primary'] = false;
|
||
|
|
}
|
||
|
|
|
||
|
|
return [...$contact, 'errors' => $errors];
|
||
|
|
}
|
||
|
|
|
||
|
|
function normalize_client_contact_primary(mixed $value): bool|int|string
|
||
|
|
{
|
||
|
|
if (is_bool($value)) {
|
||
|
|
return $value;
|
||
|
|
}
|
||
|
|
if (is_int($value) && ($value === 0 || $value === 1)) {
|
||
|
|
return $value === 1;
|
||
|
|
}
|
||
|
|
if (is_string($value)) {
|
||
|
|
$normalized = strtolower(trim($value));
|
||
|
|
if (in_array($normalized, ['1', 'true', 'yes', 'on'], true)) {
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
if (in_array($normalized, ['', '0', 'false', 'no', 'off'], true)) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return $value;
|
||
|
|
}
|