class Requirements_Backend (View source)

Traits

A class that can be instantiated or replaced via DI

Properties

static private bool $combine_in_dev

Determine if files should be combined automatically on dev mode.

bool $writeJavascriptToBody

Put all JavaScript includes at the bottom of the template before the closing <body> tag, rather than the default behaviour of placing them at the end of the <head> tag. This means script downloads won't block other HTTP requests, which can be a performance improvement.

static private string $default_combined_files_folder

Configures the default prefix for combined files.

static private bool $combine_hash_querystring

Flag to include the hash in the querystring instead of the filename for combined files.

Methods

static Injectable
create(array ...$args)

An implementation of the factory method, allows you to create an instance of a class

static Injectable
singleton(string $class = null)

Creates a class instance by the "singleton" design pattern.

getAssetHandler()

Gets the backend storage for generated files

setAssetHandler(GeneratedAssetHandler $handler)

Set a new asset handler for this backend

getMinifier() deprecated

Gets the minification service for this backend

setMinifier(Requirements_Minifier $minifier = null)

Set a new minification service for this backend

setCombinedFilesEnabled(bool $enable)

Enable or disable the combination of CSS and JavaScript files

bool
getWriteHeaderComment()

Check if header comments are written

$this
setWriteHeaderComment(bool $write)

Flag whether header comments should be written for each combined file

setCombinedFilesFolder(string $folder)

Set the folder to save combined files in. By default they're placed in _combinedfiles, however this may be an issue depending on your setup, especially for CSS files which often contain relative paths.

string
getCombinedFilesFolder()

Retrieve the combined files folder prefix

setSuffixRequirements($var)

Set whether to add caching query params to the requests for file-based requirements.

bool
getSuffixRequirements()

Check whether we want to suffix requirements

$this
setWriteJavascriptToBody($var)

Set whether you want to write the JS to the body of the page rather than at the end of the head tag.

bool
getWriteJavascriptToBody()

Check whether you want to write the JS to the body of the page rather than at the end of the head tag.

$this
setForceJSToBottom($var)

Forces the JavaScript requirements to the end of the body, right before the closing tag

bool
getForceJSToBottom()

Check if the JavaScript requirements are written to the end of the body, right before the closing tag

bool
getMinifyCombinedFiles()

Check if minify files should be combined

$this
setMinifyCombinedFiles(bool $minify)

Set if combined files should be minified

javascript(string $file, array $options = array())

Register the given JavaScript file as required.

array
getProvidedScripts()

Gets all scripts that are already provided by prior scripts.

array
getJavascript()

Returns an array of required JavaScript, excluding blocked and duplicates of provided files.

customScript(string $script, string $uniquenessID = null)

Register the given JavaScript code into the list of requirements

array
getCustomScripts()

Return all registered custom scripts

customCSS(string $script, string $uniquenessID = null)

Register the given CSS styles into the list of requirements

array
getCustomCSS()

Return all registered custom CSS

insertHeadTags(string $html, string $uniquenessID = null)

Add the following custom HTML code to the <head> section of the page

array
getCustomHeadTags()

Return all custom head tags

javascriptTemplate(string $file, string[] $vars, string $uniquenessID = null)

Include the content of the given JavaScript file in the list of requirements. Dollar-sign variables will be interpolated with values from $vars similar to a .ss template.

css(string $file, string $media = null, array $options = [])

Register the given stylesheet into the list of requirements.

array
getCSS()

Get the list of registered CSS file requirements, excluding blocked files

array
getBlocked()

Gets the list of all blocked files

clear(string|int $fileOrID = null)

Clear either a single or all requirements

restore()

Restore requirements cleared by call to Requirements::clear

block(string|int $fileOrID)

Block inclusion of a specific file

unblock(string|int $fileOrID)

Remove an item from the block list

unblockAll()

Removes all items from the block list

string
includeInHTML(string $content)

Update the given HTML content with the appropriate include tags for the registered requirements. Needs to receive a valid HTML/XHTML template in the $content parameter, including a head and body tag.

