You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/UserProfileService.php

104 lines
3.3 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services;
use App\Models\User;
/** Shared validation and persistence for registration and account profile data. */
final class UserProfileService
{
public const FIELDS = [
'last_name',
'first_name',
'phone',
'country',
'province',
'city',
'address',
'postal_code',
];
private const LABELS = [
'last_name' => '姓',
'first_name' => '名',
'phone' => '手机号',
'country' => '国家',
'province' => '省/州',
'city' => '城市',
'address' => '具体地址',
'postal_code' => '邮编',
];
private const MAX_LENGTHS = [
'last_name' => 80,
'first_name' => 80,
'phone' => 32,
'country' => 100,
'province' => 100,
'city' => 100,
'address' => 255,
'postal_code' => 32,
];
public static function validate(array $input): array
{
$profile = [];
foreach (self::FIELDS as $field) {
$value = $input[$field] ?? '';
if (!is_string($value) || preg_match('//u', $value) !== 1) {
throw new \InvalidArgumentException(self::LABELS[$field] . '格式无效');
}
$value = preg_replace('/[\p{Z}\s]+/u', ' ', $value);
$value = is_string($value) ? trim($value) : '';
if ($value === '') {
throw new \InvalidArgumentException('请填写' . self::LABELS[$field]);
}
if (preg_match('/\p{C}/u', $value) === 1) {
throw new \InvalidArgumentException(self::LABELS[$field] . '包含无效字符');
}
if (str_contains($value, '<') || str_contains($value, '>')) {
throw new \InvalidArgumentException(self::LABELS[$field] . '包含无效字符');
}
if (mb_strlen($value, 'UTF-8') > self::MAX_LENGTHS[$field]) {
throw new \InvalidArgumentException(self::LABELS[$field] . '内容过长');
}
$profile[$field] = $value;
}
foreach (['last_name', 'first_name'] as $field) {
if (preg_match("/^[\\p{L}\\p{M}][\\p{L}\\p{M} .\u{00B7}'’\\-]*$/u", $profile[$field]) !== 1) {
throw new \InvalidArgumentException(self::LABELS[$field] . '只能包含文字、空格、点、撇号或连字符');
}
}
if (preg_match('/^\+?[0-9][0-9 ()\.\-]*$/', $profile['phone']) !== 1) {
throw new \InvalidArgumentException('手机号格式无效');
}
$phoneDigits = preg_replace('/\D+/', '', $profile['phone']);
if (!is_string($phoneDigits) || strlen($phoneDigits) < 6 || strlen($phoneDigits) > 20) {
throw new \InvalidArgumentException('手机号需包含 6 至 20 位数字');
}
if (preg_match('/^[\p{L}\p{N}][\p{L}\p{N} \-]*$/u', $profile['postal_code']) !== 1) {
throw new \InvalidArgumentException('邮编格式无效');
}
return $profile;
}
public static function update(User $user, array $input): array
{
$profile = self::validate($input);
foreach ($profile as $field => $value) {
$user->{$field} = $value;
}
if (!$user->save()) {
throw new \RuntimeException('账户信息保存失败');
}
return $profile;
}
}