diff --git a/composer.json b/composer.json index d4458a9..87c1462 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "dd/modxevo-library-ddtools", "type": "modxevo-library-ddtools", - "version": "0.24.1", + "version": "0.25.0", "description": "A library with various tools facilitating your work.", "keywords": [ "modx", diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index 5e9d76f..a1d824b 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -1,7 +1,7 @@ = 5.4. * @uses (MODX)EvolutionCMS >= 1.0.10 {@link https://github.com/evolution-cms/evolution }. @@ -16,106 +16,108 @@ if (!class_exists('ddTools')){ class ddTools { - public static $modx; - - //Contains names of document fields (`site_content`) - public static $documentFields = [ - //For MODX > 1.0.11 - //alias_visible, - 'id', - 'type', - 'contentType', - 'pagetitle', - 'longtitle', - 'description', - 'alias', - 'link_attributes', - 'published', - 'pub_date', - 'unpub_date', - 'parent', - 'isfolder', - 'introtext', - 'content', - 'richtext', - 'template', - 'menuindex', - 'searchable', - 'cacheable', - 'createdby', - 'createdon', - 'editedby', - 'editedon', - 'deleted', - 'deletedon', - 'deletedby', - 'publishedon', - 'publishedby', - 'menutitle', - 'donthit', - 'haskeywords', - 'hasmetatags', - 'privateweb', - 'privatemgr', - 'content_dispo', - 'hidemenu' - ]; - - //Contains full names of db tables - public static $tables = [ - //System - 'categories' => '', - 'event_log' => '', - 'manager_log' => '', - 'manager_users' => '', - 'system_eventnames' => '', - 'system_settings' => '', - //Documents - 'site_content' => '', - 'documentgroup_names' => '', - 'document_groups' => '', - //Templates - 'site_templates' => '', - //Chunks - 'site_htmlsnippets' => '', - //TVs - 'site_tmplvars' => '', - 'site_tmplvar_access' => '', - 'site_tmplvar_contentvalues' => '', - 'site_tmplvar_templates' => '', - //Snippets - 'site_snippets' => '', - //Plugins - 'site_plugins' => '', - 'site_plugin_events' => '', - //Modules - 'site_modules' => '', - 'site_module_access' => '', - 'site_module_depobj' => '', - //Users - 'membergroup_access' => '', - 'membergroup_names' => '', - 'member_groups' => '', - 'active_users' => '', - 'active_user_locks' => '', - 'active_user_sessions' => '', - 'user_attributes' => '', - 'user_messages' => '', - 'user_roles' => '', - 'user_settings' => '', - 'webgroup_access' => '', - 'webgroup_names' => '', - 'web_groups' => '', - 'web_users' => '', - 'web_user_attributes' => '', - 'web_user_settings' => '' - ]; + public static + $modx, + //Contains names of document fields (`site_content`) + $documentFields = [ + //For MODX > 1.0.11 + //alias_visible, + 'id', + 'type', + 'contentType', + 'pagetitle', + 'longtitle', + 'description', + 'alias', + 'link_attributes', + 'published', + 'pub_date', + 'unpub_date', + 'parent', + 'isfolder', + 'introtext', + 'content', + 'richtext', + 'template', + 'menuindex', + 'searchable', + 'cacheable', + 'createdby', + 'createdon', + 'editedby', + 'editedon', + 'deleted', + 'deletedon', + 'deletedby', + 'publishedon', + 'publishedby', + 'menutitle', + 'donthit', + 'haskeywords', + 'hasmetatags', + 'privateweb', + 'privatemgr', + 'content_dispo', + 'hidemenu' + ], + //Contains full names of db tables + $tables = [ + //System + 'categories' => '', + 'event_log' => '', + 'manager_log' => '', + 'manager_users' => '', + 'system_eventnames' => '', + 'system_settings' => '', + //Documents + 'site_content' => '', + 'documentgroup_names' => '', + 'document_groups' => '', + //Templates + 'site_templates' => '', + //Chunks + 'site_htmlsnippets' => '', + //TVs + 'site_tmplvars' => '', + 'site_tmplvar_access' => '', + 'site_tmplvar_contentvalues' => '', + 'site_tmplvar_templates' => '', + //Snippets + 'site_snippets' => '', + //Plugins + 'site_plugins' => '', + 'site_plugin_events' => '', + //Modules + 'site_modules' => '', + 'site_module_access' => '', + 'site_module_depobj' => '', + //Users + 'membergroup_access' => '', + 'membergroup_names' => '', + 'member_groups' => '', + 'active_users' => '', + 'active_user_locks' => '', + 'active_user_sessions' => '', + 'user_attributes' => '', + 'user_messages' => '', + 'user_roles' => '', + 'user_settings' => '', + 'webgroup_access' => '', + 'webgroup_names' => '', + 'web_groups' => '', + 'web_users' => '', + 'web_user_attributes' => '', + 'web_user_settings' => '' + ] + ; - private static $instance; + private static + $instance + ; /** * __construct - * @version 1.0.1 (2018-10-02) + * @version 1.0.2 (2019-06-22) */ private function __construct(){ global $modx; @@ -125,7 +127,8 @@ private function __construct(){ //Init full table names foreach ( self::$tables as - $tableAlias => $tableFullName + $tableAlias => + $tableFullName ){ self::$tables[$tableAlias] = self::$modx->getFullTableName($tableAlias); } @@ -149,7 +152,7 @@ private function __construct(){ //We need to include required files if Composer is not used if(!class_exists('\DDTools\FilesTools')){ - require_once __DIR__.DIRECTORY_SEPARATOR.'require.php'; + require_once __DIR__.DIRECTORY_SEPARATOR . 'require.php'; } } @@ -174,13 +177,15 @@ public static function getInstance(){ /** * orderedParamsToNamed - * @version 1.1.5 (2018-09-28) + * @version 1.1.6 (2019-06-22) * * @desc Convert list of ordered parameters to named. Method is public, but be advised that this is beta-version! * * @param $params {array_associative|stdClass} — The object of params. @required * @param $params['paramsList'] {array} — Parameters in ordered list (func_get_args). @required + * @param $params['paramsList'][i] {mixed} — Parameter value. @required * @param $params['compliance'] {array} — The order of parameters. @required + * @param $params['compliance'][i] {string} — Parameter name. @required * * @return {array_associative} */ @@ -197,7 +202,8 @@ public static function orderedParamsToNamed($params){ //Перебираем массив соответствия foreach ( $params->compliance as - $index => $name + $index => + $name ){ //Если параметр задан if (isset($params->paramsList[$index])){ @@ -205,30 +211,43 @@ public static function orderedParamsToNamed($params){ $result[$name] = $params->paramsList[$index]; } - $logData->message[] = "'".$name."' => $".$name; + $logData->message[] = "'" . $name . "' => $" . $name; } $logData->backtraceArray = debug_backtrace(); //Remove this method array_shift($logData->backtraceArray); $caller = $logData->backtraceArray[0]; - $caller = (isset($caller['class']) ? $caller['class'].'->' : '').$caller['function']; + $caller = + ( + isset($caller['class']) ? + $caller['class'] . '->' : + '' + ) . + $caller['function'] + ; //General info with code example - $logData->message = '
Deprecated ordered parameters.
Ordered list of parameters is no longer allowed, use the “pass-by-name” style.
-//Old style
-'.$caller.'($'.implode(
- ', $',
- $params->compliance
-).');
-//Pass-by-name
-'.$caller.'([
- '.implode(
- ','.PHP_EOL."\t",
- $logData->message
-).'
-]);
-
';
+ $logData->message =
+ 'Deprecated ordered parameters.
Ordered list of parameters is no longer allowed, use the “pass-by-name” style.
' . + '//Old style' .
+ $caller .
+ '($' .
+ implode(
+ ', $',
+ $params->compliance
+ ) .
+ ');' .
+ '//Pass-by-name' .
+ $caller .
+ '([' .
+ implode(
+ ',' . PHP_EOL . "\t",
+ $logData->message
+ ) .
+ ']);' .
+ '
'
+ ;
self::logEvent($logData);
@@ -237,7 +256,7 @@ public static function orderedParamsToNamed($params){
/**
* explodeAssoc
- * @version 1.1.4 (2018-09-28)
+ * @version 1.1.5 (2019-06-22)
*
* @desc Splits string on two separators in the associative array.
*
@@ -263,14 +282,21 @@ public static function explodeAssoc(
$inputString
);
- foreach ($inputString as $item){
+ foreach (
+ $inputString as
+ $item
+ ){
//Разбиваем на ключ-значение
$item = explode(
$keyValDelimiter,
$item
);
- $result[$item[0]] = isset($item[1]) ? $item[1] : '';
+ $result[$item[0]] =
+ isset($item[1]) ?
+ $item[1] :
+ ''
+ ;
}
return $result;
@@ -278,7 +304,7 @@ public static function explodeAssoc(
/**
* unfoldArray
- * @version 1.0.4 (2018-06-26)
+ * @version 1.0.5 (2019-06-22)
*
* @desc Converts a multidimensional array into an one-dimensional one joining the keys with '.'. It can be helpful while using placeholders like [+size.width+].
* @example [
@@ -313,7 +339,8 @@ public static function unfoldArray(
//Перебираем массив
foreach (
$array as
- $key => $val
+ $key =>
+ $val
){
//Если значение является массивом
if (is_array($val)){
@@ -322,13 +349,13 @@ public static function unfoldArray(
$result,
self::unfoldArray(
$val,
- $keyPrefix.$key.'.'
+ $keyPrefix . $key . '.'
)
);
//Если значение — не массив
}else{
//Запоминаем (в соответствии с ключом родителя)
- $result[$keyPrefix.$key] = $val;
+ $result[$keyPrefix . $key] = $val;
}
}
@@ -337,7 +364,7 @@ public static function unfoldArray(
/**
* sort2dArray
- * @version 1.1.4 (2018-06-17)
+ * @version 1.1.5 (2019-06-22)
*
* @desc Sorts 2-dimensional array by multiple columns (like in SQL) using Hoare's method, also referred to as quicksort. The sorting is stable.
*
@@ -363,14 +390,25 @@ public static function sort2dArray(
$arrCent = [];
//Перебираем массив
- foreach ($array as $val){
+ foreach (
+ $array as
+ $val
+ ){
//Если эталон и текущее значение — числа
if (
$tekIsNumeric &&
is_numeric($val[$sortBy[$i]])
){
//Получаем нужную циферку
- $cmpRes = ($val[$sortBy[$i]] == $tek) ? 0 : (($val[$sortBy[$i]] > $tek) ? 1 : -1);
+ $cmpRes =
+ $val[$sortBy[$i]] == $tek ?
+ 0 :
+ (
+ $val[$sortBy[$i]] > $tek ?
+ 1 :
+ -1
+ )
+ ;
//Если они строки
}else{
//Сравниваем текущее значение со значением эталонного
@@ -393,25 +431,40 @@ public static function sort2dArray(
}
//Массивы меньших и массивы больших прогоняем по тому же алгоритму (если в них что-то есть)
- $arrLeft = (count($arrLeft) > 1) ? self::sort2dArray(
- $arrLeft,
- $sortBy,
- $sortDir,
- $i
- ) : $arrLeft;
- $arrRight = (count($arrRight) > 1) ? self::sort2dArray(
- $arrRight,
- $sortBy,
- $sortDir,
- $i
- ) : $arrRight;
+ $arrLeft =
+ count($arrLeft) > 1 ?
+ self::sort2dArray(
+ $arrLeft,
+ $sortBy,
+ $sortDir,
+ $i
+ ) :
+ $arrLeft
+ ;
+ $arrRight =
+ count($arrRight) > 1 ?
+ self::sort2dArray(
+ $arrRight,
+ $sortBy,
+ $sortDir,
+ $i
+ ) :
+ $arrRight
+ ;
//Массив одинаковых прогоняем по следующему условию сортировки (если есть условие и есть что сортировать)
- $arrCent = ((count($arrCent) > 1) && $sortBy[$i + 1]) ? self::sort2dArray(
- $arrCent,
- $sortBy,
- $sortDir,
- $i + 1
- ) : $arrCent;
+ $arrCent =
+ (
+ count($arrCent) > 1 &&
+ $sortBy[$i + 1]
+ ) ?
+ self::sort2dArray(
+ $arrCent,
+ $sortBy,
+ $sortDir,
+ $i + 1
+ ) :
+ $arrCent
+ ;
//Склеиваем отсортированные меньшие, средние и большие
return array_merge(
@@ -423,7 +476,7 @@ public static function sort2dArray(
/**
* parseFileNameVersion
- * @version 1.1.2 (2017-12-09)
+ * @version 1.1.3 (2019-06-22)
*
* @desc Parses a file path and gets its name, version & extension.
*
@@ -440,7 +493,7 @@ public static function parseFileNameVersion($file){
//Просто запоминаем его
$fileinfo = $file;
//А также запоминаем строку
- $file = $fileinfo['dirname'].'/'.$fileinfo['basename'];
+ $file = $fileinfo['dirname'] . '/' . $fileinfo['basename'];
//Если передали строку
}else{
//Получаем необходимые данные
@@ -451,7 +504,10 @@ public static function parseFileNameVersion($file){
$result = [
'name' => strtolower($file),
'version' => '0',
- 'extension' => !$fileinfo['extension'] ? '' : $fileinfo['extension']
+ 'extension' =>
+ !$fileinfo['extension'] ?
+ '' :
+ $fileinfo['extension']
];
//Try to get file version [0 — full name, 1 — script name, 2 — version, 3 — all chars after version]
@@ -543,7 +599,7 @@ public static function generateRandomString(
/**
* escapingForJS
- * @version 1.1.1 (2017-07-06)
+ * @version 1.1.2 (2019-06-22)
*
* @desc Escaping chars in string for JS.
*
@@ -553,20 +609,60 @@ public static function generateRandomString(
*/
public static function escapeForJS($str){
//Backslach escaping (see issue #1)
- $str = str_replace('\\', '\\\\', $str);
+ $str = str_replace(
+ '\\',
+ '\\\\',
+ $str
+ );
//Line breaks
- $str = str_replace("\r\n", ' ', $str);
- $str = str_replace("\n", ' ', $str);
- $str = str_replace("\r", ' ', $str);
+ $str = str_replace(
+ "\r\n",
+ ' ',
+ $str
+ );
+ $str = str_replace(
+ "\n",
+ ' ',
+ $str
+ );
+ $str = str_replace(
+ "\r",
+ ' ',
+ $str
+ );
//Tabs
- $str = str_replace(chr(9), ' ', $str);
- $str = str_replace(' ', ' ', $str);
+ $str = str_replace(
+ chr(9),
+ ' ',
+ $str
+ );
+ $str = str_replace(
+ ' ',
+ ' ',
+ $str
+ );
//MODX placeholders
- $str = str_replace('[+', '\[\+', $str);
- $str = str_replace('+]', '\+\]', $str);
+ $str = str_replace(
+ '[+',
+ '\[\+',
+ $str
+ );
+ $str = str_replace(
+ '+]',
+ '\+\]',
+ $str
+ );
//Quotes
- $str = str_replace("'", "\'", $str);
- $str = str_replace('"', '\"', $str);
+ $str = str_replace(
+ "'",
+ "\'",
+ $str
+ );
+ $str = str_replace(
+ '"',
+ '\"',
+ $str
+ );
return $str;
}
@@ -638,7 +734,7 @@ public static function encodedStringToArray($inputString){
/**
* getPlaceholdersFromText
- * @version 1.0 (2017-07-06)
+ * @version 1.0.1 (2019-06-22)
*
* @desc Finds all placeholders' names and returns them as an array.
*
@@ -651,11 +747,14 @@ public static function encodedStringToArray($inputString){
*/
public static function getPlaceholdersFromText($params = []){
//Defaults
- $params = (object) array_merge([
- 'text' => '',
- 'placeholderPrefix' => '[+',
- 'placeholderSuffix' => '+]'
- ], (array) $params);
+ $params = (object) array_merge(
+ [
+ 'text' => '',
+ 'placeholderPrefix' => '[+',
+ 'placeholderSuffix' => '+]'
+ ],
+ (array) $params
+ );
$params->placeholderPrefix = preg_quote($params->placeholderPrefix);
$params->placeholderSuffix = preg_quote($params->placeholderSuffix);
@@ -663,7 +762,7 @@ public static function getPlaceholdersFromText($params = []){
$result = [];
preg_match_all(
- '/'.$params->placeholderPrefix.'(.*?)'.$params->placeholderSuffix.'/',
+ '/' . $params->placeholderPrefix . '(.*?)' . $params->placeholderSuffix . '/',
$params->text,
$result
);
@@ -675,7 +774,7 @@ public static function getPlaceholdersFromText($params = []){
/**
* logEvent
- * @version 1.0.1 (2018-06-17)
+ * @version 1.0.2 (2019-06-22)
*
* @desc Add an alert message to the system event log with debug info (backtrace, snippet name, document id, etc).
*
@@ -690,14 +789,17 @@ public static function getPlaceholdersFromText($params = []){
*/
public static function logEvent($params){
//Defaults
- $params = (object) array_merge([
- 'message' => '',
- 'source' => '',
- //TODO: Why “1”, what does it mean?
- 'eventId' => 1,
- 'eventType' => 'warning',
-// 'backtraceArray' => debug_backtrace(),
- ], (array) $params);
+ $params = (object) array_merge(
+ [
+ 'message' => '',
+ 'source' => '',
+ //TODO: Why “1”, what does it mean?
+ 'eventId' => 1,
+ 'eventType' => 'warning',
+// 'backtraceArray' => debug_backtrace(),
+ ],
+ (array) $params
+ );
//Prepare backtrace and caller
@@ -707,14 +809,21 @@ public static function logEvent($params){
array_shift($params->backtraceArray);
}
$caller = $params->backtraceArray[0];
- $caller = (isset($caller['class']) ? $caller['class'].'->' : '').$caller['function'];
+ $caller =
+ (
+ isset($caller['class']) ?
+ $caller['class'] . '->' :
+ ''
+ ) .
+ $caller['function']
+ ;
$debugInfo = [];
//Add current document Id to debug info
if (!empty(self::$modx->documentIdentifier)){
- $debugInfo[] = '