includeInResponse(HTTPResponse $response)

Attach requirements inclusion to X-Include-JS and X-Include-CSS headers on the given HTTP Response

array|null
add_i18n_javascript(string $langDir, bool $return = false)

Add i18n files from the given javascript directory. SilverStripe expects that the given directory will contain a number of JavaScript files named by language: en_US.js, de_DE.js, etc.

combineFiles(string $combinedFileName, array $files, array $options = array())

Concatenate several css or javascript files into a single dynamically generated file. This increases performance by fewer HTTP requests.

array
getCombinedFiles()

Return all combined files; keys are the combined file names, values are lists of associative arrays with 'files', 'type', and 'media' keys for details about this combined file.

deleteAllCombinedFiles()

Clears all combined files

clearCombinedFiles()

Clear all registered CSS and JavaScript file combinations

processCombinedFiles()

Do the heavy lifting involved in combining the combined files.

bool
getCombinedFilesEnabled()

Check if combined files are enabled

themedCSS(string $name, string $media = null)

Registers the given themeable stylesheet as required.

themedJavascript(string $name, string $type = null)

Registers the given themeable javascript as required.

debug()

Output debugging information.

Details

static Injectable create(array ...$args)

An implementation of the factory method, allows you to create an instance of a class

This method will defer class substitution to the Injector API, which can be customised via the Config API to declare substitution classes.

This can be called in one of two ways - either calling via the class directly, or calling on Object and passing the class name as the first parameter. The following are equivalent: $list = DataList::create('SiteTree'); $list = SiteTree::get();

Parameters

array ...$args

Return Value

Injectable

static Injectable singleton(string $class = null)

Creates a class instance by the "singleton" design pattern.

It will always return the same instance for this class, which can be used for performance reasons and as a simple way to access instance methods which don't rely on instance data (e.g. the custom SilverStripe static handling).

Parameters

string $class

Optional classname to create, if the called class should not be used

Return Value

Injectable

The singleton instance

GeneratedAssetHandler getAssetHandler()

Gets the backend storage for generated files

Return Value

GeneratedAssetHandler

setAssetHandler(GeneratedAssetHandler $handler)

Set a new asset handler for this backend

Parameters

GeneratedAssetHandler $handler

Requirements_Minifier getMinifier() deprecated

deprecated 4.0.0:5.0.0

Gets the minification service for this backend

Return Value

Requirements_Minifier

setMinifier(Requirements_Minifier $minifier = null)

Set a new minification service for this backend

Parameters

Requirements_Minifier $minifier

setCombinedFilesEnabled(bool $enable)

Enable or disable the combination of CSS and JavaScript files

Parameters

bool $enable

bool getWriteHeaderComment()

Check if header comments are written

Return Value

bool

$this setWriteHeaderComment(bool $write)

Flag whether header comments should be written for each combined file

Parameters

bool $write

Return Value

$this

setCombinedFilesFolder(string $folder)

Set the folder to save combined files in. By default they're placed in _combinedfiles, however this may be an issue depending on your setup, especially for CSS files which often contain relative paths.

This must not include any 'assets' prefix

Parameters

string $folder

string getCombinedFilesFolder()

Retrieve the combined files folder prefix

Return Value

string

setSuffixRequirements($var)

Set whether to add caching query params to the requests for file-based requirements.

Eg: themes/myTheme/js/main.js?m=123456789. The parameter is a timestamp generated by filemtime. This has the benefit of allowing the browser to cache the URL infinitely, while automatically busting this cache every time the file is changed.

Parameters

$var

bool getSuffixRequirements()

Check whether we want to suffix requirements

Return Value

bool

$this setWriteJavascriptToBody($var)

Set whether you want to write the JS to the body of the page rather than at the end of the head tag.

Parameters

$var

Return Value

$this

bool getWriteJavascriptToBody()

Check whether you want to write the JS to the body of the page rather than at the end of the head tag.

Return Value

bool

$this setForceJSToBottom($var)

Forces the JavaScript requirements to the end of the body, right before the closing tag

Parameters

$var

