Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically exclude assets from popular caching/optimizer plugins #54

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/AssetFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
namespace Inpsyde\Assets;

use Inpsyde\Assets\Exception\InvalidArgumentException;
use Inpsyde\Assets\Loader\PhpFileLoader;
use Inpsyde\Assets\Loader\ArrayLoader;
use Inpsyde\Assets\Loader\PhpFileLoader;

/**
* Class AssetFactory
Expand Down Expand Up @@ -90,7 +90,7 @@ public static function create(array $config): Asset
}

$inFooter = $config['inFooter'] ?? true;
$inFooter
$inFooter === true
? $asset->isInFooter()
: $asset->isInHeader();

Expand Down
21 changes: 17 additions & 4 deletions src/AssetManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@

namespace Inpsyde\Assets;

use Inpsyde\Assets\Caching\IgnoreCacheHandler;
use Inpsyde\Assets\Handler\AssetHandler;
use Inpsyde\Assets\Handler\OutputFilterAwareAssetHandler;
use Inpsyde\Assets\Handler\ScriptHandler;
use Inpsyde\Assets\Handler\StyleHandler;
use Inpsyde\Assets\Util\AssetHookResolver;
use Inpsyde\Assets\Asset;

final class AssetManager
{
Expand Down Expand Up @@ -51,6 +51,10 @@
* @var bool
*/
private $setupDone = false;
/**
* @var IgnoreCacheHandler
*/
private $ignoreCacheHandler;

