silverstripe-webpack/site/code/templates/WebpackTemplateProvider.php

104 lines
2.4 KiB
PHP
Raw Normal View History

2018-02-05 12:11:01 +01:00
<?php
/**
* Directs assets requests to Webpack server or to static files
*/
2018-03-24 11:45:31 +01:00
use SilverStripe\View\TemplateGlobalProvider;
use SilverStripe\View\Requirements;
use SilverStripe\Control\Director;
use SilverStripe\Control\Controller;
use SilverStripe\Core\Config\Config;
class WebpackTemplateProvider implements TemplateGlobalProvider
2018-02-05 12:11:01 +01:00
{
/**
* @var int port number
*/
private static $port = 3000;
/**
* @var string host name
*/
private static $hostname = 'localhost';
/**
* @var string assets static files directory
*/
2018-02-22 14:39:58 +01:00
private static $dist = 'site/dist';
/**
* @return array
*/
public static function get_template_global_variables()
{
return [
'WebpackDevServer' => 'isActive',
'WebpackCSS' => 'loadCSS',
'WebpackJS' => 'loadJS',
];
}
2018-02-05 12:11:01 +01:00
/**
* Load CSS file
* @param $path
*/
public static function loadCSS($path)
{
2018-02-22 14:39:58 +01:00
Requirements::css(self::_getPath($path));
2018-02-05 12:11:01 +01:00
}
/**
* Load JS file
* @param $path
*/
public static function loadJS($path)
{
2018-02-22 14:39:58 +01:00
Requirements::javascript(self::_getPath($path));
2018-02-05 12:11:01 +01:00
}
/**
* Checks if dev mode is enabled and if webpack server is online
* @return bool
*/
public static function isActive()
{
return Director::isDev() && !!@fsockopen(
2018-03-24 11:45:31 +01:00
Config::inst()->get(__CLASS__,'HOSTNAME'),
Config::inst()->get(__CLASS__,'PORT')
2018-02-22 14:39:58 +01:00
);
}
protected static function _getPath($path)
{
return self::isActive() && strpos($path,'//') === false ?
self::_toDevServerPath($path) :
self::_toPublicPath($path);
2018-02-05 12:11:01 +01:00
}
protected static function _toDevServerPath($path)
{
2018-03-24 11:45:31 +01:00
$path = stripos($path,'css') ? 'site/client/css/'.$path : 'site/client/js/'.$path;
2018-02-05 12:11:01 +01:00
return sprintf(
2018-02-07 05:29:20 +01:00
'%s%s:%s/%s',
Director::protocol(),
2018-03-24 11:45:31 +01:00
Config::inst()->get(__CLASS__,'HOSTNAME'),
Config::inst()->get(__CLASS__,'PORT'),
2018-02-22 14:39:58 +01:00
basename($path)
2018-02-05 12:11:01 +01:00
);
}
protected static function _toPublicPath($path)
{
2018-02-22 14:39:58 +01:00
return strpos($path,'//') === false ?
Controller::join_links(
2018-03-24 11:45:31 +01:00
Config::inst()->get(__CLASS__,'DIST'),
2018-02-22 14:39:58 +01:00
(strpos($path,'.css') ? 'css' : 'js' ),
$path
)
: $path;
2018-02-05 12:11:01 +01:00
}
}