Skip to content

Commit

Permalink
Allow multiple page cache
Browse files Browse the repository at this point in the history
  • Loading branch information
Spomky committed Mar 9, 2024
1 parent d051583 commit baeacfb
Show file tree
Hide file tree
Showing 9 changed files with 198 additions and 120 deletions.
54 changes: 54 additions & 0 deletions assets/src/installation-status_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
'use strict';

import { Controller } from '@hotwired/stimulus';

/* stimulusFetch: 'lazy' */
export default class extends Controller {
static targets = ['message', 'attribute'];
static values = {
installedMessage: { type: String, default: 'The application is installed' },
notInstalledMessage: { type: String, default: 'The application is not installed' },
};

connect = () => {
console.log(window.matchMedia('(display-mode: standalone)').matches)
this.dispatchEvent('connect', {});
if (navigator.onLine) {
this.statusChanged({
status: 'ONLINE',
message: this.onlineMessageValue,
});
} else {
this.statusChanged({
status: 'OFFLINE',
message: this.offlineMessageValue,
});
}

window.addEventListener('online', () => {
this.statusChanged({
status: 'ONLINE',
message: this.onlineMessageValue,
});
});
window.addEventListener('offline', () => {
this.statusChanged({
status: 'OFFLINE',
message: this.offlineMessageValue,
});
});
}
dispatchEvent = (name, payload) => {
this.dispatch(name, { detail: payload, prefix: 'connection-status' });
}

statusChanged = (data) => {
this.messageTargets.forEach((element) => {
element.innerHTML = data.message;
});
this.attributeTargets.forEach((element) => {
element.setAttribute('data-connection-status', data.status);
});
this.dispatchEvent('status-changed', { detail: data });
}
}
2 changes: 1 addition & 1 deletion src/Command/ListCacheStrategiesCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$strategy->urlPattern,
$strategy->enabled ? 'Yes' : 'No',
$strategy->requireWorkbox ? 'Yes' : 'No',
Yaml::dump($strategy->options),
'', //Yaml::dump($strategy->options),
]);
}
}
Expand Down
6 changes: 2 additions & 4 deletions src/Dto/PageCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@

