class Requirements_Backend (View source)

Traits

A class that can be instantiated or replaced via DI

Properties

protected bool $suffixRequirements

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

protected bool|null $combinedFilesEnabled

Whether to combine CSS and JavaScript files

protected array $javascript

Paths to all required JavaScript files relative to docroot

protected array $providedJavascript

Map of included scripts to array of contained files.

protected array $css

Paths to all required CSS files relative to the docroot.

protected array $customScript

All custom javascript code that is inserted into the page's HTML

protected array $customCSS

All custom CSS rules which are inserted directly at the bottom of the HTML <head> tag

protected array $customHeadTags

All custom HTML markup which is added before the closing <head> tag, e.g. additional metatags.

protected array $disabled

Remembers the file paths or uniquenessIDs of all Requirements cleared through clear(), so that they can be restored later.

protected array $blocked

The file paths (relative to docroot) or uniquenessIDs of any included requirements which should be blocked when executing inlcudeInHTML(). This is useful, for example, to block scripts included by a superclass without having to override entire functions and duplicate a lot of code.

protected array $combinedFiles

A list of combined files registered via combine_files(). Keys are the output file names, values are lists of input files.

protected bool $writeHeaderComment

Whether or not file headers should be written when combining files

protected string $combinedFilesFolder

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

public 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.

protected bool $forceJSToBottom

Force the JavaScript to the bottom of the page, even if there's a script tag in the body already

protected GeneratedAssetHandler $assetHandler

Methods

public static 
create(mixed ...$args)

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

public static 
singleton(string $class = null)

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

public
getAssetHandler()

Gets the backend storage for generated files

public
setAssetHandler(GeneratedAssetHandler $handler)

Set a new asset handler for this backend

public
setCombinedFilesEnabled(bool $enable)

Enable or disable the combination of CSS and JavaScript files

public
bool
getWriteHeaderComment()

Check if header comments are written

public
$this
setWriteHeaderComment(bool $write)

Flag whether header comments should be written for each combined file

public
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.

public
string
getCombinedFilesFolder()

Retrieve the combined files folder prefix

public
setSuffixRequirements(bool $var)

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

public
bool
getSuffixRequirements()

Check whether we want to suffix requirements

public
$this
setWriteJavascriptToBody(bool $var)

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

public
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.

public
$this
setForceJSToBottom(bool $var)

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

public
bool
getForceJSToBottom()

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

public
javascript(string $file, array $options = [])

Register the given JavaScript file as required.

protected
unsetJavascript(string $file)

Remove a javascript requirement

public
array
getProvidedScripts()

Gets all scripts that are already provided by prior scripts.

public
array
getJavascript()

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

protected
array
getAllJavascript()

Gets all javascript, including blocked files. Unwraps the array into a non-associative list

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

Register the given JavaScript code into the list of requirements

public
customScriptWithAttributes(string $script, array $attributes = [], string|int|null $uniquenessID = null)

Register the given Javascript code into the list of requirements with optional tag attributes.

public
array
getCustomScripts()

Return all registered custom scripts

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

Register the given CSS styles into the list of requirements

public
array
getCustomCSS()

Return all registered custom CSS

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

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

public
array
getCustomHeadTags()

Return all custom head tags

public
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.

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

Register the given stylesheet into the list of requirements.

protected
unsetCSS(string $file)

Remove a css requirement

public
array
getCSS()

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

protected
array
getAllCSS()

Gets all CSS files requirements, including blocked

public
array
getBlocked()

Gets the list of all blocked files

public
clear(string|int $fileOrID = null)

Clear either a single or all requirements

public
restore()

Restore requirements cleared by call to Requirements::clear

public
block(string|int $fileOrID)

Block inclusion of a specific file

public
unblock(string|int $fileOrID)

Remove an item from the block list

public
unblockAll()

Removes all items from the block list

public
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.

protected
string
insertScriptsAtBottom(string $jsRequirements, string $content)

Given a block of HTML, insert the given scripts at the bottom before the closing </body> tag

protected
string
insertScriptsIntoBody(string $jsRequirements, string $content)

Given a block of HTML, insert the given scripts inside the <body></body>

protected
string
insertTagsIntoHead(string $jsRequirements, string $content)

Given a block of HTML, insert the given code inside the <head></head> block

protected
string
escapeReplacement(string $replacement)

Safely escape a literal string for use in preg_replace replacement

public
includeInResponse(HTTPResponse $response)

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

public
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.

protected
string|bool
pathForFile(string $fileOrUrl)

Finds the path for specified file

public
combineFiles(string $combinedFileName, array $files, array $options = [])

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

protected
array
parseCombinedFile(string|array $file)

