Just add dd/evolutioncms-libraries-ddtools to your composer.json., (*2)
ddTools version must be 0.14 or higher to use this method. If you use it, the compatibility with all your snippets, modules, etc. that use ddTools versions under 0.14 will be maintained., (*3)
If ddTools is already exist on your site, ddInstaller will check it version and update it if needed.
If ddTools is not exist on your site, ddInstaller can't do anything because requires it for itself.
Parameters description
\ddTools::isEmpty($value)
Determines whether a variable is empty., (*5)
The following values are considered as empty:
* Empty objects (e. g. new \stdClass()).
* Any values equal to false (the same as $value == false)., (*6)
$value
Description: Value to be checked.
Valid values: mixed
Default value: null
\ddTools::convertUrlToAbsolute($params)
Converts relative URLs to absolute., (*7)
The method tends to change URL as little as possible and just prepends required scheme and/or host (or sometimes nothing at all).
All kinds of query parameters, hash, ports, etc. are not modified., (*8)
$params, (*9)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->url, (*10)
Description: Source URL. Can be set as:
'some/url' — relative
'/some/url' — relative starting with slash
'example.com/some/url' — absolute starting with domain
'//example.com/some/url' — absolute starting with double slash
'https://example.com/some/url' — absolute starting with scheme
Valid values: string
Required
$params->host, (*11)
Description: Host for the result URL.
Valid values: string
Default value: $_SERVER['HTTP_HOST']
$params->scheme, (*12)
Description: Scheme for the result URL.
Valid values: string
Default value: 'https' or 'http' depending on $_SERVER['HTTPS']
Returns
$result
Description: Source URL converted to absolute. Always contains scheme.
Valid values: string
\ddTools::getTpl($tpl = '')
The same as $modx->getTpl with some differences:
* This method always returns string regardless of the parameter type. For example, $modx->getTpl(null) returns null, this method returns ''.
* The parameter is optional. $modx->getTpl() throws an error, this method jsut returns ''.
* $modx->getTpl('@CODE:') returns '@CODE:', this method returns ''., (*13)
$tpl
Description: Chunk name or inline template.
Valid values:
stringChunkName
string — use inline templates starting with @CODE:
Default value: ''
Returns
$result
Description: Required template.
Valid values: string
\ddTools::parseText($params)
Replaces placeholders in a text with required values., (*14)
$params, (*15)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->text, (*16)
Description: String to parse.
Valid values: string
Required
$params->data, (*17)
Description:
The array of additional data has to be replaced in $params->text.
Nested objects and arrays are supported too:
The method checks an array for deprecated parameters and writes warning messages into the MODX event log.
It returns an associative array, in which the correct parameter names are the keys and the parameter values are the values.
You can use the exctract function to turn the array into variables of the current symbol table., (*23)
$params, (*24)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->params, (*25)
Description: The associative array of the parameters of a snippet, in which the parameter names are the keys and the parameter values are the values.
You can directly pass here the $params variable if you call the method inside of a snippet.
Valid values:
stdClass
arrayAssociative
Required
$params->compliance, (*26)
Description: An array (or object) of correspondence between new parameter names and old ones, in which the new names are the keys and the old names are the values.
Valid values:
stdClass
arrayAssociative
Required
$params->compliance->{$newName}, (*27)
Description: The old name(s). Use a string for a single name or an array for multiple.
Valid values:
string
array
Required
$params->compliance->{$newName}[i], (*28)
Description: One of the old names.
Valid values: string
Required
$params->returnCorrectedOnly, (*29)
Description: Need to return only corrected parameters?
Valid values: boolean
Default value: true
$params->writeToLog, (*30)
Description: Write a warning message about deprecated parameters to the CMS event log.
Valid values: boolean
Default value: true
Returns
$result, (*31)
Description: An array or object, in which the correct parameter names are the keys and the parameter values are the values.
Can contains all parameters or only corrected (see $params->returnCorrectedOnly).
Valid values:
arrayAssociative — if $params->params set as an array
stdClass — if $params->params set as an object
$result[$newName], (*32)
Description: A parameter value, in which the correct parameter name is the key and the parameter value is the value.
Valid values: mixed
\DDTools\Tools\Files
\DDTools\Tools\Files::modifyImage($params)
Modify your images: create thumbnails, crop, resize, fill background color or add watermark., (*33)
$params, (*34)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->sourceFullPathName, (*35)
Description: Full file path of source image.
You can pass a relative path too (e. g. assets/images/some.jpg), the method will automatically add base_path if needed.
Valid values: string
Required
$params->outputFullPathName, (*36)
Description: Full file path of result image.
You can pass a relative path too (e. g. assets/images/some.jpg), the method will automatically add base_path if needed.
The original image will be overwritten if this parameter is omitted.
Valid values: string
Default value: == $params->sourceFullPathName
$params->transformMode, (*37)
Description: Transform mode.
Valid values:
'resize' — resize only, the image will be inscribed into the specified sizes with the same proportions
'crop' — crop only
'resizeAndCrop' — resize small side then crop big side to the specified value
'resizeAndFill' — inscribe image into the specified sizes and fill empty space with the specified background (see $params->backgroundColor)
Default value: 'resize'
$params->width, (*38)
Description: Result image width.
In pair width / height only one is required, omitted size will be calculated according to the image proportions.
Valid values: integer
Required
$params->height, (*39)
Description: Result image height.
In pair width / height only one is required, omitted size will be calculated according to the image proportions.
Valid values: integer
Required
$params->allowEnlargement, (*40)
Description: Allow image enlargement when resizing.
Valid values: boolean
Default value: false
$params->backgroundColor, (*41)
Description: Result image background color in HEX (used only for $params->transformMode == 'resizeAndFill').
Valid values: string
Default value: FFFFFF
$params->allowEnlargement, (*42)
Description: Allow image enlargement when resizing.
Valid values: boolean
Default value: false
$params->quality, (*43)
Description: JPEG compression level.
Valid values: integer
Default value: 100
$params->watermarkImageFullPathName, (*44)
Description: Specify if you want to overlay your image with watermark.
You can pass a relative path too (e. g. assets/images/some.jpg), the method will automatically add base_path if needed.
Valid values: string
Default value: —
\DDTools\Tools\Objects
\DDTools\Tools\Objects::isPropExists($params)
Checks if the object, class or array has a property / element.
This is a “syntactic sugar” for checking an element in one way regardless of the “object” type., (*45)
The first reason for creating this method is convenience to not thinking about type of “object” variables.
Second, the different order of parameters in the native PHP functions makes us crazy., (*46)
$params, (*47)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->object, (*48)
Description: Source object or array.
Valid values:
stdClass
array
Required
$params->propName, (*49)
Description: Object property name or array key.
Valid values:
string
integer
Required
\DDTools\Tools\Objects::getPropValue($params)
Get the value of an object property or an array element in any nesting level in one way regardless of the “object” type., (*50)
$params, (*51)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->object, (*52)
Description: Source object or array.
It can be nested, and elements of all levels can be mix of objects and arrays (see Examples below).
Valid values:
stdClass
array
Required
$params->propName, (*53)
Description: Object property name or array key.
You can also use '.' to get nested properties. Several examples (see also full Examples below):
somePlainProp — get first-level property
someObjectProp.secondLevelProp — get property of the someObjectProp object|array
someArrayProp.0.thirdLevelProp — get property of the zero element of the someArrayProp array
Valid values:
string
integer
Required
$params->notFoundResult, (*54)
Description: What will be returned when property is not found.
Valid values: mixed
Default value: null
Returns
$result
Description: Value of an object property or an array element.
Valid values:
mixed
$params->notFoundResult — if property not exists
\DDTools\Tools\Objects::convertType($params)
Converts an object type.
Arrays, JSON and Query string objects are also supported., (*55)
Description: Type of resulting object.
Values are case insensitive (the following names are equal: 'stringjsonauto', 'stringJsonAuto', 'STRINGJSONAUTO', etc).
Valid values:
'objectAuto' — stdClass or array depends on input object
'objectStdClass' — stdClass
'objectArray' — array
'stringJsonAuto' — stringJsonObject or stringJsonArray depends on input object
'stringJsonObject'
'stringJsonArray'
'stringQueryFormatted'
'stringHtmlAttrs' — HTML attributes string (e. g. width='100' height='50'), boolean values will be converted to 0 or 1 (e. g. data-is-loaded='1'), objects/arrays will be converted to JSON string (e. g. data-user-data='{"firstName": "Elon", "lastName": "Musk"}')
Default value: 'objectAuto'
Returns
$result
Description: Result type depends on $params->type.
Valid values:
stdClass
array
stringJsonObject
stringJsonArray
\DDTools\Tools\Objects::extend($params)
Merge the contents of two or more objects or arrays together into the first one., (*59)
$params, (*60)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->objects, (*61)
Description: Objects or arrays to merge. Moreover, objects can extend arrays and vice versa.
Valid values: array
Required
$params->objects[0], (*62)
Description: The object or array to extend. It will receive the new properties.
Valid values:
object
array
mixed — if passed something else, the new stdClass object will be created instead
Required
$params->objects[i], (*63)
Description: An object or array containing additional properties to merge in.
Valid values:
object
array
Required
$params->deep, (*64)
Description: If true, the merge becomes recursive (aka. deep copy).
Valid values: boolean
Default value: true
$params->overwriteWithEmpty, (*65)
Description: Overwrite fields with empty values (see examples below).
The following values are considered to be empty:
'' — an empty string
[] — an empty array
(object) [] — an empty object
NULL
Valid values: boolean
Default value: true
$params->extendableProperties, (*66)
Description: An array of property names that can be extended from additional objects or arrays. Properties in the initial object or array are not restricted by this parameter.
Valid values:
array
null or any empty value — all properties will be extended
Default value: null
$params->extendableProperties[$i], (*67)
Description: The name of a property that is allowed to be extended from additional objects or arrays.
Valid values: string
Required
\DDTools\Tools\Objects::unfold($params)
Converts a multidimensional array/object into an one-dimensional one joining the keys with $params->keySeparator.
For example, it can be helpful while using placeholders like [+size.width+]., (*68)
$params, (*69)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->object, (*70)
Description: An object/array to convert.
Valid values:
stdClass
arrayAssociative
Required
$params->keySeparator, (*71)
Description: Separator between nested keys in the result object/array.
Valid values: string
Default value: '.'
$params->keyPrefix, (*72)
Description: Prefix of the keys of an object/array (it's an internal varible, but can be used if required).
Valid values: string
Default value: ''
$params->isCrossTypeEnabled, (*73)
Description: This parameter determines whether the method should process elements across different data types, such as arrays and objects, at all levels. When set to true, the method will recursively unfold elements of both array and object types, regardless of the type of the root parent.
Valid values: boolean
Default value: false
Returns
$result
Description: Unfolded object/array. Type of results depends on $params->object.
Valid values:
stdClass
array
\DDTools\Tools\Cache
You can cache some data (e. g. a snippet result)., (*74)
There are 2 levels of caching: stable (file-based) and quick ($_SESSION-based). All methods utilize both levels automatically.
The name of each cache item is [+prefix+]-[+resourceId+]-[+suffix+].
Each cache item can contain a string, array or stdClass.
All cache files are stored in the assets/cache/ddCache folder.
The name of each cache file is [+cacheName+].php.
Quick cache items are stored in $_SESSION['ddCache'].
\DDTools\Tools\Cache::save($params)
Saves custom data to cache storage., (*75)
$params, (*76)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->data, (*77)
Description: Data to save.
Valid values:
string
array
stdClass
Required
$params->resourceId, (*78)
Description: Resource ID related to cache (e. g. document ID).
Valid values: string
Required
$params->suffix, (*79)
Description: Cache suffix. You can use several suffixes with the same $params->resourceId to cache some parts within a resource.
Valid values: string
Required
$params->prefix, (*80)
Description: Cache prefix. Useful if you want to cache some custom data that is not related to any documents.
Valid values: string
Default value: 'doc'
$params->isExtendEnabled, (*81)
Description: Should existing data be extended by $params->data or overwritten?
Valid values: boolean
Default value: false
\DDTools\Tools\Cache::saveSeveral($params)
Saves data of several items to cache storage., (*82)
$params, (*83)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->items, (*84)
Description: Items to save.
Valid values:
stdClass
arrayAssociative
Required
$params->items->{$resourceId}, (*85)
Description: Item data to save. Key is resource ID related to cache (e. g. document ID).
Valid values:
string
array
stdClass
Required
$params->suffix, (*86)
Description: Cache suffix.
Valid values: string
Required
$params->prefix, (*87)
Description: Cache prefix.
Valid values: string
Default value: 'doc'
$params->isExtendEnabled, (*88)
Description: Should existing items data be extended by $params->items or overwritten?
Valid values: boolean
Default value: false
\DDTools\Tools\Cache::get($params)
Retrieves item data from cache storage., (*89)
$params, (*90)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->resourceId, (*91)
Description: Resource ID related to cache (e. g. document ID).
Valid values: string
Required
$params->suffix, (*92)
Description: Cache suffix.
Valid values: string
Required
$params->prefix, (*93)
Description: Cache prefix.
Valid values: string
Default value: 'doc'
Returns
$result
Description: Cached data.
Valid values:
Type of returned data depends on type of saved data:
string
array
stdClass
null — means that the cache item does not exist
\DDTools\Tools\Cache::getSeveral($params)
Retrieves data of several items from cache storage., (*94)
$params, (*95)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->resourceId, (*96)
Description: Resource ID(s) related to cache (e. g. document ID).
Valid values:
string
'*' — means any ID
array — you can specify multiple IDs
Required
$params->resourceId[$i], (*97)
Description: A resource ID.
Valid values: string
Required
$params->suffix, (*98)
Description: Cache suffix.
Valid values: string
Required
$params->prefix, (*99)
Description: Cache prefix.
Valid values: string
Default value: 'doc'
Returns
$result, (*100)
Description: Cached items data.
Valid values:
stdClass
null — means that the cache of specified items does not exist
$result->{$resourceName}, (*101)
Description: Cached item data.
A key is an item's cache name ([+prefix+]-[+resourceId+]-[+suffix+]), a value is a data.
Type of returned data depends on type of saved data.
Valid values:
string
array
stdClass
\DDTools\Tools\Cache::delete($params)
Deletes one or more cache items., (*102)
$params, (*103)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Default value: —
$params->resourceId, (*104)
Description: Resource ID(s) related to cache (e. g. document ID).
Valid values:
string
'*' — means any ID
array — you can specify multiple IDs
null — cache of all resources will be cleared independent of $params->prefix
Default value: null
$params->resourceId[$i], (*105)
Description: A resource ID.
Valid values: string
Default value: —
$params->prefix, (*106)
Description: Cache prefix. Useful if you want to cache some custom data that is not related to any documents.
Valid values:
string
'*' — means any prefix
Default value: 'doc'
$params->suffix, (*107)
Description: Cache suffix.
Valid values:
string
'*' — means any suffix
Default value: '*'
\DDTools\ObjectCollection
Class representing a collection of some objects or arrays., (*108)
\DDTools\ObjectCollection::__construct($params)
$params, (*109)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Default value: —
$params->items, (*110)
Description: An array of items.
You can avoid this parameter to create an empty collection and set items later.
Valid values:
array — can be indexed or associative, keys will not be used
object — also can be set as an object for better convenience, only property values will be used
array — indexed arrays are supported as well as associative
object
Required
$params->itemType, (*112)
Description: Allows to convert item type. If set, each item of $params->items will be converted to needed type.
Values are case insensitive (the following names are equal: 'objectstdclass', 'objectStdClass', 'OBJECTSTDCLASS', etc).
Valid values:
'objectStdClass'
'objectArray'
null — do not convert type of items, use them as is
Default value: null
\DDTools\ObjectCollection::setItems($params)
Sets new collection items. Existing items will be removed., (*113)
Has the same parameters as \DDTools\ObjectCollection::__construct($params)., (*114)
\DDTools\ObjectCollection::addItems($params)
Appends items onto the end of collection., (*115)
Has the same parameters as \DDTools\ObjectCollection::__construct($params)., (*116)
\DDTools\ObjectCollection::getItems($params)
Gets an array of required collection items., (*117)
All items with the gender property equal to 'female'.
All items:
with the gender property equal to 'male'and
with the firstName property not equal to 'Bill'and
with the lastName property is exist with any value.
Quoted property names and values are optional, this is valid too:
'
gender == female
|| gender == male
&& firstName != Bill
&& lastName
'
Single quotes are also supported as double quotes:
"
gender == 'a'
|| gender == 'b'
&& firstName != 'Bill'
&& lastName
"
Spaces, tabs and line breaks are optional, this is valid too: gender==female||gender==male&&firstName!=Bill&&lastName.
Valid values: stringSeparated
Default value: '' (without filtration)
$params->limit, (*120)
Description: Maximum number of items to return.
Valid values:
integer
0 — all matching items
Default value: 0
$params->propAsResultKey, (*121)
Description: Item property, which value will be an item key in result array instead of an item index.
For example, it can be useful if items have an ID property or something like that.
Valid values:
string
null — result array will be indexed
Default value: null
$params->propAsResultValue, (*122)
Description: Item property, which value will be an item value in result array instead of an item object.
Valid values:
string
null — result array values will item objects
Default value: null
Returns
$result, (*123)
Description: An array of items.
Valid values:
arrayIndexed
arrayAssociative — item property values will be used as result keys if $params->propAsResultKey is set
$result[$itemIndex|$itemFieldValue], (*124)
Description: An item object or item property value if specified in $params->propAsResultValue.
Valid values: mixed
\DDTools\ObjectCollection::getOneItem($params)
Gets required item., (*125)
$params, (*126)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Default value: —
$params->filter, (*127)
Description: Filter clause for item properties. The same parameter as \DDTools\ObjectCollection::getItems($params).
Valid values: stringSeparated
Default value: '' (first found item will be returned)
$params->notFoundResult, (*128)
Description: What will be returned when no items found.
Sets data of an item object. All setting of an item data inside the class must be use this method.
It's convenient to override this method in child classes if items are not plain objects., (*144)
$params, (*145)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->index, (*146)
Description: Item index which data will be set.
Valid values: integer
Required
$params->data, (*147)
Description: New item data.
Valid values:
array — indexed arrays are supported as well as associative
Returns data of an item object. All getting of an item data inside the class must use this method.
It's convenient to override this method in child classes if items are not plain objects., (*148)
$params, (*149)
Description: The parameters object.
Valid values:
stdClass
arrayAssociative
Required
$params->itemObject, (*150)
Description: An item object which data will be returned.
Valid values:
array — indexed arrays are supported as well as associative
object
Required
Returns
$result
Description: Data of an item object.
Valid values:
array
object
\DDTools\Base\Base
Simple abstract class with some small methods facilitating your work.
It is convenient to inherit your classes from this., (*151)
Description: Directory of the parent file (e. g. __DIR__).
Valid values: string
Default value: — (dirname of a class that uses this trait)
$params->capitalizeName, (*180)
Description: Need to capitalize child name?
Valid values: boolean
Default value: true
Returns
$result
Description: Child class name.
Valid values: string
\DDTools\Snippet
Abstract class for snippets., (*181)
Properties
\DDTools\Snippet::$name, (*182)
Description: Snippet name (e. g. ddGetDocuments).
Will be set from namespace in \DDTools\Snippet::__construct($params).
You can use it inside child classes: $this->name.
Valid values: string
Visibility: protected
\DDTools\Snippet::$version, (*183)
Description: Snippet version.
You must define it in your child class declaration.
Valid values: string
Visibility: protected
\DDTools\Snippet::$paths, (*184)
Description: Snippet paths.
Will be set in \DDTools\Snippet::__construct($params).
Valid values: stdClass
Visibility: protected
\DDTools\Snippet::$paths->snippet, (*185)
Description: Full path to the snippet folder.
Valid values: string
\DDTools\Snippet::$paths->src, (*186)
Description: Ful path to the src folder.
Valid values: string
\DDTools\Snippet::$params, (*187)
Description: Snippet params.
Will be set in \DDTools\Snippet::__construct($params).
You can define default values of parameters as associative array in this field of your child class (e. g. protected $params = ['someParameter' => 'valueByDefault'];);.
Valid values: stdClass
Visibility: protected
\DDTools\Snippet::$params->{$paramName}, (*188)
Description: Key is parameter name, value is value.
Valid values: mixed
\DDTools\Snippet::$paramsTypes, (*189)
Description: Overwrite in child classes if you want to convert some parameters types.
Parameters types will be converted respectively with this field in \DDTools\Snippet::prepareParams.
Description: The parameter type.
Values are case insensitive (the following names are equal: 'stringjsonauto', 'stringJsonAuto', 'STRINGJSONAUTO', etc).
Description: Overwrite in child classes if you want to rename some parameters with backward compatibility (see $params->compliance of \ddTools::verifyRenamedParams).
Valid values: arrayAssociative
Visibility: protected
\DDTools\Snippet::__construct($params)
$params, (*192)
Description: Snippet parameters, the pass-by-name style is used.
Valid values:
stdClass
arrayAssociative
stringJsonObject
stringQueryFormatted
Default value: []
$params->{$paramName}, (*193)
Description: Key is parameter name, value is value.
Valid values: mixed
Required
\DDTools\Snippet::run()
Abstract method for main snippet action., (*194)
You must define it in your child class declaration., (*195)
\DDTools\Snippet::runSnippet($params)
Static method for easy running needed snippet using only it's name and parameters (if needed)., (*196)
$params, (*197)
Description: Snippet parameters, the pass-by-name style is used.
Valid values:
stdClass
arrayAssociative
stringJsonObject
stringQueryFormatted
Required
$params->name, (*198)
Description: The name of the snippet you want to run (e. g. ddGetDocuments).
Valid values: string
Required
$params->params, (*199)
Description: Parameters that will be passed to the snippet constructor.
Valid values:
stdClass
arrayAssociative
stringJsonObject
stringQueryFormatted
Default value: —
$params->params->{$paramName}, (*200)
Description: Key is parameter name, value is value.
Valid values: mixed
Required
Examples
\ddTools::convertUrlToAbsolute($params): Convert relative URLs to absolute
$params->url can be set in various ways for more convenience:, (*201)
// Relative
$url = 'some/page?q=42#hash';
// Relative starting with slash
$url = '/some/page?q=42#hash';
// Absolute starting with domain
$url = 'example.com/some/page?q=42#hash';
// Absolute starting with double slash
$url = '//example.com/some/page?q=42#hash';
// Absolute starting with scheme
$url = 'https://example.com/some/page?q=42#hash';
\ddTools::convertUrlToAbsolute([
'url' => $url,
// The parameter is optional and is used here just for clarity. By default it will be equal to domain of your site.
'host' => 'example.com',
]);
Suppose we have the snippet ddSendFeedback with the getEmail and getId parameters.
Over time, we decided to rename the parameters as docField and docId respectively (as it happened in version 1.9).
And we want to save backward compatibility, the snippet must work with the old names and send message to the MODX event log., (*203)
// Include (MODX)EvolutionCMS.libraries.ddTools
require_once(
$modx->getConfig('base_path')
. 'assets/libs/ddTools/modx.ddtools.class.php'
);
// Backward compatibility
extract(\ddTools::verifyRenamedParams([
// We called the method inside of a snippet, so its parameters are contained in the `$params` variable (MODX feature)
'params' => $params,
'compliance' => [
// The new name => The old name
'docField' => 'getEmail',
'docId' => 'getId',
],
]));
Below we can use $docField and $docId and not to worry. The method will check everything and will send a message to the MODX event log., (*204)
After some time we decided to rename the parameters again as email_docField и email_docId. Nothing wrong, the method can works with multiple old names, just pass an array:, (*205)
extract(\ddTools::verifyRenamedParams([
// We called the method inside of a snippet, so its parameters are contained in the `$params` variable (MODX feature)
'params' => $params,
'compliance' => [
// The new name => The old names
'email_docField' => [
'docField',
'getEmail',
],
'email_docId' => [
'docId',
'getId',
],
],
// Also you can prevent writing to the CMS event log if you want
'writeToLog' => false,
]));
\ddTools::parseText($params)
Basic example
\ddTools::parseText([
'text' => '
<article>
<h1>[+title+]</h1>
[+text+]
<p>[+authorFirstName+] [+authorLastName+], [+date+].</p>
</article>
',
'data' => [
'title' => 'Bethink Yourselves!',
'text' => '<p>Question your loyalty to your country and government and strive for a more just and peaceful society.</p>',
'authorFirstName' => 'Leo',
'authorLastName' => 'Tolstoy',
'date' => '1904',
],
]);
Returns:, (*206)
<article>
<h1>Bethink Yourselves!</h1>
<p>Question your loyalty to your country and government and strive for a more just and peaceful society.</p>
<p>Leo Tolstoy, 1904.</p>
</article>
Nested objects in $params->data
\ddTools::parseText([
// Data can have a complex nested structure
'data' => [
'title' => 'Bethink Yourselves!',
'text' => '<p>Question your actions and consider the morality behind them.</p>',
// Note that this is not a string, but that's okay
'meta' => [
// Moreover, any depth is supported
// And objects are also supported as well as arrays regardless of nesting level
'author' => (object) [
'firstName' => 'Leo',
'lastName' => 'Tolstoy',
],
'date' => '1904',
],
],
// For nested data you can use placeholders like '[+meta.date+]' for getting a property
// Or like '[+meta+]' to get whole object as JSON
'text' => '
<article data-meta=\'[+meta+]\'>
<h1>[+title+]</h1>
[+text+]
<p>[+meta.author.firstName+] [+meta.author.lastName+], [+meta.date+].</p>
</article>
',
]);
Returns:, (*207)
<article data-meta='{"author":{"firstName":"Leo","lastName":"Tolstoy"},"date":"1904"}'>
<h1>Bethink Yourselves!</h1>
<p>Question your actions and consider the morality behind them.</p>
<p>Leo Tolstoy, 1904.</p>
</article>
\DDTools\Tools\Objects
\DDTools\Tools\Objects::convertType($params)
Convert a JSON or Query encoded string to an array
For example, some snippet supports 2 formats in one of parameters: JSON or Query string.
Users use the format that is convenient to them and we support both.
Just call this method and don't care about it., (*208)
// We can pass string in JSON format
\DDTools\Tools\Objects::convertType([
'object' => '{
"pagetitle": "Test title",
"published": "0"
}',
'type' => 'objectArray',
]);
// Or Query string
\DDTools\Tools\Objects::convertType([
'object' => 'pagetitle=Test title&published=0',
'type' => 'objectArray',
]);
\DDTools\Tools\Objects::convertType([
'object' => "{
// This is HJSON, not JSON, so we can use comments insides
keys: and values can be specified without quotes,
multilineValues:
'''
Write multiline strings with proper whitespace handling.
Starts and ends with triple quotes.
A simple syntax and easy to read.
'''
}",
'type' => 'objectStdClass',
]);
Returns:, (*212)
stdClass::__set_state(array(
'keys' => 'and values can be specified without quotes,',
'multilineValues' => 'Write multiline strings with proper whitespace handling.
Starts and ends with triple quotes.
A simple syntax and easy to read.'
,
))
Convert an associative array to a string of HTML attributes
\DDTools\Tools\Objects::convertType([
'object' => [
'data-name' => 'KINO',
// Will be converted to 1
'data-is-active' => true,
// Will be converted to JSON array
'data-members' => [
'Viktor Tsoi',
'Yuri Kasparyan',
'Aleksei Rybin',
'Igor Tikhomirov',
'Aleksandr Titov',
'Georgy Guryanov',
'Oleg Valinsky',
],
],
'type' => 'stringHtmlAttrs',
]);
Get the value of an object property or an array element in any nesting level
Source object can be nested, and elements of all levels can be mix of objects and arrays., (*236)
// For example let the first level be stdClass
$sourceObject = (object) [
// Let the second level be an indexed array
'PinkFloyd' => [
// Let the third level be an associative array
[
'name' => 'Syd Barrett',
'role' => 'lead and rhythm guitars, vocals',
],
[
'name' => 'David Gilmour',
'role' => 'lead and rhythm guitars, vocals, bass, keyboards, synthesisers',
],
// Let Roger be a little bit special ;)
(object) [
'name' => 'Roger Waters',
'role' => 'bass, vocals, rhythm guitar, synthesisers',
],
[
'name' => 'Richard Wright',
'role' => 'keyboards, piano, organ, synthesisers, vocals',
],
[
'name' => 'Nick Mason',
'role' => 'drums, percussion',
],
],
];
Get a first-level property
There's nothing special, just look at this example for the full picture., (*237)
No matter what type of element is used in any nesting level, the method will work fine.
So let's get Roger's name. As you remember, he is stdClass as opposed to the other members who are associative arrays., (*242)
Of course, it works fine with single-level objects that contain '.' in their property names
var_export(
\DDTools\Tools\Objects::getPropValue([
'object' => [
'1973.03.01' => 'The Dark Side of the Moon',
'1975.09.12' => 'Wish You Were Here',
],
'propName' => '1975.09.12',
])
);
$collection->getItems([
// Spaces, tabs and line breaks are also allowed and do not matter
'filter' => '
gender == female
|| nobelPeacePrize == 1 && isHuman == 0
'
]);
array(
0 => stdClass::__set_state(array(
// Existing properties that absent in `$params->data` have remained as is
'name' => 'Mahatma Gandhi',
'isHuman' => 1,
'gender' => 'male',
// Given property values have overwritten the existing ones
'nobelPeacePrize' => 1,
// Non-existing properties have been created
'birthday' => '2 October 1869',
))
)