Return Value

$this

bool getForceJSToBottom()

Check if the JavaScript requirements are written to the end of the body, right before the closing tag

Return Value

bool

bool getMinifyCombinedFiles()

Check if minify files should be combined

Return Value

bool

$this setMinifyCombinedFiles(bool $minify)

Set if combined files should be minified

Parameters

bool $minify

Return Value

$this

javascript(string $file, array $options = array())

Register the given JavaScript file as required.

Parameters

string $file

Either relative to docroot or in the form "vendor/package:resource"

array $options

List of options. Available options include:

  • 'provides' : List of scripts files included in this file
  • 'async' : Boolean value to set async attribute to script tag
  • 'defer' : Boolean value to set defer attribute to script tag
  • 'type' : Override script type= value.
  • 'integrity' : SubResource Integrity hash
  • 'crossorigin' : Cross-origin policy for the resource

array getProvidedScripts()

Gets all scripts that are already provided by prior scripts.

This follows these rules:

  • Files will not be considered provided if they are separately included prior to the providing file.
  • Providing files can be blocked, and don't provide anything
  • Provided files can't be blocked (you need to block the provider)
  • If a combined file includes files that are provided by prior scripts, then these should be excluded from the combined file.
  • If a combined file includes files that are provided by later scripts, then these files should be included in the combined file, but we can't block the later script either (possible double up of file).

Return Value

array

Array of provided files (map of $path => $path)

array getJavascript()

Returns an array of required JavaScript, excluding blocked and duplicates of provided files.

Return Value

array

customScript(string $script, string $uniquenessID = null)

Register the given JavaScript code into the list of requirements

Parameters

string $script

The script content as a string (without enclosing <script> tag)

string $uniquenessID

A unique ID that ensures a piece of code is only added once

array getCustomScripts()

Return all registered custom scripts

Return Value

array

customCSS(string $script, string $uniquenessID = null)

Register the given CSS styles into the list of requirements

Parameters

string $script

CSS selectors as a string (without enclosing <style> tag)

string $uniquenessID

A unique ID that ensures a piece of code is only added once

array getCustomCSS()

Return all registered custom CSS

Return Value

array

insertHeadTags(string $html, string $uniquenessID = null)

Add the following custom HTML code to the <head> section of the page

Parameters

string $html

Custom HTML code

string $uniquenessID

A unique ID that ensures a piece of code is only added once

array getCustomHeadTags()

Return all custom head tags

Return Value

array

javascriptTemplate(string $file, string[] $vars, string $uniquenessID = null)

Include the content of the given JavaScript file in the list of requirements. Dollar-sign variables will be interpolated with values from $vars similar to a .ss template.

Parameters

string $file

The template file to load, relative to docroot

string[] $vars

The array of variables to interpolate.

string $uniquenessID

A unique ID that ensures a piece of code is only added once

css(string $file, string $media = null, array $options = [])

Register the given stylesheet into the list of requirements.

Parameters

string $file

The CSS file to load, relative to site root

string $media

Comma-separated list of media types to use in the link tag (e.g. 'screen,projector')

array $options

List of options. Available options include:

  • 'integrity' : SubResource Integrity hash
  • 'crossorigin' : Cross-origin policy for the resource

array getCSS()

Get the list of registered CSS file requirements, excluding blocked files

Return Value

array

Associative array of file to spec

array getBlocked()

Gets the list of all blocked files

Return Value

array

clear(string|int $fileOrID = null)

Clear either a single or all requirements

Caution: Clearing single rules added via customCSS and customScript only works if you originally specified a $uniquenessID.

Parameters

string|int $fileOrID

restore()

Restore requirements cleared by call to Requirements::clear

block(string|int $fileOrID)

Block inclusion of a specific file

The difference between this and {@link clear} is that the calling order does not matter; {@link clear} must be called after the initial registration, whereas {@link block} can be used in advance. This is useful, for example, to block scripts included by a superclass without having to override entire functions and duplicate a lot of code.

Note that blocking should be used sparingly because it's hard to trace where an file is being blocked from.

