Skip to content
This repository has been archived by the owner on Jul 25, 2023. It is now read-only.

Commit

Permalink
Merge branch 'release/v2.0.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
tgerulaitis committed Jun 20, 2017
2 parents c691c61 + 62c71c5 commit fdfbcdd
Show file tree
Hide file tree
Showing 16 changed files with 554 additions and 177 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "meanbee/magento2-serviceworker",
"description": "A Magento 2 extension that adds Service Worker support.",
"type": "magento2-module",
"version": "1.1.0",
"version": "2.0.0",
"license": [
"MIT"
],
Expand Down
7 changes: 6 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{
"name": "@meanbee/magento2-serviceworker",
"version": "1.1.0",
"version": "2.0.0",
"description": "A Magento 2 extension that adds Service Worker support.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build:clean": "rm -rf src/view/frontend/web/js/lib/*",
"build:copy": "find node_modules/workbox-google-analytics -name 'workbox-google-analytics.prod.*' -exec install -t src/view/frontend/web/js/lib {} +",
"build:copy": "find node_modules -path '*/importScripts/*' -name '*.prod.*' -exec install -t src/view/frontend/web/js/lib {} +",
"build": "npm run build:clean && npm run build:copy"
},
"repository": {
Expand All @@ -20,6 +20,7 @@
},
"homepage": "https://github.com/meanbee/magento2-serviceworker#readme",
"dependencies": {
"workbox-google-analytics": "^1.0.0"
"workbox-google-analytics": "^1.0.0",
"workbox-sw": "^1.0.1"
}
}
31 changes: 31 additions & 0 deletions src/Block/Adminhtml/Form/Field/CachingStrategy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Meanbee\ServiceWorker\Block\Adminhtml\Form\Field;

use \Magento\Framework\View\Element;

class CachingStrategy extends Element\Html\Select
{

public function __construct(
Element\Context $context,
\Meanbee\ServiceWorker\Model\Config\Source\CachingStrategy $optionsProvider,
array $data = []
) {
parent::__construct($context, $data);

$this->setOptions($optionsProvider->toOptionArray());
}

/**
* Set the input element name.
*
* @param string $name
*
* @return $this
*/
public function setInputName($name)
{
return $this->setName($name);
}
}
58 changes: 58 additions & 0 deletions src/Block/Adminhtml/Form/Field/CustomStrategies.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

namespace Meanbee\ServiceWorker\Block\Adminhtml\Form\Field;

class CustomStrategies extends \Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray
{
/** @var CachingStrategy */
protected $strategyRenderer;

/**
* @inheritdoc
*/
protected function _prepareToRender()
{
$this->addColumn("path", [
"label" => __("URL Path"),
]);

$this->addColumn("strategy", [
"label" => __("Strategy"),
"renderer" => $this->getStrategyRenderer(),
]);

$this->_addAfter = false;
}

/**
* @inheritdoc
*/
protected function _prepareArrayRow(\Magento\Framework\DataObject $row)
{
$optionName = sprintf("option_%s", $this->getStrategyRenderer()->calcOptionHash($row->getData("strategy")));

$row->setData("option_extra_attrs", [
$optionName => 'selected="selected"',
]);
}

/**
* Get the caching strategy input field renderer.
*
* @return CachingStrategy
*/
protected function getStrategyRenderer()
{
if (!$this->strategyRenderer) {
$this->strategyRenderer = $this->getLayout()->createBlock(
CachingStrategy::class,
"",
["data" => [
"is_render_to_js_template" => true,
]]
);
}

return $this->strategyRenderer;
}
}
50 changes: 38 additions & 12 deletions src/Block/Js.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,36 @@ class Js extends \Magento\Framework\View\Element\Template
/** @var \Meanbee\ServiceWorker\Helper\Config $config */
protected $config;

/** @var \Magento\Framework\Json\Helper\Data $jsonHelper */
protected $jsonHelper;

public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Meanbee\ServiceWorker\Helper\Config $config,
\Magento\Framework\Json\Helper\Data $jsonHelper,
array $data
) {
$this->config = $config;

$this->jsonHelper = $jsonHelper;

$data["cache_lifetime"] = 60 * 60 * 24 * 365;

parent::__construct($context, $data);
}

/**
* Get the provided data encoded as a JSON object.
*
* @param mixed $data
*
* @return string
*/
public function jsonEncode($data)
{
return $this->jsonHelper->jsonEncode($data);
}

/**
* Get the service worker version string.
*
Expand All @@ -45,32 +63,40 @@ public function getOfflinePageUrl()
}

/**
* Get the list of URLs unavailable for caching or viewing offline.
* Get the list of URLs for external scripts to import into the service worker.
*
* @return array
* @return string[]
*/
public function getUrlBlacklist()
public function getExternalScriptUrls()
{
return $this->config->getUrlBlacklist();
$scripts = [
$this->getViewFileUrl("Meanbee_ServiceWorker::js/lib/workbox-sw.prod.v1.0.1.js"),
];

if ($this->isGaOfflineEnabled()) {
$scripts[] = $this->getViewFileUrl("Meanbee_ServiceWorker::js/lib/workbox-google-analytics.prod.v1.0.0.js");
}

return array_filter($scripts);
}

/**
* Check if Offline Google Analytics features are enabled.
* Get the configured paths with custom caching strategies.
*
* @return bool
* @return \array[]
*/
public function isGaOfflineEnabled()
public function getCustomStrategies()
{
return $this->config->isGaOfflineEnabled();
return $this->config->getCustomStrategies();
}