final class PageCache
{
public bool $enabled = true;

#[SerializedName('cache_name')]
public string $cacheName = 'pages';
public string $cacheName;

Check failure on line 12 in src/Dto/PageCache.php

View workflow job for this annotation

GitHub Actions / PHP 8.3 Test on ubuntu-latest

Class SpomkyLabs\PwaBundle\Dto\PageCache has an uninitialized property $cacheName. Give it default value or assign it in the constructor.

#[SerializedName('regex')]
public string $regex = '/\.(ico|png|jpe?g|gif|svg|webp|bmp)$/';
public string $regex;

Check failure on line 15 in src/Dto/PageCache.php

View workflow job for this annotation

GitHub Actions / PHP 8.3 Test on ubuntu-latest

Class SpomkyLabs\PwaBundle\Dto\PageCache has an uninitialized property $regex. Give it default value or assign it in the constructor.

#[SerializedName('network_timeout')]
public int $networkTimeout = 3;
Expand Down
7 changes: 5 additions & 2 deletions src/Dto/Workbox.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,11 @@ final class Workbox
#[SerializedName('font_cache')]
public FontCache $fontCache;

#[SerializedName('page_cache')]
public PageCache $pageCache;
/**
* @var array<PageCache>
*/
#[SerializedName('page_caches')]
public array $pageCaches;

Check failure on line 34 in src/Dto/Workbox.php

View workflow job for this annotation

GitHub Actions / PHP 8.3 Test on ubuntu-latest

Class SpomkyLabs\PwaBundle\Dto\Workbox has an uninitialized property $pageCaches. Give it default value or assign it in the constructor.

#[SerializedName('asset_cache')]
public AssetCache $assetCache;
Expand Down
136 changes: 73 additions & 63 deletions src/Resources/config/definition/service_worker.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,11 @@
->beforeNormalization()
->ifTrue(static fn (mixed $v): bool => true)
->then(static function (mixed $v): array {
if (isset($v['page_cache'])) {
if (isset($v['page_caches'])) {

Check failure on line 100 in src/Resources/config/definition/service_worker.php

View workflow job for this annotation

GitHub Actions / PHP 8.3 Test on ubuntu-latest

Cannot access offset 'page_caches' on mixed.
return $v;
}
$v['page_cache'] = array_filter([
'enabled' => true,
$v['page_caches'] = [];

Check failure on line 103 in src/Resources/config/definition/service_worker.php

View workflow job for this annotation

GitHub Actions / PHP 8.3 Test on ubuntu-latest

Cannot access offset 'page_caches' on mixed.
$v['page_caches'][] = array_filter([
'cache_name' => $v['page_cache_name'] ?? 'pages',
'network_timeout' => $v['network_timeout_seconds'] ?? 3,
'urls' => $v['warm_cache_urls'] ?? [],
Expand Down Expand Up @@ -281,64 +281,74 @@
->end()
->end()
->end()
->arrayNode('page_cache')
->canBeDisabled()
->children()
->scalarNode('cache_name')
->defaultValue('pages')
->info('The name of the page cache.')
->end()
->integerNode('network_timeout')
->defaultValue(3)
->info(
'The network timeout in seconds before cache is called (for warm cache URLs only).'
)
->example([1, 2, 5])
->end()
->scalarNode('strategy')
->defaultValue('networkFirst')
->info(
'The caching strategy. Only "networkFirst" and "staleWhileRevalidate" are supported.'
)
->example(['networkFirst', 'staleWhileRevalidate'])
->end()
->booleanNode('broadcast')
->defaultFalse()
->info(
'Whether to broadcast the cache update events. Only supported with "staleWhileRevalidate" strategy.'
)
->end()
->arrayNode('broadcast_headers')
->treatNullLike(['Content-Length', 'ETag', 'Last-Modified'])
->treatFalseLike(['Content-Length', 'ETag', 'Last-Modified'])
->treatTrueLike(['Content-Length', 'ETag', 'Last-Modified'])
->defaultValue(['Content-Length', 'ETag', 'Last-Modified'])
->scalarPrototype()->end()
->end()
->arrayNode('urls')
->treatNullLike([])
->treatFalseLike([])
->treatTrueLike([])
->info('The URLs to warm the cache. The URLs shall be served by the application.')
->arrayPrototype()
->beforeNormalization()
->ifString()
->then(static fn (string $v): array => [
'path' => $v,
])
->end()
->children()
->scalarNode('path')
->isRequired()
->info('The URL of the shortcut.')
->example('app_homepage')
->arrayNode('page_caches')
->treatNullLike([])
->treatFalseLike([])
->treatTrueLike([])
->arrayPrototype()
->children()
->scalarNode('regex')
->isRequired()
->info('The regex to match the URLs.')
->end()
->scalarNode('cache_name')
->isRequired()
->info('The name of the page cache.')
->end()
->integerNode('network_timeout')
->defaultValue(3)
->info(
'The network timeout in seconds before cache is called (for "networkFirst" strategy only).'
)
->example([1, 2, 5])
->end()
->scalarNode('strategy')
->defaultValue('networkFirst')
->info(
'The caching strategy. Only "networkFirst" and "staleWhileRevalidate" are supported.'
)
->example(['networkFirst', 'staleWhileRevalidate'])
->end()
->booleanNode('broadcast')
->defaultFalse()
->info(
'Whether to broadcast the cache update events (for "staleWhileRevalidate" strategy only).'
)
->end()
->arrayNode('broadcast_headers')
->treatNullLike(['Content-Length', 'ETag', 'Last-Modified'])
->treatFalseLike(['Content-Length', 'ETag', 'Last-Modified'])
->treatTrueLike(['Content-Length', 'ETag', 'Last-Modified'])
->defaultValue(['Content-Length', 'ETag', 'Last-Modified'])
->scalarPrototype()->end()
->end()
->arrayNode('urls')
->treatNullLike([])
->treatFalseLike([])
->treatTrueLike([])
->info(
'The URLs to warm the cache. The URLs shall be served by the application.'
)
->arrayPrototype()
->beforeNormalization()
->ifString()
->then(static fn (string $v): array => [
'path' => $v,
])
->end()
->arrayNode('params')
->treatFalseLike([])
->treatTrueLike([])
->treatNullLike([])
->prototype('variable')->end()
->info('The parameters of the action.')
->children()
->scalarNode('path')
->isRequired()
->info('The URL of the shortcut.')
->example('app_homepage')
->end()
->arrayNode('params')
->treatFalseLike([])
->treatTrueLike([])
->treatNullLike([])
->prototype('variable')->end()
->info('The parameters of the action.')
->end()
->end()
->end()
->end()
Expand Down Expand Up @@ -409,7 +419,7 @@
->setDeprecated(
'spomky-labs/phpwa',
'1.1.0',
'The "%node%" option is deprecated and will be removed in 2.0.0. Please use "pwa.serviceworker.workbox.page_cache.cache_name" instead.'
'The "%node%" option is deprecated and will be removed in 2.0.0. Please use "pwa.serviceworker.workbox.page_caches[].cache_name" instead.'
)
->end()
->scalarNode('asset_cache_name')
Expand Down Expand Up @@ -501,7 +511,7 @@
->setDeprecated(
'spomky-labs/phpwa',
'1.1.0',
'The "%node%" option is deprecated and will be removed in 2.0.0. Please use "pwa.serviceworker.workbox.page_cache.network_timeout" instead.'
'The "%node%" option is deprecated and will be removed in 2.0.0. Please use "pwa.serviceworker.workbox.page_caches[].network_timeout" instead.'
)
->end()
->arrayNode('warm_cache_urls')
Expand All @@ -512,7 +522,7 @@
->setDeprecated(
'spomky-labs/phpwa',
'1.1.0',
'The "%node%" option is deprecated and will be removed in 2.0.0. Please use "pwa.serviceworker.workbox.page_cache.urls" instead.'
'The "%node%" option is deprecated and will be removed in 2.0.0. Please use "pwa.serviceworker.workbox.page_caches[].urls" instead.'
)
->arrayPrototype()
->beforeNormalization()
Expand Down
4 changes: 2 additions & 2 deletions src/Service/Rule/AssetCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function process(string $body): string
$assetUrlsLength = count($assets) * 2;

$declaration = <<<ASSET_CACHE_RULE_STRATEGY
const assetCacheStrategy = new workbox.strategies.CacheFirst({
const assetCacheStrategy = new workbox.strategies.CacheOnly({
cacheName: '{$this->workbox->assetCache->cacheName}',
plugins: [
new workbox.cacheableResponse.CacheableResponsePlugin({statuses: [0, 200]}),
Expand Down Expand Up @@ -103,7 +103,7 @@ public function getCacheStrategies(): array
return [
CacheStrategy::create(
$this->workbox->assetCache->cacheName,
CacheStrategy::STRATEGY_CACHE_FIRST,
CacheStrategy::STRATEGY_CACHE_ONLY,
sprintf("'({url}) => url.pathname.startsWith('%s')'", $this->assetPublicPrefix),
$this->workbox->enabled && $this->workbox->assetCache->enabled,
true,
Expand Down
5 changes: 1 addition & 4 deletions src/Service/Rule/BackgroundSync.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,12 @@ public function getCacheStrategies(): array
$strategies = [];
foreach ($this->workbox->backgroundSync as $sync) {
$strategies[] = CacheStrategy::create(
'---',
'BackgroundSync API',
CacheStrategy::STRATEGY_NETWORK_ONLY,
$sync->regex,
$this->workbox->enabled,
true,
[
'maxTimeout' => 0,
'maxAge' => 0,
'maxEntries' => 0,
'plugins' => [
sprintf('backgroundSync: "%s"', $sync->queueName),
sprintf('broadcastChannel: "%s"', $sync->broadcastChannel ?? '---'),
Expand Down
6 changes: 5 additions & 1 deletion src/Service/Rule/GoogleFontCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,11 @@ public function getCacheStrategies(): array
'workbox.recipes.googleFontsCache',
'Google Fonts Cache',
$this->workbox->enabled && $this->workbox->googleFontCache->enabled,
$this->workbox->googleFontCache->enabled
$this->workbox->googleFontCache->enabled,
[

Check failure on line 81 in src/Service/Rule/GoogleFontCache.php

View workflow job for this annotation

GitHub Actions / PHP 8.3 Test on ubuntu-latest

Parameter #6 $options of static method SpomkyLabs\PwaBundle\Service\CacheStrategy::create() expects array{maxTimeout?: int, maxAge?: int, maxEntries?: int, warmUrls?: array<string>, plugins?: array<string>}, array{maxAge: int|null, maxEntries: int|null} given.
'maxAge' => $this->workbox->googleFontCache->maxAge,
'maxEntries' => $this->workbox->googleFontCache->maxEntries,
]
),
];
}
Expand Down
Loading

0 comments on commit baeacfb

Please sign in to comment.