silverstripe-webpack/site/code/WebpackTemplateProvider.php

99 lines
2.2 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
*/
class WebpackTemplateProvider extends Object implements TemplateGlobalProvider
{
/**
* @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()
{
$class = __CLASS__;
return Director::isDev() && !!@fsockopen(
2018-02-22 14:39:58 +01:00
$class::config()->get('HOSTNAME'),
$class::config()->get('PORT')
);
}
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)
{
$class = __CLASS__;
return sprintf(
2018-02-07 05:29:20 +01:00
'%s%s:%s/%s',
Director::protocol(),
2018-02-22 14:39:58 +01:00
$class::config()->get('HOSTNAME'),
$class::config()->get('PORT'),
basename($path)
2018-02-05 12:11:01 +01:00
);
}
protected static function _toPublicPath($path)
{
$class = __CLASS__;
2018-02-22 14:39:58 +01:00
return strpos($path,'//') === false ?
Controller::join_links(
$class::config()->get('DIST'),
(strpos($path,'.css') ? 'css' : 'js' ),
$path
)
: $path;
2018-02-05 12:11:01 +01:00
}
}