/**
* Get the URL to the Offline Google Analytics helper script.
* Check if Offline Google Analytics features are enabled.
*
* @return string
* @return bool
*/
public function getGaJsUrl()
public function isGaOfflineEnabled()
{
return $this->getViewFileUrl("Meanbee_ServiceWorker::js/lib/workbox-google-analytics.prod.v1.0.0.js");
return $this->config->isGaOfflineEnabled();
}
}
47 changes: 24 additions & 23 deletions src/Helper/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class Config extends \Magento\Framework\App\Helper\AbstractHelper
{
const XML_PATH_ENABLE = "web/serviceworker/enable";
const XML_PATH_OFFLINE_PAGE = "web/serviceworker/offline_page";
const XML_PATH_URL_BLACKLIST = "web/serviceworker/url_blacklist";
const XML_PATH_CUSTOM_STRATEGIES = "web/serviceworker/custom_strategies";
const XML_PATH_GA_OFFLINE_ENABLE = "web/serviceworker/ga_offline_enable";

const PATH_WILDCARD_SYMBOL = "*";
Expand Down Expand Up @@ -54,33 +54,34 @@ public function getOfflinePageUrl()
}

/**
* Get the list of URLs blacklisted from cache.
* Get the configured paths with custom caching strategies.
*
* @return array
* @param string $store
*
* @return array[]
*/
public function getUrlBlacklist()
public function getCustomStrategies($store = null)
{
$base_url = $this->_urlBuilder->getBaseUrl();

$paths = array_filter(array_map(
"trim",
explode("\n", $this->scopeConfig->getValue(static::XML_PATH_URL_BLACKLIST, ScopeInterface::SCOPE_STORE))
));

$data = [
"full_match" => [],
"prefix_match" => [],
];

foreach ($paths as $path) {
if (substr($path, -1) == static::PATH_WILDCARD_SYMBOL) {
$data["prefix_match"][] = $base_url . substr($path, 0, -1);
} else {
$data["full_match"][] = $base_url . $path;
}
$custom_strategies = $this->scopeConfig->getValue(static::XML_PATH_CUSTOM_STRATEGIES, ScopeInterface::SCOPE_STORE, $store);

if (is_string($custom_strategies) && !empty($custom_strategies)) {
$custom_strategies = unserialize($custom_strategies);
}

if (!is_array($custom_strategies)) {
return [];
}

return $data;
$base_url = $this->_urlBuilder->getBaseUrl(["_scope" => $store]);

array_walk($custom_strategies, function (&$item) use ($base_url) {
$item["path"] = $base_url . $item["path"];
});

// Reset indexes to allow encoding as JSON array
$custom_strategies = array_values($custom_strategies);

return $custom_strategies;
}

/**
Expand Down
41 changes: 41 additions & 0 deletions src/Model/Config/Source/CachingStrategy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace Meanbee\ServiceWorker\Model\Config\Source;

class CachingStrategy implements \Magento\Framework\Option\ArrayInterface
{
const CACHE_FIRST = "cacheFirst";
const NETWORK_FIRST = "networkFirst";
const NETWORK_ONLY = "networkOnly";

/**
* Get options in "key-value" format
*
* @return string[]
*/
public function toArray()
{
return [
static::CACHE_FIRST => __("Cache First"),
static::NETWORK_FIRST => __("Network First"),
static::NETWORK_ONLY => __("Network Only"),
];
}

/**
* @inheritdoc
*/
public function toOptionArray()
{
$options = $this->toArray();

array_walk($options, function (&$value, $key) {
$value = [
"value" => $key,
"label" => $value,
];
});

return $options;
}
}
22 changes: 21 additions & 1 deletion src/Setup/InstallData.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Store\Model\Store;
use Meanbee\ServiceWorker\Model\Config\Source\CachingStrategy;

class InstallData implements InstallDataInterface
{
Expand All @@ -17,12 +18,17 @@ class InstallData implements InstallDataInterface
/** @var \Magento\Cms\Model\PageRepository $pageRepository */
protected $pageRepository;

/** @var \Magento\Framework\App\Config\Storage\WriterInterface $configWriter */
protected $configWriter;

public function __construct(
\Magento\Cms\Model\PageFactory $pageFactory,
\Magento\Cms\Model\PageRepository $pageRepository
\Magento\Cms\Model\PageRepository $pageRepository,
\Magento\Framework\App\Config\Storage\WriterInterface $configWriter
) {
$this->pageFactory = $pageFactory;
$this->pageRepository = $pageRepository;
$this->configWriter = $configWriter;
}

/**
Expand Down Expand Up @@ -57,6 +63,20 @@ public function install(ModuleDataSetupInterface $setup, ModuleContextInterface
$this->pageRepository->save($page);
}

/**
* Add custom strategies
*/
$strategies = [
["path" => "checkout/", "strategy" => CachingStrategy::NETWORK_ONLY],
["path" => "customer/account/create*", "strategy" => CachingStrategy::NETWORK_ONLY],
["path" => "checkout/account/login*", "strategy" => CachingStrategy::NETWORK_ONLY],
];

$this->configWriter->save(
"web/serviceworker/custom_strategies",
serialize($strategies)
);

$setup->endSetup();
}

Expand Down
Loading

0 comments on commit fdfbcdd

Please sign in to comment.