class i18nTextCollector extends SS_Object (View source)

SilverStripe-variant of the "gettext" tool: Parses the string content of all PHP-files and SilverStripe templates for ocurrences of the _t() translation method. Also uses the i18nEntityProvider interface to get dynamically defined entities by executing the provideI18nEntities() method on all implementors of this interface.

Collects all found entities (and their natural language text for the default locale) into language-files for each module in an array notation. Creates or overwrites these files, e.g. framework/lang/en.yml.

The collector needs to be run whenever you make new translatable entities available. Please don't alter the arrays in language tables manually.

Usage through URL: http://localhost/dev/tasks/i18nTextCollectorTask Usage through URL (module-specific): http://localhost/dev/tasks/i18nTextCollectorTask/?module=mymodule Usage on CLI: sake dev/tasks/i18nTextCollectorTask Usage on CLI (module-specific): sake dev/tasks/i18nTextCollectorTask module=mymodule

Properties

public string $class from  SS_Object
protected array $extension_instances from  SS_Object
protected $beforeExtendCallbacks

List of callbacks to call prior to extensions having extend called on them, each grouped by methodName.

from  SS_Object
protected $afterExtendCallbacks

List of callbacks to call after extensions having extend called on them, each grouped by methodName.

from  SS_Object
protected string $defaultLocale

Default (master) locale

public string $basePath

The directory base on which the collector should act.

public string $baseSavePath

Save path

protected i18nTextCollector_Writer $writer
protected array $fileExtensions

List of file extensions to parse

Methods

public static 
config()

Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).

protected
beforeExtending(string $method, callable $callback)

Allows user code to hook into Object::extend prior to control being delegated to extensions. Each callback will be reset once called.

protected
afterExtending(string $method, callable $callback)

Allows user code to hook into Object::extend after control being delegated to extensions. Each callback will be reset once called.

public static 
create()

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

public static 
singleton()

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

public static 
create_from_string($classSpec, $firstArg = null)

Create an object from a string representation. It treats it as a PHP constructor without the 'new' keyword. It also manages to construct the object without the use of eval().

public static 
parse_class_spec($classSpec)

Parses a class-spec, such as "Versioned('Stage','Live')", as passed to create_from_string().

public static 
strong_create()

Similar to Object::create(), except that classes are only overloaded if you set the $strong parameter to TRUE when using Object::useCustomClass()

public static 
useCustomClass(string $oldClass, string $newClass, bool $strong = false)

This class allows you to overload classes with other classes when they are constructed using the factory method Object::create()

public static 
string
getCustomClass(string $class)

If a class has been overloaded, get the class name it has been overloaded with - otherwise return the class name

public static 
any
static_lookup($class, $name, null $default = null)

Get the value of a static property of a class, even in that property is declared protected (but not private), without any inheritance, merging or parent lookup if it doesn't exist on the given class.

public static 
get_static($class, $name, $uncached = false) deprecated

No description

public static 
set_static($class, $name, $value) deprecated

No description

public static 
uninherited_static($class, $name, $uncached = false) deprecated

No description

public static 
combined_static($class, $name, $ceiling = false) deprecated

No description

public static 
addStaticVars($class, $properties, $replace = false) deprecated

No description

public static 
add_static_var($class, $name, $value, $replace = false) deprecated

No description

public static 
has_extension(string $classOrExtension, string $requiredExtension = null, bool $strict = false)

Return TRUE if a class has a specified extension.

public static 
add_extension(string $classOrExtension, string $extension = null)

Add an extension to a specific class.

public static 
remove_extension(string $extension)

Remove an extension from a class.

public static 
array
get_extensions(string $class, bool $includeArgumentString = false)

No description

public static 
get_extra_config_sources($class = null)

No description

public
__construct($locale = null)

No description

public
mixed
__call(string $method, array $arguments)

Attemps to locate and call a method dynamically added to a class at runtime if a default cannot be located

public
bool
hasMethod(string $method)

Return TRUE if a method exists on this object

public
array
allMethodNames(bool $custom = false)

