Files
WP-LIT-MCP/src/Integrations/Divi/Design/FontNameRules.php
T

70 lines
2.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace LIT\MCP\Integrations\Divi\Design;
defined('ABSPATH') || exit;
/**
* Name rules of an uploaded font (ruling W9), stricter than FontsUtility::font_add(): Divi silently strips every
* character but A–Z, a–z, 0–9, whitespace, _ and -; the plugin refuses them and names what Divi would store.
* Divi compares names with Google's and uploaded fonts case-sensitively and skips the web-safe ones; the plugin
* refuses any of them whatever the case, so a font never shadows another one in Divi's font lists. Pure PHP.
*/
final class FontNameRules
{
/** = FontsUtility::FONT_NAME_MAX_LENGTH in Divi 5.15.1 (FontInstaller::nameMaxLength() reads Divi's). */
public const MAX_LENGTH = 100;
private const ALLOWED = '/^[A-Za-z0-9 _-]+$/D';
/** What FontsUtility::font_add() removes from a name. */
private const DIVI_STRIPS = '/[^A-Za-z0-9\s\_-]/';
/**
* The form only; whether the name is taken is taken().
*
* @return string|null null = valid, else the problem (German).
*/
public static function check(string $name, int $maxLength = self::MAX_LENGTH): ?string
{
if (trim($name) === '') {
return sprintf('Name fehlt (1–%d Zeichen)', $maxLength);
}
if (preg_match(self::ALLOWED, $name) !== 1) {
$stored = trim((string) preg_replace(self::DIVI_STRIPS, '', $name));
return 'nur Buchstaben A–Z/a–z, Ziffern, Leerzeichen, _ und - erlaubt ('
. ($stored === '' ? 'Divi ließe nichts übrig)' : sprintf('Divi würde „%s“ speichern)', $stored));
}
if ($name !== trim($name)) {
return 'ohne Leerzeichen am Anfang oder Ende';
}
if (strlen($name) > $maxLength) {
return sprintf('höchstens %d Zeichen (%d angegeben)', $maxLength, strlen($name));
}
return null;
}
/**
* @param list<string> $reserved Names of Google, web-safe and uploaded fonts (FontCatalog::reserved()).
* @return string|null The existing name $name collides with (case-insensitive), null when it is free.
*/
public static function taken(string $name, array $reserved): ?string
{
$lower = strtolower($name);
foreach ($reserved as $existing) {
if (strtolower($existing) === $lower) {
return $existing;
}
}
return null;
}
}