46 lines
1.6 KiB
PHP
46 lines
1.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Content;
|
|
|
|
use RuntimeException;
|
|
|
|
final class Buttons
|
|
{
|
|
public const STYLES = ['solid' => '纯色填充', 'outline' => '线框', 'underline' => '下划线', 'plain' => '无样式'];
|
|
private const CLASSES = ['solid' => 'button-primary', 'outline' => 'button-outline', 'underline' => 'button-underline', 'plain' => 'button-plain'];
|
|
|
|
public static function validate(mixed $items, int $limit = 8): array
|
|
{
|
|
if (!is_array($items) || !array_is_list($items) || count($items) > $limit) {
|
|
throw new RuntimeException('按钮或链接数量超过限制。');
|
|
}
|
|
$buttons = [];
|
|
foreach ($items as $index => $item) {
|
|
$url = $item[0] ?? null;
|
|
$label = $item[1] ?? null;
|
|
$style = $item[2] ?? ($index === 0 ? 'solid' : 'outline');
|
|
$blank = $item[3] ?? false;
|
|
if (!is_string($url) || strlen($url) > 1000 || !Html::url($url) || !is_string($label)
|
|
|| trim($label) === '' || mb_strlen($label) > 70 || !is_string($style) || !isset(self::STYLES[$style])
|
|
|| !is_bool($blank)) {
|
|
throw new RuntimeException('请检查按钮文案、链接和样式。');
|
|
}
|
|
$buttons[] = [$url, $label, $style, $blank];
|
|
}
|
|
|
|
return $buttons;
|
|
}
|
|
|
|
public static function css(string $style): string
|
|
{
|
|
return 'button ' . (self::CLASSES[$style] ?? self::CLASSES['solid']);
|
|
}
|
|
|
|
public static function target(bool $blank): string
|
|
{
|
|
return $blank ? ' target="_blank" rel="noopener noreferrer"' : '';
|
|
}
|
|
}
|