You are here

function _pwa_serviceworker_file in Progressive Web App 7

Same name and namespace in other branches
  1. 7.2 pwa.module \_pwa_serviceworker_file()

Take the serviceworker template file and replace all the variables needed.

Return value

string

2 calls to _pwa_serviceworker_file()
pwa_flush_caches in ./pwa.module
Implements hook_flush_caches().
pwa_serviceworker_file_data in ./pwa.pages.inc
Returns the JS of the service worker.

File

./pwa.module, line 184

Code

function _pwa_serviceworker_file() {
  $path = drupal_get_path('module', 'pwa');
  $sw = file_get_contents($path . '/js/serviceworker.js');
  $cacheUrls = (array) preg_split("/\r\n|\n|\r/", trim(variable_get('pwa_sw_cache_urls', '')));

  // Get icons list and convert into array of sources.
  $manifest = _pwa_manifest_data();
  $cacheIcons = [];
  foreach ($manifest['icons'] as $icon) {
    $cacheIcons[] = $icon['src'];
  }

  // Combine URLs from admin UI with manifest icons.
  $cacheWhitelist = array_merge($cacheUrls, $cacheIcons);

  // Turn all the paths into fully-qualified URLs.
  foreach ($cacheWhitelist as &$url) {
    $url = url($url);
  }
  foreach ($cacheUrls as &$url) {
    $url = url($url);
  }

  // Look up module release from package info.
  $pwa_module_info = system_get_info('module', 'pwa');
  $pwa_module_version = $pwa_module_info['version'];

  // Packaging script will always provide the published module version. Checking
  // for NULL is only so maintainers have something predictable to test against.
  if ($pwa_module_version == null) {
    $pwa_module_version = '7.x-1.x-dev';
  }

  // Set up placeholders.
  $replace = [
    '[/*cacheConditionsExclude*/]' => drupal_json_encode((array) preg_split("/\r\n|\n|\r/", trim(variable_get('pwa_sw_cache_exclude', '[\'' . PWA_MODULE_ACTIVE_ROUTE . '\']')))),
    '[/*cacheUrls*/]' => drupal_json_encode($cacheWhitelist),
    '[/*cacheUrlsAssets*/]' => drupal_json_encode((array) _pwa_fetch_offline_page_resources($cacheUrls)),
    '1/*cacheVersion*/' => '\'' . $pwa_module_version . '-v' . variable_get('pwa_sw_cache_version', 1) . '\'',
    '/offline' => url('/offline'),
    'offline-image.png' => file_create_url(drupal_get_path('module', 'pwa') . '/assets/offline-image.png'),
  ];

  // Fill placeholders and return final file.
  return str_replace(array_keys($replace), array_values($replace), $sw);
}