silverstripe-progressivewebapp/src/Controllers/ServiceWorkerController.php

106 lines
2.5 KiB
PHP
Raw Normal View History

2018-07-04 12:36:46 +02:00
<?php
2020-04-01 21:42:13 +02:00
namespace A2nt\ProgressiveWebApp\Controllers;
2018-07-04 12:36:46 +02:00
use SilverStripe\Control\Controller;
2018-07-08 10:55:43 +02:00
use SilverStripe\Control\Director;
use SilverStripe\ORM\ArrayList;
use SilverStripe\View\ArrayData;
use SilverStripe\Core\ClassInfo;
use MichelSteege\ProgressiveWebApp\Interfaces\ServiceWorkerCacheProvider;
2018-07-04 12:36:46 +02:00
class ServiceWorkerController extends Controller {
/**
* @var array
*/
private static $allowed_actions = [
2020-04-02 01:41:49 +02:00
'index',
2018-07-04 12:36:46 +02:00
];
2020-04-01 21:42:13 +02:00
2018-07-08 10:55:43 +02:00
/**
* @config
*/
2018-08-02 08:46:31 +02:00
private static $debug_mode = false;
2020-04-02 01:41:49 +02:00
private static $version = '1';
2018-07-04 12:36:46 +02:00
/**
* Default controller action for the service-worker.js file
*
* @return mixed
*/
2020-04-02 01:41:49 +02:00
public function index($req) {
$resp = $this->getResponse();
$script = file_get_contents(self::getScriptPath());
if($req->param('Action') === 'cachequeue') {
return json_encode([
'urls' => [
self::join_links(self::BaseUrl(),'app','client','dist','app.js')
]
]);
}
$resp->addHeader('Content-Type', 'application/javascript; charset="utf-8"');
return $this->customise([
'Script' => $script,
])->renderWith('ServiceWorker');
}
private static function getScriptPath()
{
return join(DIRECTORY_SEPARATOR, [
__DIR__,
'..',
'..',
'client',
'dist',
'sw.js',
]);
2018-07-04 12:36:46 +02:00
}
2020-04-01 21:42:13 +02:00
2018-07-08 10:55:43 +02:00
/**
* Base URL
* @return varchar
*/
2020-04-02 01:41:49 +02:00
public static function BaseUrl() {
return Director::absoluteBaseURL();
2018-07-08 10:55:43 +02:00
}
2020-04-01 21:42:13 +02:00
2018-07-08 10:55:43 +02:00
/**
* Debug mode
* @return bool
*/
public function DebugMode() {
if(Director::isDev()){
return true;
}
return $this->config()->get('debug_mode');
}
2020-04-01 21:42:13 +02:00
2020-04-02 01:41:49 +02:00
public function Version() {
return $this->config()->get('version').filemtime(self::getScriptPath());
}
2018-07-08 10:55:43 +02:00
/**
* A list with file to cache in the install event
* @return ArrayList
*/
public function CacheOnInstall() {
$paths = [];
foreach(ClassInfo::implementorsOf(ServiceWorkerCacheProvider::class) as $class){
foreach($class::getServiceWorkerCachedPaths() as $path){
$paths[] = $path;
}
}
$list = new ArrayList();
foreach($paths as $path){
$list->push(new ArrayData([
'Path' => $path
]));
}
return $list;
}
2018-07-04 12:36:46 +02:00
}