Return the names of all the methods available on this object

protected
defineMethods()

Adds any methods from Extension instances attached to this object.

protected
array
findMethodsFromExtension(object $extension)

No description

protected
addMethodsFrom(string $property, string|int $index = null)

Add all the methods from an object property (which is an Extension) to this object.

protected
removeMethodsFrom(string $property, string|int $index = null)

Add all the methods from an object property (which is an Extension) to this object.

protected
addWrapperMethod(string $method, string $wrap)

Add a wrapper method - a method which points to another method with a different name. For example, Thumbnail(x) can be wrapped to generateThumbnail(x)

protected
createMethod(string $method, string $code)

Add an extra method using raw PHP code passed as a string

public
stat($name, $uncached = false)

No description

public
set_stat($name, $value)

No description

public
uninherited($name)

No description

public
bool
exists()

Return true if this object "exists" i.e. has a sensible value

public
string
parentClass()

No description

public
bool
is_a(string $class)

Check if this class is an instance of a specific class, or has that class as one of its parents

public
string
__toString()

No description

public
mixed
invokeWithExtensions(string $method, mixed $argument = null)

Calls a method if available on both this object and all applied Extensions, and then attempts to merge all results into an array

public
array
extend(string $method, mixed $a1 = null, mixed $a2 = null, mixed $a3 = null, mixed $a4 = null, mixed $a5 = null, mixed $a6 = null, mixed $a7 = null)

Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed

public
getExtensionInstance(string $extension)

Get an extension instance attached to this object by name.

public
bool
hasExtension(string $extension)

Returns TRUE if this object instance has a specific extension applied in $extension_instances. Extension instances are initialized at constructor time, meaning if you use add_extension() afterwards, the added extension will just be added to new instances of the extended class. Use the static method has_extension() to check if a class (not an instance) has a specific extension.

public
array
getExtensionInstances()

Get all extension instances for this specific object instance.

public
mixed
cacheToFile(string $method, int $lifetime = 3600, string $ID = false, array $arguments = array())

Cache the results of an instance method in this object to a file, or if it is already cache return the cached results

public
clearCache($method, $ID = false, $arguments = array())

Clears the cache for the given cacheToFile call

protected
mixed
loadCache(string $cache, int $lifetime = 3600)

Loads a cache from the filesystem if a valid on is present and within the specified lifetime

protected
saveCache(string $cache, mixed $data)

Save a piece of cached data to the file system

protected
string
sanitiseCachename(string $name)

Strip a file name of special characters so it is suitable for use as a cache file name

public
setWriter(i18nTextCollector_Writer $writer)

Assign a writer

public
getWriter()

Gets the currently assigned writer, or the default if none is specified.

public
run(array $restrictToModules = null, bool $mergeWithExisting = false)

This is the main method to build the master string tables with the original strings. It will search for existent modules that use the i18n feature, parse the _t() calls and write the resultant files in the lang folder of each module.

protected
array
getModules(string $directory)

Gets the list of modules in this installer

public
array
collect(array $restrictToModules = array(), bool $mergeWithExisting = false)

Extract all strings from modules and return these grouped by module name

protected
array
resolveDuplicateConflicts(array $entitiesByModule)

Resolve conflicts between duplicate keys across modules

protected
array
getConflicts(array $entitiesByModule)

Find all keys in the entity list that are duplicated across modules

protected
string
getBestModuleForKey(array $entitiesByModule, string $key)

Determine the best module to be given ownership over this key

protected
array
mergeWithExisting(array $entitiesByModule)

Merge all entities with existing strings

protected
array
getEntitiesByModule()

Collect all entities grouped by module

public
write($module, $entities)

No description

protected
array
processModule(string $module)

Builds a master string table from php and .ss template files for the module passed as the $module param

protected
array
getFileListForModule(type $module)

Retrieves the list of files for this module

public
array
collectFromCode(string $content, string $module)

Extracts translatables from .php files.

public
array
collectFromTemplate(string $content, string $fileName, string $module, $parsedFiles = array())

