Skip to content

Instantly share code, notes, and snippets.

@OldStarchy
Last active February 14, 2020 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OldStarchy/cb1194ef47443666318dd998b6c497fe to your computer and use it in GitHub Desktop.
Save OldStarchy/cb1194ef47443666318dd998b6c497fe to your computer and use it in GitHub Desktop.
Sync fonts to the assets dir so relative links in combined CSS will work
SilverStripe\Assets\File:
allowed_extensions:
- eot
- svg
- ttf
- woff
- woff2
<?php
use SilverStripe\CMS\Controllers\ContentController;
use SilverStripe\Core\Flushable;
use SilverStripe\Core\Path;
use SilverStripe\View\Requirements;
use SilverStripe\View\ThemeResourceLoader;
class PageController extends ContentController implements Flushable
{
public static function flush()
{
$loader = ThemeResourceLoader::inst();
$paths = $loader->getThemePaths();
$paths = array_reverse($paths);
// Finds all files in webfonts directory, not just fonts.
$fonts = [];
foreach ($paths as $path) {
if (substr($path, 0, 6) === 'vendor') {
continue;
}
$fontDir = Path::join(BASE_PATH, $path, 'webfonts');
if (is_dir($fontDir)) {
$files = scandir($fontDir);
if ($files !== false) {
foreach ($files as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$filePath = Path::join($fontDir, $file);
// Only find files (and therefore ignore . and .. directories)
if (is_file($filePath)) {
$fonts[] = [$file, $filePath];
}
}
}
}
}
$webfontsOutPath = Path::join(ASSETS_PATH, 'webfonts');
if (!file_exists($webfontsOutPath)) {
mkdir($webfontsOutPath, 0777, true);
}
if (!is_dir($webfontsOutPath)) {
user_error("Couldn't create webfonts folder in combinedFiles, it exists as a file already");
return;
}
foreach ($fonts as $font) {
[$name, $path] = $font;
$outPath = Path::join($webfontsOutPath, $name);
$shouldCopy = true;
if (file_exists($outPath)) {
if (filemtime($outPath) > filemtime($path)) {
$shouldCopy = false;
} else {
unlink($outPath);
}
}
if ($shouldCopy) {
copy($path, $outPath);
}
}
$existingFiles = scandir($webfontsOutPath);
$fontNames = array_column($fonts, 0);
foreach ($existingFiles as $existingFile) {
if ($existingFile === '.' || $existingFile === '..') {
continue;
}
$existingFilePath = Path::join($webfontsOutPath, $existingFile);
if (is_file($existingFilePath)) {
if (!in_array($existingFile, $fontNames)) {
unlink($existingFilePath);
}
}
}
}
}
@OldStarchy
Copy link
Author

That note about it taking 7ms, thats testing on our not-so-fast dev server in php7.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment