| 1 |
<?php |
| 2 |
|
| 3 |
/* |
| 4 |
* This file is part of the Assets package. |
| 5 |
* |
| 6 |
* (c) Inpsyde GmbH |
| 7 |
* |
| 8 |
* For the full copyright and license information, please view the LICENSE |
| 9 |
* file that was distributed with this source code. |
| 10 |
*/ |
| 11 |
|
| 12 |
declare(strict_types=1); |
| 13 |
|
| 14 |
namespace Inpsyde\Assets\Handler; |
| 15 |
|
| 16 |
use Inpsyde\Assets\Asset; |
| 17 |
use Inpsyde\Assets\OutputFilter\AsyncStyleOutputFilter; |
| 18 |
use Inpsyde\Assets\OutputFilter\AttributesOutputFilter; |
| 19 |
use Inpsyde\Assets\OutputFilter\InlineAssetOutputFilter; |
| 20 |
use Inpsyde\Assets\Style; |
| 21 |
|
| 22 |
class StyleHandler implements AssetHandler, OutputFilterAwareAssetHandler |
| 23 |
{ |
| 24 |
use OutputFilterAwareAssetHandlerTrait; |
| 25 |
|
| 26 |
/** |
| 27 |
* @var \WP_Styles |
| 28 |
*/ |
| 29 |
protected $wpStyles; |
| 30 |
|
| 31 |
/** |
| 32 |
* StyleHandler constructor. |
| 33 |
* |
| 34 |
* @param \WP_Styles $wpStyles |
| 35 |
* @param array<string, callable> $outputFilters |
| 36 |
*/ |
| 37 |
public function __construct(\WP_Styles $wpStyles, array $outputFilters = []) |
| 38 |
{ |
| 39 |
$this->withOutputFilter(AsyncStyleOutputFilter::class, new AsyncStyleOutputFilter()); |
| 40 |
$this->withOutputFilter(InlineAssetOutputFilter::class, new InlineAssetOutputFilter()); |
| 41 |
$this->withOutputFilter(AttributesOutputFilter::class, new AttributesOutputFilter()); |
| 42 |
|
| 43 |
$this->wpStyles = $wpStyles; |
| 44 |
foreach ($outputFilters as $name => $callable) { |
| 45 |
$this->withOutputFilter($name, $callable); |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
public function enqueue(Asset $asset): bool |
| 50 |
{ |
| 51 |
$this->register($asset); |
| 52 |
|
| 53 |
if ($asset->enqueue()) { |
| 54 |
wp_enqueue_style($asset->handle()); |
| 55 |
|
| 56 |
return true; |
| 57 |
} |
| 58 |
|
| 59 |
return false; |
| 60 |
} |
| 61 |
|
| 62 |
public function register(Asset $asset): bool |
| 63 |
{ |
| 64 |
/** @var Style $asset */ |
| 65 |
|
| 66 |
$handle = $asset->handle(); |
| 67 |
wp_register_style( |
| 68 |
$handle, |
| 69 |
$asset->url(), |
| 70 |
$asset->dependencies(), |
| 71 |
$asset->version(), |
| 72 |
$asset->media() |
| 73 |
); |
| 74 |
|
| 75 |
$inlineStyles = $asset->inlineStyles(); |
| 76 |
if ($inlineStyles !== null) { |
| 77 |
wp_add_inline_style($handle, implode("\n", $inlineStyles)); |
| 78 |
} |
| 79 |
|
| 80 |
$cssVars = $asset->cssVars(); |
| 81 |
if (count($cssVars) > 0) { |
| 82 |
wp_add_inline_style($handle, $asset->cssVarsAsString()); |
| 83 |
} |
| 84 |
|
| 85 |
if (count($asset->data()) > 0) { |
| 86 |
foreach ($asset->data() as $key => $value) { |
| 87 |
$this->wpStyles->add_data($handle, $key, $value); |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
return true; |
| 92 |
} |
| 93 |
|
| 94 |
public function filterHook(): string |
| 95 |
{ |
| 96 |
return 'style_loader_tag'; |
| 97 |
} |
| 98 |
} |
| 99 |
|