v1.0.0.1
StocketBase
- <?php
-
- declare(strict_types=1);
-
- final class FontLibrary
- {
- private const FONTS_DIR = __DIR__ . '/../assets/fonts';
- private const ALLOWED_EXTENSIONS = ['ttf', 'otf', 'woff', 'woff2'];
-
- public static function available(): array
- {
- if (!is_dir(self::FONTS_DIR)) {
- return [];
- }
-
- $fonts = [];
- $entries = scandir(self::FONTS_DIR) ?: [];
-
- foreach ($entries as $entry) {
- if ($entry === '.' || $entry === '..') {
- continue;
- }
-
- $extension = strtolower((string) pathinfo($entry, PATHINFO_EXTENSION));
- if (!in_array($extension, self::ALLOWED_EXTENSIONS, true)) {
- continue;
- }
-
- $baseName = (string) pathinfo($entry, PATHINFO_FILENAME);
- $displayName = str_replace('_', ' ', $baseName);
-
- $fonts[$displayName] = [
- 'display_name' => $displayName,
- 'file' => $entry,
- 'format' => self::formatFor($extension),
- ];
- }
-
- ksort($fonts);
- return array_values($fonts);
- }
-
- public static function findByDisplayName(string $displayName): ?array
- {
- foreach (self::available() as $font) {
- if ($font['display_name'] === $displayName) {
- return $font;
- }
- }
-
- return null;
- }
-
- private static function formatFor(string $extension): string
- {
- return match ($extension) {
- 'ttf' => 'truetype',
- 'otf' => 'opentype',
- 'woff' => 'woff',
- 'woff2' => 'woff2',
- default => 'truetype',
- };
- }
-
- public static function fontFaceCss(string $displayName, string $cssFamilyName): string
- {
- $font = self::findByDisplayName($displayName);
- if ($font === null) {
- return '';
- }
-
- $safeFamily = addslashes($cssFamilyName);
- $safeFile = rawurlencode($font['file']);
-
- return "@font-face{font-family:\"{$safeFamily}\";src:url(\"assets/fonts/{$safeFile}\") format(\"{$font['format']}\");font-display:swap;}";
- }
- }
-