Skip to content

Instantly share code, notes, and snippets.

@OldStarchy
Last active February 14, 2020 02:26
Embed
What would you like to do?
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