Return path and type of given combined file

public
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.

protected
array
getAllCombinedFiles()

Includes all combined files, including blocked ones

public
deleteAllCombinedFiles()

Clears all combined files

public
clearCombinedFiles()

Clear all registered CSS and JavaScript file combinations

public
processCombinedFiles()

Do the heavy lifting involved in combining the combined files.

protected
string|null
getCombinedFileURL(string $combinedFile, array $fileList, string $type)

Given a set of files, combine them (as necessary) and return the url

protected
string
resolveCSSReferences(string $content, string $filePath)

Resolves relative paths in CSS files which are lost when combining them

protected
string
hashedCombinedFilename(string $combinedFile, array $fileList)

Given a filename and list of files, generate a new filename unique to these files

public
bool
getCombinedFilesEnabled()

Check if combined files are enabled

protected
string
hashOfFiles(array $fileList)

For a given filelist, determine some discriminating value to determine if any of these files have changed.

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

Registers the given themeable stylesheet as required.

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

Registers the given themeable javascript as required.

public
debug()

Output debugging information.

Details

static Injectable create(mixed ...$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::class); $list = SiteTree::get();

Parameters

mixed ...$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

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(bool $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

bool $var

bool getSuffixRequirements()

Check whether we want to suffix requirements

Return Value

bool

$this setWriteJavascriptToBody(bool $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

bool $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(bool $var)

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

Parameters

bool $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

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

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

protected unsetJavascript(string $file)

Remove a javascript requirement

Parameters

string $file

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

protected array getAllJavascript()

Gets all javascript, including blocked files. Unwraps the array into a non-associative list

Return Value

array

Indexed array of javascript files

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

customScriptWithAttributes(string $script, array $attributes = [], string|int|null $uniquenessID = null)

Register the given Javascript code into the list of requirements with optional tag attributes.

Parameters

string $script

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

array $attributes
string|int|null $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

protected unsetCSS(string $file)

Remove a css requirement

Parameters

string $file

array getCSS()

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

Return Value

array

Associative array of file to spec

protected array getAllCSS()

Gets all CSS files requirements, including blocked

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 clear is that the calling order does not matter; 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 SSViewer

Return Value

string

HTML content augmented with the requirements tags

protected string insertScriptsAtBottom(string $jsRequirements, string $content)

Given a block of HTML, insert the given scripts at the bottom before the closing </body> tag

Parameters

string $jsRequirements

String containing one or more javascript <script /> tags

string $content

HTML body

Return Value

string

Merged HTML

protected string insertScriptsIntoBody(string $jsRequirements, string $content)

Given a block of HTML, insert the given scripts inside the <body></body>

Parameters

string $jsRequirements

String containing one or more javascript <script /> tags

string $content

HTML body

Return Value

string

Merged HTML

protected string insertTagsIntoHead(string $jsRequirements, string $content)

Given a block of HTML, insert the given code inside the <head></head> block

Parameters

string $jsRequirements

String containing one or more html tags

string $content

HTML body

Return Value

string

Merged HTML

protected string escapeReplacement(string $replacement)

Safely escape a literal string for use in preg_replace replacement

Parameters

string $replacement

Return Value

string

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

protected string|bool pathForFile(string $fileOrUrl)

Finds the path for specified file

Parameters

string $fileOrUrl

Return Value

string|bool

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

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

protected array parseCombinedFile(string|array $file)

Return path and type of given combined file

Parameters

string|array $file

Either a file path, or an array spec

Return Value

array

array with two elements, path and type of file

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

protected array getAllCombinedFiles()

Includes all combined files, including blocked ones

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.

protected string|null getCombinedFileURL(string $combinedFile, array $fileList, string $type)

Given a set of files, combine them (as necessary) and return the url

Parameters

string $combinedFile

Filename for this combined file

array $fileList

List of files to combine

string $type

Either 'js' or 'css'

Return Value

string|null

URL to this resource, if there are files to combine

Exceptions

Exception

protected string resolveCSSReferences(string $content, string $filePath)

Resolves relative paths in CSS files which are lost when combining them

Parameters

string $content
string $filePath

Return Value

string

New content with paths resolved

protected string hashedCombinedFilename(string $combinedFile, array $fileList)

Given a filename and list of files, generate a new filename unique to these files

Parameters

string $combinedFile
array $fileList

Return Value

string

bool getCombinedFilesEnabled()

Check if combined files are enabled

Return Value

bool

protected string hashOfFiles(array $fileList)

For a given filelist, determine some discriminating value to determine if any of these files have changed.

Parameters

array $fileList

List of files

Return Value

string

SHA1 bashed file hash

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.