/**
* @param AssetHookResolver|null $hookResolver
Expand All @@ -59,6 +63,7 @@
{
$this->hookResolver = $hookResolver ?? new AssetHookResolver();
$this->assets = new \SplObjectStorage();
$this->ignoreCacheHandler = new IgnoreCacheHandler();
}

/**
Expand Down Expand Up @@ -108,7 +113,7 @@

foreach ($assets as $asset) {
$handle = $asset->handle();
if ($handle) {
if ($handle !== '') {
$this->assets->attach($asset, [$handle, get_class($asset)]);
}
}
Expand Down Expand Up @@ -252,7 +257,7 @@

/** @var int|null $locationId */
$locationId = Asset::HOOK_TO_LOCATION[$currentHook] ?? null;
if (!$locationId) {
if (is_null($locationId)) {
return [];
}

Expand Down Expand Up @@ -308,7 +313,10 @@
*
* @psalm-suppress PossiblyNullArgument
*/
if (!$lastHook && did_action($lastHook) && !doing_action($lastHook)) {
if (
(is_null($lastHook) || $lastHook === '') &&
did_action($lastHook) && !doing_action($lastHook)
) {
$this->assets = new \SplObjectStorage();

return;
Expand All @@ -317,4 +325,9 @@
$this->useDefaultHandlers();
do_action(self::ACTION_SETUP, $this);
}

public function ignoreCache(): void

Check warning on line 329 in src/AssetManager.php

View check run for this annotation

Codecov / codecov/patch

src/AssetManager.php#L329

Added line #L329 was not covered by tests
{
$this->ignoreCacheHandler->run($this);

Check warning on line 331 in src/AssetManager.php

View check run for this annotation

Codecov / codecov/patch

src/AssetManager.php#L331

Added line #L331 was not covered by tests
}
}
1 change: 1 addition & 0 deletions src/BaseAsset.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace Inpsyde\Assets;

use Inpsyde\Assets\Caching\IgnoreCacheHandler;
use Inpsyde\Assets\Handler\AssetHandler;
use Inpsyde\Assets\Util\AssetPathResolver;
use Inpsyde\Assets\OutputFilter\AssetOutputFilter;
Expand Down
53 changes: 53 additions & 0 deletions src/Caching/IgnoreCacheHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

namespace Inpsyde\Assets\Caching;

use Inpsyde\Assets\AssetManager;
use Inpsyde\Assets\Script;
use Inpsyde\Assets\Style;

class IgnoreCacheHandler
{
public function run(AssetManager $assetManager): bool
{
/** @var IgnorePluginCacheInterface[] $handlers */
$handlers = [
new IgnoreW3TotalCache(),
new IgnoreSitegroundCache(),
];

$assetHandles = $this->extractHandles($assetManager);

if (
count($assetHandles[Script::class]) === 0 &&
count($assetHandles[Style::class]) === 0
) {
return false;
}

foreach ($handlers as $ignorePluginHandler) {
if ($ignorePluginHandler->isInstalled()) {
$ignorePluginHandler->apply($assetHandles);

Check warning on line 32 in src/Caching/IgnoreCacheHandler.php

View check run for this annotation

Codecov / codecov/patch

src/Caching/IgnoreCacheHandler.php#L32

Added line #L32 was not covered by tests
}
}
return true;
}

protected function extractHandles(AssetManager $assetManager): array
{
$assets = $assetManager->assets();
$assetHandles = [
Script::class => [],
Style::class => [],
];

foreach ($assets as $assetKey => $assetType) {
foreach ($assetType as $asset) {
$assetHandles[$assetKey][] = $asset->handle();
}
}
return $assetHandles;
}
}
11 changes: 11 additions & 0 deletions src/Caching/IgnorePluginCacheInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace Inpsyde\Assets\Caching;

interface IgnorePluginCacheInterface
{
public function isInstalled(): bool;
public function apply(array $handles): void;
}
57 changes: 57 additions & 0 deletions src/Caching/IgnoreSitegroundCache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

declare(strict_types=1);

namespace Inpsyde\Assets\Caching;

use Inpsyde\Assets\Script;
use Inpsyde\Assets\Style;

/**
* Add this tag to the script: script data-wpfc-render=“false”
*/

class IgnoreSitegroundCache implements IgnorePluginCacheInterface
{
public function isInstalled(): bool
{
return class_exists('SiteGround_Optimizer\Loader\Loader');
}

public function apply(array $handles): void
{
/**
* Ignore Javascript
*/
add_filter('sgo_js_minify_exclude', function (array $scripts) use ($handles) {
assert(is_array($handles[Script::class]));
return $this->applyExcludedHandles($scripts, $handles[Script::class]);

Check warning on line 28 in src/Caching/IgnoreSitegroundCache.php

View check run for this annotation

Codecov / codecov/patch

src/Caching/IgnoreSitegroundCache.php#L28

Added line #L28 was not covered by tests
});

add_filter(
'sgo_javascript_combine_exclude',
function (array $scripts) use ($handles) {
assert(is_array($handles[Script::class]));
return $this->applyExcludedHandles($scripts, $handles[Script::class]);

Check warning on line 35 in src/Caching/IgnoreSitegroundCache.php

View check run for this annotation

Codecov / codecov/patch

src/Caching/IgnoreSitegroundCache.php#L35

Added line #L35 was not covered by tests
}
);

/**
* Ignore Styles
*/
add_filter('sgo_css_minify_exclude', function (array $styles) use ($handles) {
assert(is_array($handles[Style::class]));
return $this->applyExcludedHandles($styles, $handles[Style::class]);

Check warning on line 44 in src/Caching/IgnoreSitegroundCache.php

View check run for this annotation

Codecov / codecov/patch

src/Caching/IgnoreSitegroundCache.php#L44

Added line #L44 was not covered by tests
});
add_filter('sgo_css_combine_exclude', function (array $styles) use ($handles) {
assert(is_array($handles[Style::class]));
return $this->applyExcludedHandles($styles, $handles[Style::class]);

Check warning on line 48 in src/Caching/IgnoreSitegroundCache.php

View check run for this annotation

Codecov / codecov/patch

src/Caching/IgnoreSitegroundCache.php#L48

Added line #L48 was not covered by tests
});
}

protected function applyExcludedHandles(array $excluded, array $toExclude): array
{

return array_merge($excluded, $toExclude);
}
}
51 changes: 51 additions & 0 deletions src/Caching/IgnoreW3TotalCache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

namespace Inpsyde\Assets\Caching;

use Inpsyde\Assets\Script;
use Inpsyde\Assets\Style;

/**
* Check filters
*/

class IgnoreW3TotalCache implements IgnorePluginCacheInterface
{
public function isInstalled(): bool
{
return class_exists('W3TC\Root_Loader');
}

// phpcs:disable Inpsyde.CodeQuality.NestingLevel.High
public function apply(array $handles): void
{
/**
* Ignore Javascript
*/
add_filter('w3tc_minify_js_do_tag_minification', function (bool $doMinification, string $scriptTag) use ($handles) {
assert(is_array($handles[Script::class]));
return $this->determineMinification($doMinification, $scriptTag, $handles[Script::class]);

Check warning on line 29 in src/Caching/IgnoreW3TotalCache.php

View check run for this annotation

Codecov / codecov/patch

src/Caching/IgnoreW3TotalCache.php#L29

Added line #L29 was not covered by tests
}, 10, 2);

/**
* Ignore Styles
*/
add_filter('w3tc_minify_css_do_tag_minification', function (bool $doMinification, string $scriptTag) use ($handles) {
assert(is_array($handles[Style::class]));
return $this->determineMinification($doMinification, $scriptTag, $handles[Style::class]);

Check warning on line 37 in src/Caching/IgnoreW3TotalCache.php

View check run for this annotation

Codecov / codecov/patch

src/Caching/IgnoreW3TotalCache.php#L37

Added line #L37 was not covered by tests
}, 10, 2);
}

protected function determineMinification(bool $doMinification, string $scriptTag, array $handles): bool
{

foreach ($handles as $handle) {
if (strpos($scriptTag, (string)$handle) !== false) {
return false;
}
}
return $doMinification;
}
}
19 changes: 11 additions & 8 deletions src/Loader/AbstractWebpackLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,13 @@
)
);
}
$json = @file_get_contents($resource);

