Skip to content

Commit

Permalink
馃帹 Improve the markup build handling
Browse files Browse the repository at this point in the history
馃帹 Move WordPress handling to the service provider
  • Loading branch information
Log1x committed Mar 28, 2024
1 parent 4f6c339 commit 98234cd
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 29 deletions.
64 changes: 36 additions & 28 deletions src/PreloadWebfonts.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,24 @@

namespace Log1x\LaravelWebfonts;

use Illuminate\Support\Str;

class PreloadWebfonts
{
/**
* The Webfonts instance.
*/
protected $webfonts;
protected Webfonts $webfonts;

/**
* The font preload markup.
*/
protected ?string $markup = null;

/**
* Create a new Preload Fonts instance.
*
* @return void
*/
public function __construct(Webfonts $webfonts)
{
$this->webfonts = $webfonts;
$this->handleWordPress();
}

/**
Expand All @@ -33,12 +33,38 @@ public static function make(Webfonts $webfonts): self
/**
* Build the font preload markup.
*/
public function build(): string
public function build(): ?string
{
return collect($this->webfonts()->fonts())
if ($this->markup) {
return $this->markup;
}

if (! $fonts = $this->webfonts()->fonts()) {
return null;
}

return $this->markup = collect($fonts)
->map(fn ($font) => $this->asset($font))
->map(fn ($font) => "<link rel='preload' href='{$font}' as='font' type='font/woff2' crossorigin>")
->implode(PHP_EOL);
->implode("\n");
}

/**
* Handle the font preload markup for WordPress.
*/
public function handleWordPress(): void
{
if (! $this->isWordPress()) {
return;
}

add_filter('wp_head', function () {
if (! $markup = $this->build()) {
return;
}

echo "{$markup}\n";
}, 5);
}

/**
Expand Down Expand Up @@ -68,28 +94,10 @@ protected function isAcorn(): bool
}

/**
* Determine if WordPress is available.
* Determine if the application is running WordPress.
*/
protected function isWordPress(): bool
{
return class_exists('\WP') && function_exists('\add_filter');
}

/**
* Handle preloading on WordPress.
*/
protected function handleWordPress(): void
{
if (! $this->isAcorn() || ! $this->isWordPress()) {
return;
}

add_filter('wp_head', function () {
if (! $this->webfonts()) {
return;
}

echo Str::finish($this->build(), PHP_EOL);
}, 5);
}
}
4 changes: 3 additions & 1 deletion src/WebfontsServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ public function boot()

Blade::directive('preloadFonts', fn () => "<?php echo app('laravel-webfonts')->preload()->build(); ?>");

$this->app->make('laravel-webfonts');
$webfonts = $this->app->make('laravel-webfonts');

$webfonts->preload()->handleWordPress();
}
}

0 comments on commit 98234cd

Please sign in to comment.