Extracts translatables from .ss templates (Self referencing)

public
array
collectFromEntityProviders(string $filePath, string $module = null)

Allows classes which implement i18nEntityProvider to provide additional translation strings.

protected
string|bool
normalizeEntity(string $fullName, string $_namespace = null)

Normalizes enitities with namespaces.

protected
array
getFilesRecursive(string $folder, array $fileList = array(), string $type = null, string $folderExclude = '/\\/(tests)$/')

Helper function that searches for potential files (templates and code) to be parsed

public
getDefaultLocale()

No description

public
setDefaultLocale($locale)

No description

Details

static Config_ForClass|null config()

Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).

Return Value

Config_ForClass|null

protected beforeExtending(string $method, callable $callback)

Allows user code to hook into Object::extend prior to control being delegated to extensions. Each callback will be reset once called.

Parameters

string $method

The name of the method to hook into

callable $callback

The callback to execute

protected afterExtending(string $method, callable $callback)

Allows user code to hook into Object::extend after control being delegated to extensions. Each callback will be reset once called.

Parameters

string $method

The name of the method to hook into

callable $callback

The callback to execute

static SS_Object create()

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

This method first for strong class overloads (singletons & DB interaction), then custom class overloads. If an overload is found, an instance of this is returned rather than the original class. To overload a class, use Object::useCustomClass()

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();

Return Value

SS_Object

static SS_Object singleton()

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

Return Value

SS_Object

The singleton instance

static create_from_string($classSpec, $firstArg = null)

Create an object from a string representation. It treats it as a PHP constructor without the 'new' keyword. It also manages to construct the object without the use of eval().

Construction itself is done with Object::create(), so that Object::useCustomClass() calls are respected.