Parameters

string|int $fileOrID

Relative path from webroot, module resource reference or requirement API ID

unblock(string|int $fileOrID)

Remove an item from the block list

Parameters

string|int $fileOrID

unblockAll()

Removes all items from the block list

string includeInHTML(string $content)

Update the given HTML content with the appropriate include tags for the registered requirements. Needs to receive a valid HTML/XHTML template in the $content parameter, including a head and body tag.

Parameters

string $content

HTML content that has already been parsed from the $templateFile through {@link SSViewer}

Return Value

string

HTML content augmented with the requirements tags

includeInResponse(HTTPResponse $response)

Attach requirements inclusion to X-Include-JS and X-Include-CSS headers on the given HTTP Response

Parameters

HTTPResponse $response

array|null add_i18n_javascript(string $langDir, bool $return = false)

Add i18n files from the given javascript directory. SilverStripe expects that the given directory will contain a number of JavaScript files named by language: en_US.js, de_DE.js, etc.

Parameters

string $langDir

The JavaScript lang directory, relative to the site root, e.g., 'framework/javascript/lang'

bool $return

Return all relative file paths rather than including them in requirements

Return Value

array|null

All relative files if $return is true, or null otherwise

combineFiles(string $combinedFileName, array $files, array $options = array())

Concatenate several css or javascript files into a single dynamically generated file. This increases performance by fewer HTTP requests.

The combined file is regenerated based on every file modification time. Optionally a rebuild can be triggered by appending ?flush=1 to the URL.

All combined files will have a comment on the start of each concatenated file denoting their original position.

CAUTION: You're responsible for ensuring that the load order for combined files is retained - otherwise combining JavaScript files can lead to functional errors in the JavaScript logic, and combining CSS can lead to incorrect inheritance. You can also only include each file once across all includes and combinations in a single page load.

CAUTION: Combining CSS Files discards any "media" information.

Example for combined JavaScript: Requirements::combine_files( 'foobar.js', array( 'mysite/javascript/foo.js', 'mysite/javascript/bar.js', ), array( 'async' => true, 'defer' => true, ) );

Example for combined CSS: Requirements::combine_files( 'foobar.css', array( 'mysite/javascript/foo.css', 'mysite/javascript/bar.css', ), array( 'media' => 'print', ) );

Parameters

string $combinedFileName

Filename of the combined file relative to docroot

array $files

Array of filenames relative to docroot

array $options

Array of options for combining files. Available options are:

  • 'media' : If including CSS Files, you can specify a media type
  • 'async' : If including JavaScript Files, boolean value to set async attribute to script tag
  • 'defer' : If including JavaScript Files, boolean value to set defer attribute to script tag

array getCombinedFiles()

Return all combined files; keys are the combined file names, values are lists of associative arrays with 'files', 'type', and 'media' keys for details about this combined file.

Return Value

array

deleteAllCombinedFiles()

Clears all combined files

clearCombinedFiles()

Clear all registered CSS and JavaScript file combinations

processCombinedFiles()

Do the heavy lifting involved in combining the combined files.

bool getCombinedFilesEnabled()

Check if combined files are enabled

Return Value

bool

themedCSS(string $name, string $media = null)

Registers the given themeable stylesheet as required.

A CSS file in the current theme path name 'themename/css/$name.css' is first searched for, and it that doesn't exist and the module parameter is set then a CSS file with that name in the module is used.

Parameters

string $name

The name of the file - eg '/css/File.css' would have the name 'File'

string $media

Comma-separated list of media types to use in the link tag (e.g. 'screen,projector')

themedJavascript(string $name, string $type = null)

Registers the given themeable javascript as required.

A javascript file in the current theme path name 'themename/javascript/$name.js' is first searched for, and it that doesn't exist and the module parameter is set then a javascript file with that name in the module is used.

Parameters

string $name

The name of the file - eg '/js/File.js' would have the name 'File'

string $type

Comma-separated list of types to use in the script tag (e.g. 'text/javascript,text/ecmascript')

debug()

Output debugging information.