$data = @file_get_contents($resource)
?: ''; // phpcs:ignore
$data = json_decode($data, true);
if ($json === false) {
$json = '';

Check warning on line 74 in src/Loader/AbstractWebpackLoader.php

View check run for this annotation

Codecov / codecov/patch

src/Loader/AbstractWebpackLoader.php#L74

Added line #L74 was not covered by tests
}

$data = json_decode($json, true);
$errorCode = json_last_error();
if (0 < $errorCode) {
throw new InvalidResourceException(
Expand Down Expand Up @@ -183,23 +186,23 @@
*/
protected function resolveLocation(string $fileName): int
{
if (stristr($fileName, '-backend')) {
if (stristr($fileName, '-backend') !== false) {
return Asset::BACKEND;
}

if (stristr($fileName, '-block')) {
if (stristr($fileName, '-block') !== false) {
return Asset::BLOCK_EDITOR_ASSETS;
}

if (stristr($fileName, '-login')) {
if (stristr($fileName, '-login') !== false) {
return Asset::LOGIN;
}

if (stristr($fileName, '-customizer-preview')) {
if (stristr($fileName, '-customizer-preview') !== false) {
return Asset::CUSTOMIZER_PREVIEW;
}

if (stristr($fileName, '-customizer')) {
if (stristr($fileName, '-customizer') !== false) {
return Asset::CUSTOMIZER;
}

Expand Down
2 changes: 1 addition & 1 deletion src/OutputFilter/AsyncStyleOutputFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function __invoke(string $html, Asset $asset): string
{
$url = $asset->url();
$version = $asset->version();
if ($version) {
if ($version !== null && $version !== '') {
$url = add_query_arg('ver', $version, $url);
}

Expand Down
2 changes: 1 addition & 1 deletion src/OutputFilter/InlineAssetOutputFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public function __invoke(string $html, Asset $asset): string
}

$content = @file_get_contents($filePath);
if (! $content) {
if ($content === false) {
return $html;
}

Expand Down
3 changes: 1 addition & 2 deletions src/Script.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

namespace Inpsyde\Assets;

use Inpsyde\Assets\Handler\AssetHandler;
use Inpsyde\Assets\Handler\ScriptHandler;

class Script extends BaseAsset implements Asset
Expand Down Expand Up @@ -260,7 +259,7 @@ protected function resolveDependencyExtractionPlugin(): bool
$version = $data['version'] ?? null;

$this->withDependencies(...$dependencies);
if (!$this->version && $version) {
if (is_null($this->version) && !is_null($version)) {
$this->withVersion($version);
}

Expand Down
3 changes: 1 addition & 2 deletions src/Style.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

namespace Inpsyde\Assets;

use Inpsyde\Assets\Handler\AssetHandler;
use Inpsyde\Assets\Handler\StyleHandler;
use Inpsyde\Assets\OutputFilter\AsyncStyleOutputFilter;

Expand Down Expand Up @@ -73,7 +72,7 @@ public function inlineStyles(): ?array
*/
public function withInlineStyles(string $inline): Style
{
if (!$this->inlineStyles) {
if (!is_array($this->inlineStyles)) {
$this->inlineStyles = [];
}

Expand Down
Loading
Loading