Object::create_from_string("Versioned('Stage','Live')") will return the result of Versioned::create('Stage', 'Live);

It is designed for simple, clonable objects. The first time this method is called for a given string it is cached, and clones of that object are returned.

If you pass the $firstArg argument, this will be prepended to the constructor arguments. It's impossible to pass null as the firstArg argument.

Object::create_from_string("Varchar(50)", "MyField") will return the result of Vachar::create('MyField', '50');

Arguments are always strings, although this is a quirk of the current implementation rather than something that can be relied upon.

Parameters

$classSpec
$firstArg

static parse_class_spec($classSpec)

Parses a class-spec, such as "Versioned('Stage','Live')", as passed to create_from_string().

Returns a 2-elemnent array, with classname and arguments

Parameters

$classSpec

static SS_Object strong_create()

Similar to Object::create(), except that classes are only overloaded if you set the $strong parameter to TRUE when using Object::useCustomClass()

Return Value

SS_Object

static useCustomClass(string $oldClass, string $newClass, bool $strong = false)

This class allows you to overload classes with other classes when they are constructed using the factory method Object::create()

Parameters

string $oldClass

the class to replace

string $newClass

the class to replace it with

bool $strong

allows you to enforce a certain class replacement under all circumstances. This is used in singletons and DB interaction classes

static string getCustomClass(string $class)

If a class has been overloaded, get the class name it has been overloaded with - otherwise return the class name

Parameters

string $class

the class to check

Return Value

string

the class that would be created if you called Object::create() with the class

static any static_lookup($class, $name, null $default = null)

Get the value of a static property of a class, even in that property is declared protected (but not private), without any inheritance, merging or parent lookup if it doesn't exist on the given class.

Parameters

$class
  • The class to get the static from
$name
  • The property to get from the class
null $default
  • The value to return if property doesn't exist on class

Return Value

any
  • The value of the static property $name on class $class, or $default if that property is not defined

static get_static($class, $name, $uncached = false) deprecated

deprecated

No description

Parameters

$class
$name
$uncached

static set_static($class, $name, $value) deprecated

deprecated

No description

Parameters

$class
$name
$value

static uninherited_static($class, $name, $uncached = false) deprecated

deprecated

No description

Parameters

$class
$name
$uncached

static combined_static($class, $name, $ceiling = false) deprecated

deprecated

No description

Parameters

$class
$name
$ceiling

static addStaticVars($class, $properties, $replace = false) deprecated

deprecated

No description

Parameters

$class
$properties
$replace

static add_static_var($class, $name, $value, $replace = false) deprecated

deprecated

No description

Parameters

$class
$name
$value
$replace

static has_extension(string $classOrExtension, string $requiredExtension = null, bool $strict = false)

Return TRUE if a class has a specified extension.

This supports backwards-compatible format (static Object::has_extension($requiredExtension)) and new format ($object->has_extension($class, $requiredExtension))

Parameters

string $classOrExtension

if 1 argument supplied, the class name of the extension to check for; if 2 supplied, the class name to test

string $requiredExtension

used only if 2 arguments supplied

bool $strict

if the extension has to match the required extension and not be a subclass

static add_extension(string $classOrExtension, string $extension = null)

Add an extension to a specific class.

The preferred method for adding extensions is through YAML config, since it avoids autoloading the class, and is easier to override in more specific configurations.

As an alternative, extensions can be added to a specific class directly in the Object::$extensions array. See SiteTree::$extensions for examples. Keep in mind that the extension will only be applied to new instances, not existing ones (including all instances created through singleton()).

Parameters

string $classOrExtension

Class that should be extended - has to be a subclass of Object

string $extension

Subclass of Extension with optional parameters as a string, e.g. "Versioned" or "Translatable('Param')"

See also

http://doc.silverstripe.org/framework/en/trunk/reference/dataextension

static remove_extension(string $extension)

Remove an extension from a class.

Keep in mind that this won't revert any datamodel additions of the extension at runtime, unless its used before the schema building kicks in (in your _config.php). Doesn't remove the extension from any Object instances which are already created, but will have an effect on new extensions. Clears any previously created singletons through singleton() to avoid side-effects from stale extension information.

Add support for removing extensions with parameters

Parameters

string $extension

Classname of an Extension subclass, without parameters

static array get_extensions(string $class, bool $includeArgumentString = false)

No description

Parameters

string $class
bool $includeArgumentString

Include the argument string in the return array, FALSE would return array("Versioned"), TRUE returns array("Versioned('Stage','Live')").

Return Value

array

Numeric array of either DataExtension classnames, or eval'ed classname strings with constructor arguments.

static get_extra_config_sources($class = null)

No description

Parameters

$class

__construct($locale = null)

No description

Parameters

$locale

mixed __call(string $method, array $arguments)

Attemps to locate and call a method dynamically added to a class at runtime if a default cannot be located

You can add extra methods to a class using Extensions}, {@link Object::createMethod() or Object::addWrapperMethod()

Parameters

string $method
array $arguments

Return Value

mixed

bool hasMethod(string $method)

Return TRUE if a method exists on this object

This should be used rather than PHP's inbuild method_exists() as it takes into account methods added via extensions

Parameters

string $method

Return Value

bool

array allMethodNames(bool $custom = false)

Return the names of all the methods available on this object

Parameters

bool $custom

include methods added dynamically at runtime

Return Value

array

protected defineMethods()

Adds any methods from Extension instances attached to this object.

All these methods can then be called directly on the instance (transparently mapped through __call()}), or called explicitly through {@link extend().

protected array findMethodsFromExtension(object $extension)

No description

Parameters

object $extension

Return Value

array

protected addMethodsFrom(string $property, string|int $index = null)

Add all the methods from an object property (which is an Extension) to this object.

Parameters

string $property

the property name

string|int $index

an index to use if the property is an array

protected removeMethodsFrom(string $property, string|int $index = null)

Add all the methods from an object property (which is an Extension) to this object.

Parameters

string $property

the property name

string|int $index

an index to use if the property is an array

protected addWrapperMethod(string $method, string $wrap)

Add a wrapper method - a method which points to another method with a different name. For example, Thumbnail(x) can be wrapped to generateThumbnail(x)

Parameters

string $method

the method name to wrap

string $wrap

the method name to wrap to

protected createMethod(string $method, string $code)

Add an extra method using raw PHP code passed as a string

Parameters

string $method

the method name

string $code

the PHP code - arguments will be in an array called $args, while you can access this object by using $obj. Note that you cannot call protected methods, as the method is actually an external function

stat($name, $uncached = false)

No description

Parameters

$name
$uncached

See also

SS_Object::get_static

set_stat($name, $value)

No description

Parameters

$name
$value

See also

SS_Object::set_static

uninherited($name)

No description

Parameters

$name

See also

SS_Object::uninherited_static

bool exists()

Return true if this object "exists" i.e. has a sensible value

This method should be overriden in subclasses to provide more context about the classes state. For example, a DataObject class could return false when it is deleted from the database

Return Value

bool

string parentClass()

No description

Return Value

string

this classes parent class

bool is_a(string $class)

Check if this class is an instance of a specific class, or has that class as one of its parents

Parameters

string $class

Return Value

bool

string __toString()

No description

Return Value

string

the class name

mixed invokeWithExtensions(string $method, mixed $argument = null)

Calls a method if available on both this object and all applied Extensions, and then attempts to merge all results into an array

integrate inheritance rules

Parameters

string $method

the method name to call

mixed $argument

a single argument to pass

Return Value

mixed

array extend(string $method, mixed $a1 = null, mixed $a2 = null, mixed $a3 = null, mixed $a4 = null, mixed $a5 = null, mixed $a6 = null, mixed $a7 = null)

Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed

Currently returns an array, with an index resulting every time the function is called. Only adds returns if they're not NULL, to avoid bogus results from methods just defined on the parent extension. This is important for permission-checks through extend, as they use min() to determine if any of the returns is FALSE. As min() doesn't do type checking, an included NULL return would fail the permission checks.

The extension methods are defined during __construct()} in {@link defineMethods().

Parameters

string $method

the name of the method to call on each extension

mixed $a1
mixed $a2
mixed $a3
mixed $a4
mixed $a5
mixed $a6
mixed $a7

Return Value

array

Extension getExtensionInstance(string $extension)

Get an extension instance attached to this object by name.

Parameters

string $extension

Return Value

Extension

bool hasExtension(string $extension)

Returns TRUE if this object instance has a specific extension applied in $extension_instances. Extension instances are initialized at constructor time, meaning if you use add_extension() afterwards, the added extension will just be added to new instances of the extended class. Use the static method has_extension() to check if a class (not an instance) has a specific extension.

Caution: Don't use singleton()->hasExtension() as it will give you inconsistent results based on when the singleton was first accessed.

Parameters

string $extension

Classname of an Extension subclass without parameters

Return Value

bool

array getExtensionInstances()

Get all extension instances for this specific object instance.

See get_extensions() to get all applied extension classes for this class (not the instance).

Return Value

array

Map of DataExtension instances, keyed by classname.

mixed cacheToFile(string $method, int $lifetime = 3600, string $ID = false, array $arguments = array())

Cache the results of an instance method in this object to a file, or if it is already cache return the cached results

Parameters

string $method

the method name to cache

int $lifetime

the cache lifetime in seconds

string $ID

custom cache ID to use

array $arguments

an optional array of arguments

Return Value

mixed

the cached data

clearCache($method, $ID = false, $arguments = array())

Clears the cache for the given cacheToFile call

Parameters

$method
$ID
$arguments

protected mixed loadCache(string $cache, int $lifetime = 3600)

Loads a cache from the filesystem if a valid on is present and within the specified lifetime

Parameters

string $cache

the cache name

int $lifetime

the lifetime (in seconds) of the cache before it is invalid

Return Value

mixed

protected saveCache(string $cache, mixed $data)

Save a piece of cached data to the file system

Parameters

string $cache

the cache name

mixed $data

data to save (must be serializable)

protected string sanitiseCachename(string $name)

Strip a file name of special characters so it is suitable for use as a cache file name

Parameters

string $name

Return Value

string

the name with all special cahracters replaced with underscores

setWriter(i18nTextCollector_Writer $writer)

Assign a writer

Parameters

i18nTextCollector_Writer $writer

i18nTextCollector_Writer getWriter()

Gets the currently assigned writer, or the default if none is specified.

run(array $restrictToModules = null, bool $mergeWithExisting = false)

This is the main method to build the master string tables with the original strings. It will search for existent modules that use the i18n feature, parse the _t() calls and write the resultant files in the lang folder of each module.

Parameters

array $restrictToModules
bool $mergeWithExisting

Merge new master strings with existing ones already defined in language files, rather than replacing them. This can be useful for long-term maintenance of translations across releases, because it allows "translation backports" to older releases without removing strings these older releases still rely on.

protected array getModules(string $directory)

Gets the list of modules in this installer

Parameters

string $directory

Path to look in

Return Value

array

List of modules as paths relative to base

array collect(array $restrictToModules = array(), bool $mergeWithExisting = false)

Extract all strings from modules and return these grouped by module name

Parameters

array $restrictToModules
bool $mergeWithExisting

Return Value

array

protected array resolveDuplicateConflicts(array $entitiesByModule)

Resolve conflicts between duplicate keys across modules

Parameters

array $entitiesByModule

List of all modules with keys

Return Value

array

Filtered listo of modules with duplicate keys unassigned

protected array getConflicts(array $entitiesByModule)

Find all keys in the entity list that are duplicated across modules

Parameters

array $entitiesByModule

Return Value

array

List of keys

protected string getBestModuleForKey(array $entitiesByModule, string $key)

Determine the best module to be given ownership over this key

Parameters

array $entitiesByModule
string $key

Return Value

string

Best module, if found

protected array mergeWithExisting(array $entitiesByModule)

Merge all entities with existing strings

Parameters

array $entitiesByModule

Return Value

array

protected array getEntitiesByModule()

Collect all entities grouped by module

Return Value

array

write($module, $entities)

No description

Parameters

$module
$entities

protected array processModule(string $module)

Builds a master string table from php and .ss template files for the module passed as the $module param

Parameters

string $module

A module's name or just 'themes/'

Return Value

array

An array of entities found in the files that comprise the module

See also

collectFromCode() and collectFromTemplate()

protected array getFileListForModule(type $module)

Retrieves the list of files for this module

Parameters

type $module

Return Value

array

List of files to parse

array collectFromCode(string $content, string $module)

Extracts translatables from .php files.

Parameters

string $content

The text content of a parsed template-file

string $module

Module's name or 'themes'. Could also be a namespace Generated by templates includes. E.g. 'UploadField.ss'

Return Value

array

$entities An array of entities representing the extracted translation function calls in code

array collectFromTemplate(string $content, string $fileName, string $module, $parsedFiles = array())

Extracts translatables from .ss templates (Self referencing)

Parameters

string $content

The text content of a parsed template-file

string $fileName

The name of a template file when method is used in self-referencing mode

string $module

Module's name or 'themes'

$parsedFiles

Return Value

array

$entities An array of entities representing the extracted template function calls

array collectFromEntityProviders(string $filePath, string $module = null)

Allows classes which implement i18nEntityProvider to provide additional translation strings.

Not all classes can be instanciated without mandatory arguments, so entity collection doesn't work for all SilverStripe classes currently

Parameters

string $filePath
string $module

Return Value

array

protected string|bool normalizeEntity(string $fullName, string $_namespace = null)

Normalizes enitities with namespaces.

Parameters

string $fullName
string $_namespace

Return Value

string|bool FALSE

protected array getFilesRecursive(string $folder, array $fileList = array(), string $type = null, string $folderExclude = '/\\/(tests)$/')

Helper function that searches for potential files (templates and code) to be parsed

Parameters

string $folder

base directory to scan (will scan recursively)

array $fileList

Array to which potential files will be appended

string $type

Optional, "php" or "ss" only

string $folderExclude

Regular expression matching folder names to exclude

Return Value

array

$fileList An array of files

getDefaultLocale()

No description

setDefaultLocale($locale)

No description

Parameters

$locale