WebOrbiton
v1.0.0.0

StocketBase

78 lines · 2.1 KB
  1. <?php
  2. ​
  3. declare(strict_types=1);
  4. ​
  5. final class FontLibrary
  6. {
  7. private const FONTS_DIR = __DIR__ . '/../assets/fonts';
  8. private const ALLOWED_EXTENSIONS = ['ttf', 'otf', 'woff', 'woff2'];
  9. ​
  10. public static function available(): array
  11. {
  12. if (!is_dir(self::FONTS_DIR)) {
  13. return [];
  14. }
  15. ​
  16. $fonts = [];
  17. $entries = scandir(self::FONTS_DIR) ?: [];
  18. ​
  19. foreach ($entries as $entry) {
  20. if ($entry === '.' || $entry === '..') {
  21. continue;
  22. }
  23. ​
  24. $extension = strtolower((string) pathinfo($entry, PATHINFO_EXTENSION));
  25. if (!in_array($extension, self::ALLOWED_EXTENSIONS, true)) {
  26. continue;
  27. }
  28. ​
  29. $baseName = (string) pathinfo($entry, PATHINFO_FILENAME);
  30. $displayName = str_replace('_', ' ', $baseName);
  31. ​
  32. $fonts[$displayName] = [
  33. 'display_name' => $displayName,
  34. 'file' => $entry,
  35. 'format' => self::formatFor($extension),
  36. ];
  37. }
  38. ​
  39. ksort($fonts);
  40. return array_values($fonts);
  41. }
  42. ​
  43. public static function findByDisplayName(string $displayName): ?array
  44. {
  45. foreach (self::available() as $font) {
  46. if ($font['display_name'] === $displayName) {
  47. return $font;
  48. }
  49. }
  50. ​
  51. return null;
  52. }
  53. ​
  54. private static function formatFor(string $extension): string
  55. {
  56. return match ($extension) {
  57. 'ttf' => 'truetype',
  58. 'otf' => 'opentype',
  59. 'woff' => 'woff',
  60. 'woff2' => 'woff2',
  61. default => 'truetype',
  62. };
  63. }
  64. ​
  65. public static function fontFaceCss(string $displayName, string $cssFamilyName): string
  66. {
  67. $font = self::findByDisplayName($displayName);
  68. if ($font === null) {
  69. return '';
  70. }
  71. ​
  72. $safeFamily = addslashes($cssFamilyName);
  73. $safeFile = rawurlencode($font['file']);
  74. ​
  75. return "@font-face{font-family:\"{$safeFamily}\";src:url(\"assets/fonts/{$safeFile}\") format(\"{$font['format']}\");font-display:swap;}";
  76. }
  77. }
  78. ​