From 3f03c723195fca0dd79c7b6d94539883869f88e2 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Tue, 3 Dec 2024 23:04:53 +0400 Subject: [PATCH 1/5] * Minor changes (code style). --- modx.ddtools.class.php | 974 +++++++++++----------- src/Base/Base.php | 14 +- src/ObjectCollection/ObjectCollection.php | 74 +- src/Response/Response.php | 116 ++- src/Snippet/Snippet.php | 118 ++- src/Storage/DB/Storage.php | 222 +++-- src/Storage/Storage.php | 26 +- src/Tools/Files.php | 54 +- src/Tools/Objects.php | 8 +- 9 files changed, 795 insertions(+), 811 deletions(-) diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index 6159111..c40fe05 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -12,107 +12,103 @@ if (!class_exists('ddTools')){ class ddTools { - public static - $modx, - // Contains names of document fields (`site_content`) - $documentFields = [ - 'id', - 'type', - 'contentType', - 'pagetitle', - 'longtitle', - 'description', - 'alias', - 'alias_visible', - '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' => '' - ] - ; + public static $modx; + // Contains names of document fields (`site_content`) + public static $documentFields = [ + 'id', + 'type', + 'contentType', + 'pagetitle', + 'longtitle', + 'description', + 'alias', + 'alias_visible', + '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' => '' + ]; - private static - $instance - ; + private static $instance; /** * __construct - * @version 1.0.6 (2024-08-04) + * @version 1.0.7 (2024-12-03) */ private function __construct(){ global $modx; @@ -121,9 +117,9 @@ private function __construct(){ // Init full table names foreach ( - self::$tables as - $tableAlias => - $tableFullName + self::$tables + as $tableAlias + => $tableFullName ){ self::$tables[$tableAlias] = self::$modx->getFullTableName($tableAlias); } @@ -131,9 +127,9 @@ private function __construct(){ // We need to include required files if Composer is not used if(!class_exists('\DDTools\Tools\Files')){ require_once( - __DIR__ . - DIRECTORY_SEPARATOR . - 'require.php' + __DIR__ + . DIRECTORY_SEPARATOR + . 'require.php' ); } } @@ -142,14 +138,14 @@ private function __clone(){} /** * getInstance - * @version 1.0 (2018-10-01) + * @version 1.0.1 (2024-12-03) */ public static function getInstance(){ global $modx; if( - isset($modx) && - !self::$instance + isset($modx) + && !self::$instance ){ self::$instance = new ddTools(); } @@ -175,7 +171,7 @@ public static function isEmpty($value = null): bool { /** * orderedParamsToNamed - * @version 1.1.7 (2024-08-04) + * @version 1.1.8 (2024-12-03) * * @desc Convert list of ordered parameters to named. Method is public, but be advised that this is beta-version! * @@ -199,9 +195,9 @@ public static function orderedParamsToNamed($params){ // Перебираем массив соответствия foreach ( - $params->compliance as - $index => - $name + $params->compliance + as $index + => $name ){ // Если параметр задан if (isset($params->paramsList[$index])){ @@ -218,33 +214,33 @@ public static function orderedParamsToNamed($params){ $caller = $logData->backtraceArray[0]; $caller = ( - isset($caller['class']) ? - $caller['class'] . '->' : - '' - ) . - $caller['function'] + 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
-			) .
-			']);' .
-			'
' + '

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); @@ -254,7 +250,7 @@ public static function orderedParamsToNamed($params){ /** * explodeAssoc - * @version 1.1.7 (2024-08-04) + * @version 1.1.8 (2024-12-03) * * @desc Splits string on two separators in the associative array. * @@ -283,8 +279,8 @@ public static function explodeAssoc( ); foreach ( - $inputString as - $item + $inputString + as $item ){ // Разбиваем на ключ-значение $item = explode( @@ -293,9 +289,9 @@ public static function explodeAssoc( ); $result[$item[0]] = - isset($item[1]) ? - $item[1] : - '' + isset($item[1]) + ? $item[1] + : '' ; } @@ -304,7 +300,7 @@ public static function explodeAssoc( /** * sort2dArray - * @version 1.3.2 (2024-08-04) + * @version 1.3.3 (2024-12-03) * * @desc Sorts 2-dimensional array by multiple columns (like in SQL) using Hoare's method, also referred to as quicksort. The sorting is stable. * @@ -343,9 +339,9 @@ public static function sort2dArray( // Перебираем массив foreach ( - $array as - $arrayItemKey => - $arrayItem + $array + as $arrayItemKey + => $arrayItem ){ $arrayItem_comparisonValue = \DDTools\Tools\Objects::getPropValue([ 'object' => $arrayItem, @@ -354,17 +350,17 @@ public static function sort2dArray( // Если эталон и текущее значение — числа if ( - $isCurrentItemComparisonValueNumeric && - is_numeric($arrayItem_comparisonValue) + $isCurrentItemComparisonValueNumeric + && is_numeric($arrayItem_comparisonValue) ){ // Получаем нужную циферку $cmpRes = - $arrayItem_comparisonValue == $currentItem_comparisonValue ? - 0 : - ( - $arrayItem_comparisonValue > $currentItem_comparisonValue ? - 1 : - -1 + $arrayItem_comparisonValue == $currentItem_comparisonValue + ? 0 + : ( + $arrayItem_comparisonValue > $currentItem_comparisonValue + ? 1 + : -1 ) ; // Если они строки @@ -396,38 +392,38 @@ public static function sort2dArray( // Массивы меньших и массивы больших прогоняем по тому же алгоритму (если в них что-то есть) $resultArrayLeft = - count($resultArrayLeft) > 1 ? - self::sort2dArray( + count($resultArrayLeft) > 1 + ? self::sort2dArray( $resultArrayLeft, $sortBy, $sortDir, $i - ) : - $resultArrayLeft + ) + : $resultArrayLeft ; $resultArrayRight = - count($resultArrayRight) > 1 ? - self::sort2dArray( + count($resultArrayRight) > 1 + ? self::sort2dArray( $resultArrayRight, $sortBy, $sortDir, $i - ) : - $resultArrayRight + ) + : $resultArrayRight ; // Массив одинаковых прогоняем по следующему условию сортировки (если есть условие и есть что сортировать) $resultArrayCenter = ( - count($resultArrayCenter) > 1 && - $sortBy[$i + 1] - ) ? - self::sort2dArray( + count($resultArrayCenter) > 1 + && $sortBy[$i + 1] + ) + ? self::sort2dArray( $resultArrayCenter, $sortBy, $sortDir, $i + 1 - ) : - $resultArrayCenter + ) + : $resultArrayCenter ; // Склеиваем отсортированные меньшие, средние и большие @@ -440,7 +436,7 @@ public static function sort2dArray( /** * parseFileNameVersion - * @version 1.1.5 (2024-08-04) + * @version 1.1.6 (2024-12-03) * * @desc Parses a file path and gets its name, version & extension. * @@ -458,9 +454,9 @@ public static function parseFileNameVersion($file){ $fileinfo = $file; // А также запоминаем строку $file = - $fileinfo['dirname'] . - '/' . - $fileinfo['basename'] + $fileinfo['dirname'] + . '/' + . $fileinfo['basename'] ; // Если передали строку }else{ @@ -473,9 +469,9 @@ public static function parseFileNameVersion($file){ 'name' => strtolower($file), 'version' => '0', 'extension' => - !$fileinfo['extension'] ? - '' : - $fileinfo['extension'] + !$fileinfo['extension'] + ? '' + : $fileinfo['extension'] ]; // Try to get file version [0 — full name, 1 — script name, 2 — version, 3 — all chars after version] @@ -496,7 +492,7 @@ public static function parseFileNameVersion($file){ /** * convertUrlToAbsolute - * @version 1.0.2 (2024-08-04) + * @version 1.0.3 (2024-12-03) * * @desc Converts relative URLs to absolute. * @@ -524,14 +520,14 @@ public static function convertUrlToAbsolute($params){ if (is_null($params->scheme)){ $params->scheme = ( - isset($_SERVER['HTTPS']) && - ( - $_SERVER['HTTPS'] == 'on' || - $_SERVER['HTTPS'] == 1 + isset($_SERVER['HTTPS']) + && ( + $_SERVER['HTTPS'] == 'on' + || $_SERVER['HTTPS'] == 1 ) - ) ? - 'https' : - 'http' + ) + ? 'https' + : 'http' ; } @@ -549,9 +545,9 @@ public static function convertUrlToAbsolute($params){ '//' ){ $result = - $params->scheme . - ':' . - $params->url + $params->scheme + . ':' + . $params->url ; // E. g. 'https://example.com/some/url' }elseif ( @@ -570,18 +566,18 @@ public static function convertUrlToAbsolute($params){ 0 ){ $result = - $params->scheme . - '://' . - $params->url + $params->scheme + . '://' + . $params->url ; // E. g. 'some/url', '/some/url' }else{ $result = - $params->scheme . - '://' . - $params->host . - '/' . - ltrim( + $params->scheme + . '://' + . $params->host + . '/' + . ltrim( $params->url, '/' ) @@ -699,7 +695,7 @@ public static function escapeForJS($str){ /** * getPlaceholdersFromText - * @version 1.0.3 (2024-08-04) + * @version 1.0.4 (2024-12-03) * * @desc Finds all placeholders' names and returns them as an array. * @@ -728,11 +724,11 @@ public static function getPlaceholdersFromText($params = []){ preg_match_all( ( - '/' . - $params->placeholderPrefix . - '(.*?)' . - $params->placeholderSuffix . '/' + . $params->placeholderPrefix + . '(.*?)' + . $params->placeholderSuffix + . '/' ), $params->text, $result @@ -745,7 +741,7 @@ public static function getPlaceholdersFromText($params = []){ /** * logEvent - * @version 1.0.4 (2024-08-04) + * @version 1.0.5 (2024-12-03) * * @desc Add an alert message to the system event log with debug info (backtrace, snippet name, document id, etc). * @@ -782,11 +778,11 @@ public static function logEvent($params){ $caller = $params->backtraceArray[0]; $caller = ( - isset($caller['class']) ? - $caller['class'] . '->' : - '' - ) . - $caller['function'] + isset($caller['class']) + ? $caller['class'] . '->' + : '' + ) + . $caller['function'] ; @@ -795,9 +791,9 @@ public static function logEvent($params){ // Add current document Id to debug info if (!empty(self::$modx->documentIdentifier)){ $debugInfo[] = - '
  • Document id: “' . - self::$modx->documentIdentifier . - '”;
  • ' + '
  • Document id: “' + . self::$modx->documentIdentifier + . '”;
  • ' ; } @@ -810,9 +806,9 @@ public static function logEvent($params){ }else{ // Add to debug info $debugInfo[] = - '
  • Snippet: “' . - self::$modx->currentSnippet . - '”;
  • ' + '
  • Snippet: “' + . self::$modx->currentSnippet + . '”;
  • ' ; } } @@ -827,12 +823,12 @@ public static function logEvent($params){ if (!empty($debugInfo)){ $params->message .= - '' ; } @@ -907,7 +903,7 @@ public static function getTpl($tpl = ''){ /** * parseText - * @version 1.9.2 (2024-08-04) + * @version 1.9.3 (2024-12-03) * * @see README.md */ @@ -927,9 +923,9 @@ public static function parseText($params = []){ ]); foreach ( - $params->data as - $key => - $value + $params->data + as $key + => $value ){ $result = static::parseText_parseItem([ 'text' => $result, @@ -1006,7 +1002,7 @@ private static function parseText_parepareParams($params = []): \stdClass { /** * parseText_prepareData - * @version 1.0.2 (2024-08-04) + * @version 1.0.3 (2024-12-03) * * @param $params {stdClass|arrayAssociative} — The parameters object. See $this->parseText. * @param $params->data {stdClass|array|string} @@ -1020,8 +1016,8 @@ private static function parseText_prepareData($params = []): \stdClass { // Arrays and objects are already ready to use if ( - !is_object($params->data) && - !is_array($params->data) + !is_object($params->data) + && !is_array($params->data) ){ $params->data = \DDTools\Tools\Objects::convertType([ 'object' => $params->data, @@ -1030,13 +1026,13 @@ private static function parseText_prepareData($params = []): \stdClass { } foreach ( - $params->data as - $key => - $value + $params->data + as $key + => $value ){ if ( - is_object($value) || - is_array($value) + is_object($value) + || is_array($value) ){ // Unfold for nested objects and arrays support (e. g. ['some' => ['a' => 'one', 'b' => 'two'] ] → '[+some.a+]', '[+some.b+]'; ['some' => ['one', 'two'] ] → '[+some.0+]', '[some.1]') $unfoldedValue = \DDTools\Tools\Objects::unfold([ @@ -1047,9 +1043,9 @@ private static function parseText_prepareData($params = []): \stdClass { ]); foreach ( - $unfoldedValue as - $unfoldedValue_itemKey => - $unfoldedValue_itemValue + $unfoldedValue + as $unfoldedValue_itemKey + => $unfoldedValue_itemValue ){ $result->{$unfoldedValue_itemKey} = $unfoldedValue_itemValue; } @@ -1117,7 +1113,7 @@ public static function parseSource($source){ /** * clearCache - * @version 1.1.1 (2024-08-04) + * @version 1.1.2 (2024-12-03) * * @desc Clears cache of required document(s) and their parents. * @@ -1146,34 +1142,34 @@ public static function clearCache($params){ } $cacheFilePrefix = - self::$modx->getConfig('base_path') . - self::$modx->getCacheFolder() . - 'docid_' + self::$modx->getConfig('base_path') + . self::$modx->getCacheFolder() + . 'docid_' ; $cacheFileSuffix = '.pageCache.php'; foreach ( - $params->docIds as - $docId + $params->docIds + as $docId ){ // $_GET cache $cacheFiles = glob( - $cacheFilePrefix . - $docId . - '_*' . - $cacheFileSuffix + $cacheFilePrefix + . $docId + . '_*' + . $cacheFileSuffix ); // Without $_GET $cacheFiles[] = - $cacheFilePrefix . - $docId . - $cacheFileSuffix + $cacheFilePrefix + . $docId + . $cacheFileSuffix ; foreach ( - $cacheFiles as - $cacheFiles_item + $cacheFiles + as $cacheFiles_item ){ if (!is_file($cacheFiles_item)){ continue; @@ -1197,7 +1193,7 @@ public static function clearCache($params){ /** * prepareDocData - * @version 2.0.5 (2024-08-04) + * @version 2.0.6 (2024-12-03) * * @desc Prepare document data from single array of fields and TVs: separate them and get TV IDs if needed. * @@ -1233,9 +1229,9 @@ public static function prepareDocData($params){ // Перебираем поля, раскидываем на поля документа и TV foreach ( - $params->data as - $data_itemFieldName => - $data_itemFieldValue + $params->data + as $data_itemFieldName + => $data_itemFieldValue ){ // Если это не поле документа if (!in_array( @@ -1251,9 +1247,9 @@ public static function prepareDocData($params){ } if ( - !empty($params->tvAdditionalFieldsToGet) && + !empty($params->tvAdditionalFieldsToGet) // Если есть хоть одна TV - count($result->tvsData) > 0 + && count($result->tvsData) > 0 ){ if (!in_array( 'name', @@ -1266,23 +1262,23 @@ public static function prepareDocData($params){ $dbRes = self::$modx->db->select( // Fields ( - '`' . - implode( + '`' + . implode( '`, `', $params->tvAdditionalFieldsToGet - ) . - '`' + ) + . '`' ), // From self::$tables['site_tmplvars'], // Where ( - "`name` IN ('" . - implode( + "`name` IN ('" + . implode( "','", array_keys($result->tvsData) - ) . - "')" + ) + . "')" ) ); @@ -1329,7 +1325,7 @@ private static function createDocument_prepareAlias($sourceString){ /** * createDocument - * @version 1.5.2 (2024-08-04) + * @version 1.5.3 (2024-12-03) * * @desc Create a new document. * @@ -1378,9 +1374,9 @@ public static function createDocument( $docAlias = $docData->alias; foreach ( - $docData as - $fieldName => - $fieldValue + $docData + as $fieldName + => $fieldValue ){ $docData->{$fieldName} = self::$modx->db->escape($fieldValue); } @@ -1407,14 +1403,14 @@ public static function createDocument( if (count($docData->tvsAdditionalData) > 0){ // Перебираем массив TV с ID foreach ( - $docData->tvsAdditionalData as - $tvName => - $tvData + $docData->tvsAdditionalData + as $tvName + => $tvData ){ if ( // Если это дата - $tvData['type'] == 'date' && - // И она задана как Unixtime + $tvData['type'] == 'date' + && // И она задана как Unixtime is_numeric($docData->tvsData[$tvName]) ){ // Приведём её к формату системы @@ -1439,8 +1435,8 @@ public static function createDocument( if ($docGroups){ // Перебираем все группы foreach ( - $docGroups as - $docGroupId + $docGroups + as $docGroupId ){ self::$modx->db->insert( // Field @@ -1456,14 +1452,14 @@ public static function createDocument( // Смотрим родителя нового документа, является ли он папкой и его псевдоним $docParent = - isset($docData->fieldsData['parent']) ? - $docData->fieldsData['parent'] : - 0 + isset($docData->fieldsData['parent']) + ? $docData->fieldsData['parent'] + : 0 ; $docIsFolder = - isset($docData->fieldsData['isfolder']) ? - $docData->fieldsData['isfolder'] : - 0 + isset($docData->fieldsData['isfolder']) + ? $docData->fieldsData['isfolder'] + : 0 ; // Пусть созданного документа @@ -1493,11 +1489,11 @@ public static function createDocument( // Добавляем в documentListing if(self::$modx->aliasListing[$docId]['path'] !== ''){ self::$modx->documentListing[ - self::$modx->aliasListing[$docId]['path'] . '/' . - ( + self::$modx->aliasListing[$docId]['path'] . '/' + . ( self::$modx->aliasListing[$docId]['alias'] != ''? - self::$modx->aliasListing[$docId]['alias'] : - self::$modx->aliasListing[$docId]['id'] + self::$modx->aliasListing[$docId]['alias'] + : self::$modx->aliasListing[$docId]['id'] ) ] = $docId; } @@ -1507,7 +1503,7 @@ public static function createDocument( /** * updateDocument - * @version 1.5.2 (2024-08-04) + * @version 1.5.3 (2024-12-03) * * @desc Update document(s). Cache of the updated docs and their parents will be cleared. * @@ -1526,8 +1522,8 @@ public static function updateDocument( ){ // Required parameters if ( - $docId == 0 && - trim($where) == '' + $docId == 0 + && trim($where) == '' ){ return false; } @@ -1549,21 +1545,21 @@ public static function updateDocument( $whereSql = ''; if ( - is_array($docId) && - count($docId) + is_array($docId) + && count($docId) ){ // Обрабатываем массив id $whereSql .= - '`id` IN ("' . - implode( + '`id` IN ("' + . implode( '","', $docId - ) . - '")' + ) + . '")' ; }elseif ( - is_numeric($docId) && - $docId != 0 + is_numeric($docId) + && $docId != 0 ){ // Обрабатываем числовой id $whereSql .= '`id`="' . $docId . '"'; @@ -1573,11 +1569,11 @@ public static function updateDocument( if ($where != ''){ $whereSql .= ( - $whereSql != '' ? - ' AND ' : - '' - ) . - $where + $whereSql != '' + ? ' AND ' + : '' + ) + . $where ; } @@ -1595,9 +1591,9 @@ public static function updateDocument( } foreach ( - $docData as - $fieldName => - $fieldValue + $docData + as $fieldName + => $fieldValue ){ $docData->{$fieldName} = self::$modx->db->escape($fieldValue); } @@ -1624,19 +1620,19 @@ public static function updateDocument( if (count($docData->tvsAdditionalData) > 0){ // Обновляем TV всех найденых документов foreach ( - $docIdsToUpdate as - $docId + $docIdsToUpdate + as $docId ){ // Перебираем массив существующих TV foreach ( - $docData->tvsAdditionalData as - $tvName => - $tvData + $docData->tvsAdditionalData + as $tvName + => $tvData ){ if ( // Если это дата - $tvData['type'] == 'date' && - // И она задана как Unixtime + $tvData['type'] == 'date' + && // И она задана как Unixtime is_numeric($docData->tvsData[$tvName]) ){ // Приведём её к формату системы @@ -1700,7 +1696,7 @@ public static function updateDocument( /** * getDocuments - * @version 1.2.9 (2024-08-04) + * @version 1.2.10 (2024-12-03) * * @desc Returns required documents (documents fields). * @@ -1770,8 +1766,8 @@ public static function getDocuments( }else{ // modify field names to use sc. table reference $fields = - 'sc.' . - implode( + 'sc.' + . implode( ',sc.', array_filter(array_map( 'trim', @@ -1783,11 +1779,11 @@ public static function getDocuments( ) ; $sort = - $sort == '' ? - '' : - ( - 'sc.' . - implode( + $sort == '' + ? '' + : ( + 'sc.' + . implode( ',sc.', array_filter(array_map( 'trim', @@ -1804,14 +1800,14 @@ public static function getDocuments( } $published = - $published !== 'all' ? - "AND sc.published = '{$published}'" : - '' + $published !== 'all' + ? "AND sc.published = '{$published}'" + : '' ; $deleted = - $deleted !== 'all' ? - "AND sc.deleted = '{$deleted}'" : - '' + $deleted !== 'all' + ? "AND sc.deleted = '{$deleted}'" + : '' ; $result = self::$modx->db->select( @@ -1824,24 +1820,24 @@ public static function getDocuments( ', // Where ( - '(sc.id IN (' . - implode( + '(sc.id IN (' + . implode( ',', $ids - ) . - ') ' . - $published . - ' ' . - $deleted . - ' ' . - $where . - ') GROUP BY sc.id' + ) + . ') ' + . $published + . ' ' + . $deleted + . ' ' + . $where + . ') GROUP BY sc.id' ), // Order ( - $sort ? - $sort . ' ' . $dir : - '' + $sort + ? $sort . ' ' . $dir + : '' ), // Limit $limit @@ -1919,7 +1915,7 @@ public static function getDocument( /** * getTemplateVars - * @version 1.3.11 (2024-08-04) + * @version 1.3.12 (2024-12-03) * * @desc Returns the TV and fields array of a document. * @@ -1954,10 +1950,10 @@ public static function getTemplateVars( } if ( - empty($idnames) || - ( - !is_array($idnames) && - $idnames != '*' + empty($idnames) + || ( + !is_array($idnames) + && $idnames != '*' ) ){ return false; @@ -1981,11 +1977,11 @@ public static function getTemplateVars( // get user defined template variables $fields = - $fields == '' ? - 'tv.*' : - ( - 'tv.' . - implode( + $fields == '' + ? 'tv.*' + : ( + 'tv.' + . implode( ',tv.', array_filter(array_map( 'trim', @@ -1998,11 +1994,11 @@ public static function getTemplateVars( ) ; $sort = - $sort == '' ? - '' : - ( - 'tv.' . - implode( + $sort == '' + ? '' + : ( + 'tv.' + . implode( ',tv.', array_filter(array_map( 'trim', @@ -2020,24 +2016,24 @@ public static function getTemplateVars( }else{ $query = ( - is_numeric($idnames[0]) ? - 'tv.id' : - 'tv.name' - ) . - ' IN ("' . - implode( + is_numeric($idnames[0]) + ? 'tv.id' + : 'tv.name' + ) + . ' IN ("' + . implode( '","', $idnames - ) . - '")' + ) + . '")' ; } $rs = self::$modx->db->select( // Fields ( - $fields . - ', IF(tvc.value != "", tvc.value, tv.default_text) as value' + $fields + . ', IF(tvc.value != "", tvc.value, tv.default_text) as value' ), // From self::$tables['site_tmplvars'] . ' tv @@ -2048,16 +2044,16 @@ public static function getTemplateVars( ', // Where ( - $query . - ' AND tvtpl.templateid = "' . - $docRow['template'] . - '"' + $query + . ' AND tvtpl.templateid = "' + . $docRow['template'] + . '"' ), // Order ( - $sort ? - $sort . ' ' . $dir : - '' + $sort + ? $sort . ' ' . $dir + : '' ) ); @@ -2067,13 +2063,13 @@ public static function getTemplateVars( ksort($docRow); foreach ( - $docRow as - $key => - $value + $docRow + as $key + => $value ){ if ( - $idnames == '*' || - in_array( + $idnames == '*' + || in_array( $key, $idnames ) @@ -2094,7 +2090,7 @@ public static function getTemplateVars( /** * getTemplateVarOutput - * @version 1.1.10 (2024-08-04) + * @version 1.1.11 (2024-12-03) * * @desc Returns the associative array of fields and TVs of a document. * @@ -2125,10 +2121,10 @@ public static function getTemplateVarOutput( } if ( - empty($idnames) || - ( - !is_array($idnames) && - $idnames != '*' + empty($idnames) + || ( + !is_array($idnames) + && $idnames != '*' ) ){ return false; @@ -2136,17 +2132,17 @@ public static function getTemplateVarOutput( $output = []; $vars = ( - $idnames == '*' || - is_array($idnames) - ) ? - $idnames : - [$idnames] + $idnames == '*' + || is_array($idnames) + ) + ? $idnames + : [$idnames] ; $docid = - intval($docid) ? - intval($docid) : - self::$modx->documentIdentifier + intval($docid) + ? intval($docid) + : self::$modx->documentIdentifier ; // remove sort for speed $result = self::getTemplateVars( @@ -2162,17 +2158,17 @@ public static function getTemplateVarOutput( return false; }else{ $baspath = - MODX_MANAGER_PATH . - 'includes' + MODX_MANAGER_PATH + . 'includes' ; include_once( - $baspath . - '/tmplvars.format.inc.php' + $baspath + . '/tmplvars.format.inc.php' ); include_once( - $baspath . - '/tmplvars.commands.inc.php' + $baspath + . '/tmplvars.commands.inc.php' ); for ( @@ -2204,7 +2200,7 @@ public static function getTemplateVarOutput( /** * getDocumentChildren - * @version 1.2.8 (2024-08-04) + * @version 1.2.9 (2024-12-03) * * @desc Returns the associative array of a document fields. * @@ -2253,14 +2249,14 @@ public static function getDocumentChildren( } $published = - $published !== 'all' ? - 'AND sc.published = ' . $published : - '' + $published !== 'all' + ? 'AND sc.published = ' . $published + : '' ; $deleted = - $deleted !== 'all' ? - 'AND sc.deleted = ' . $deleted : - '' + $deleted !== 'all' + ? 'AND sc.deleted = ' . $deleted + : '' ; if ($where != ''){ @@ -2269,8 +2265,8 @@ public static function getDocumentChildren( // Modify field names to use sc. table reference $fields = - 'sc.' . - implode( + 'sc.' + . implode( ',sc.', array_filter(array_map( 'trim', @@ -2282,11 +2278,11 @@ public static function getDocumentChildren( ) ; $sort = - $sort == '' ? - '' : - ( - 'sc.' . - implode( + $sort == '' + ? '' + : ( + 'sc.' + . implode( ',sc.', array_filter(array_map( 'trim', @@ -2310,14 +2306,14 @@ public static function getDocumentChildren( // Build query $access = ( - self::$modx->isFrontend() ? - 'sc.privateweb=0' : - '1="' . $_SESSION['mgrRole'] . '" OR sc.privatemgr=0' - ) . - ( - !$docgrp ? - '' : - ' OR dg.document_group IN (' . $docgrp . ')' + self::$modx->isFrontend() + ? 'sc.privateweb=0' + : '1="' . $_SESSION['mgrRole'] . '" OR sc.privatemgr=0' + ) + . ( + !$docgrp + ? '' + : ' OR dg.document_group IN (' . $docgrp . ')' ) ; @@ -2331,23 +2327,23 @@ public static function getDocumentChildren( ', // Where ( - 'sc.parent = "' . - $parentid . - '" ' . - $published . - ' ' . - $deleted . - ' ' . - $where . - ' AND (' . - $access . - ') GROUP BY sc.id' + 'sc.parent = "' + . $parentid + . '" ' + . $published + . ' ' + . $deleted + . ' ' + . $where + . ' AND (' + . $access + . ') GROUP BY sc.id' ), // Order ( - $sort ? - $sort . ' ' . $dir : - '' + $sort + ? $sort . ' ' . $dir + : '' ), // Limit $limit @@ -2360,7 +2356,7 @@ public static function getDocumentChildren( /** * getDocumentChildrenTVarOutput - * @version 1.3.6 (2024-08-04) + * @version 1.3.7 (2024-12-03) * * @desc Get necessary children of document. * @@ -2412,8 +2408,8 @@ public static function getDocumentChildrenTVarOutput( if ($resultKey !== false){ if (is_array($tvidnames)){ if ( - count($tvidnames) != 0 && - !in_array( + count($tvidnames) != 0 + && !in_array( $resultKey, $tvidnames ) @@ -2422,8 +2418,8 @@ public static function getDocumentChildrenTVarOutput( $unsetResultKey = true; } }elseif ( - $tvidnames != '*' && - $tvidnames != $resultKey + $tvidnames != '*' + && $tvidnames != $resultKey ){ $tvidnames = [ $tvidnames, @@ -2449,8 +2445,8 @@ public static function getDocumentChildrenTVarOutput( if ($tvs){ // Если нужно в качестве ключа использовать не индекс и такое поле есть if ( - $resultKey !== false && - array_key_exists( + $resultKey !== false + && array_key_exists( $resultKey, $tvs ) @@ -2474,7 +2470,7 @@ public static function getDocumentChildrenTVarOutput( /** * regEmptyClientScript - * @version 1.1.4 (2024-08-04) + * @version 1.1.5 (2024-12-03) * * @desc Adds a required JS-file into a required MODX inner list according to its version and name. The method is used to register the scripts, that has already been connected manually. * Be advised that the method does not add script code, but register its name and version to avoid future connections with $modx->regClientScript and $modx->regClientStartupScript, and the script code will be deleted if the script had been connected with $modx->regClientScript or $modx->regClientStartupScript. @@ -2513,15 +2509,15 @@ public static function regEmptyClientScript($params = []){ $name = strtolower($params->name); // Если версия не задана, будет нулевая (полезно дальше при сравнении version_compare) $version = - isset($params->version) ? - strtolower($params->version) : - '0' + isset($params->version) + ? strtolower($params->version) + : '0' ; // Куда подключён скрипт: перед , или перед $startup = - isset($params->startup) ? - $params->startup : - false + isset($params->startup) + ? $params->startup + : false ; // Ну мало ли unset($overwritepos); @@ -2546,20 +2542,20 @@ public static function regEmptyClientScript($params = []){ // Если надо юзать старую версию if (!$useThisVer){ - // Запомним версию как старую. Здесь нам пофиг на его код, ведь новый код будет подключен мануально. + // Запомним версию как старую. Здесь нам пофиг на его код, ведь новый код будет подключен мануально $version = self::$modx->loadedjscripts[$name]['version']; } // Если новая версия должна подключаться в
    , а старая подключалась перед if ( - $startup == true && - self::$modx->loadedjscripts[$name]['startup'] == false + $startup == true + && self::$modx->loadedjscripts[$name]['startup'] == false ){ - // Снесём старый скрипт из массива подключения перед (ведь новая подключится в ). Здесь нам пофиг на его код, ведь новый код будет подключен мануально. + // Снесём старый скрипт из массива подключения перед (ведь новая подключится в ). Здесь нам пофиг на его код, ведь новый код будет подключен мануально unset(self::$modx->jscripts[self::$modx->loadedjscripts[$name]['pos']]); - // Если новая версия должна подключаться перед или старая уже подключалась перед . На самом деле, сработает только если обе перед или обе перед , т.к. если старая была перед , то новая выставится также кодом выше. + // Если новая версия должна подключаться перед или старая уже подключалась перед . На самом деле, сработает только если обе перед или обе перед , т.к. если старая была перед , то новая выставится также кодом выше }else{ - // Запомним позицию старого скрипта (порядок подключения может быть важен для зависимых скриптов), на новую пофиг. Дальше код старой просто перетрётся в соответсвтии с позицией. + // Запомним позицию старого скрипта (порядок подключения может быть важен для зависимых скриптов), на новую пофиг. Дальше код старой просто перетрётся в соответсвтии с позицией $overwritepos = self::$modx->loadedjscripts[$name]['pos']; } } @@ -2568,23 +2564,23 @@ public static function regEmptyClientScript($params = []){ if ($startup){ // Позиция такова: либо старая (уже вычислена), либо максимальное значение между нолём и одним из ключей массива подключённых скриптов + 1 (это, чтобы заполнить возможные дыры) $pos = - isset($overwritepos) ? - $overwritepos : - max(array_merge( + isset($overwritepos) + ? $overwritepos + : max(array_merge( [0], array_keys(self::$modx->sjscripts) )) + 1 ; if ($useThisVer){ - // Запоминаем пустую строку подключения в нужный массив, т.к. подключаем мануально. + // Запоминаем пустую строку подключения в нужный массив, т.к. подключаем мануально self::$modx->sjscripts[$pos] = ''; } // Если надо подключить перед , то всё по аналогии, только массив другой }else{ $pos = - isset($overwritepos) ? - $overwritepos : - max(array_merge( + isset($overwritepos) + ? $overwritepos + : max(array_merge( [0], array_keys(self::$modx->jscripts) )) + 1 @@ -2678,7 +2674,7 @@ public static function getDocumentParentIds($params){ /** * getDocumentIdByUrl - * @version 1.2.2 (2024-08-04) + * @version 1.2.3 (2024-12-03) * * @desc Gets id of a document by its url. * @@ -2697,9 +2693,9 @@ public static function getDocumentIdByUrl($url){ // For domains in IDNA ASCII-compatible format $siteHost['host'] = - function_exists('idn_to_utf8') ? - idn_to_utf8($siteHost['host']) : - $siteHost['host'] + function_exists('idn_to_utf8') + ? idn_to_utf8($siteHost['host']) + : $siteHost['host'] ; // На всякий случай вышережем host из адреса (а то вдруг url просто без http:// передали) + лишние слэши по краям @@ -2730,7 +2726,7 @@ function_exists('idn_to_utf8') ? /** * verifyRenamedParams - * @version 1.7.3 (2024-08-04) + * @version 1.7.4 (2024-12-03) * * @see README.md */ @@ -2769,9 +2765,9 @@ public static function verifyRenamedParams($params){ // Перебираем таблицу соответствия foreach ( - $params->compliance as - $newName => - $oldNames + $params->compliance + as $newName + => $oldNames ){ // Если параметр с новым именем не задан if (!isset($params->params[$newName])){ @@ -2793,14 +2789,14 @@ public static function verifyRenamedParams($params){ // If need to write to the CMS event log if ($params->writeToLog){ $logMessageItems[] .= - '
  • ' . - implode( + '
  • ' + . implode( ', ', $oldNames - ) . - ' must be renamed as ' . - $newName . - ';
  • ' + ) + . ' must be renamed as ' + . $newName + . ';' ; } } @@ -2825,13 +2821,13 @@ public static function verifyRenamedParams($params){ // If there is something to write to the CMS event log if (count($logMessageItems) > 0){ self::logEvent([ - 'message' => - '

    Some of the snippet parameters have been renamed. Please, correct the following parameters:

    ' ]); } @@ -2844,7 +2840,7 @@ public static function verifyRenamedParams($params){ /** * sendMail - * @version 3.0.4 (2024-08-04) + * @version 3.0.5 (2024-12-03) * * @desc Method for sending e-mails. * @@ -2894,8 +2890,8 @@ public static function sendMail($params){ // Перебираем имена полей с файлами foreach( - $params->fileInputNames as - $value + $params->fileInputNames + as $value ){ // Проверяем находится ли в POST массив if(is_array($_FILES[$value]['name'])){ @@ -2904,9 +2900,9 @@ public static function sendMail($params){ // Перебираем пост foreach( - $_FILES[$value]['name'] as - $key => - $name + $_FILES[$value]['name'] + as $key + => $name ){ // Если нет ошибок if ($_FILES[$value]['error'][$key] == 0){ @@ -2935,8 +2931,8 @@ public static function sendMail($params){ $result = []; foreach ( - $params->to as - $val + $params->to + as $val ){ // Если адрес валидный if (filter_var( @@ -2947,15 +2943,15 @@ public static function sendMail($params){ self::$modx->mail->AddAddress($val); self::$modx->mail->From = $params->from; - self::$modx->mail->FromName = self::$modx->config['site_name']; - self::$modx->mail->Subject = $params->subject; - self::$modx->mail->Body = $message; + self::$modx->mail->FromName = self::$modx->config['site_name']; + self::$modx->mail->Subject = $params->subject; + self::$modx->mail->Body = $message; // Перебираем присоединяемые файлы if(!empty($attachFiles)){ foreach( - $attachFiles as - $value + $attachFiles + as $value ){ // добавить еще парамет name self::$modx->mail->AddAttachment( @@ -2991,7 +2987,7 @@ public static function getResponse(){ /** * encodedStringToArray - * @version 1.2.2 (2024-08-04) + * @version 1.2.3 (2024-12-03) * * @desc Converts encoded strings to arrays. * Supported formats: @@ -3010,15 +3006,15 @@ public static function encodedStringToArray($inputString){ // The old deprecated format where string is separated by '||' and '::' if ( - count($result) == 1 && - array_keys($result)[0] == $inputString + count($result) == 1 + && array_keys($result)[0] == $inputString ){ $result = self::explodeAssoc($inputString); self::logEvent([ 'message' => - '

    Strings separated by :: && || in parameters are deprecated.

    ' . - '

    Use JSON or Query string instead.

    ' + '

    Strings separated by :: && || in parameters are deprecated.

    ' + . '

    Use JSON or Query string instead.

    ' ]); } @@ -3140,9 +3136,9 @@ public static function explodeFieldsArr($fields = []){ $result[0] = $docData->fieldsData; // And TVs foreach ( - $docData->tvsData as - $tvName => - $tvValue + $docData->tvsData + as $tvName + => $tvValue ){ $result[1][$tvName] = ['val' => $tvValue]; diff --git a/src/Base/Base.php b/src/Base/Base.php index 96b4c97..9bdb2cc 100644 --- a/src/Base/Base.php +++ b/src/Base/Base.php @@ -85,7 +85,7 @@ public static function getClassName(): \stdClass { /** * setExistingProps - * @version 1.4.1 (2024-08-02) + * @version 1.4.2 (2024-12-03) * * @see README.md * @@ -100,9 +100,9 @@ public function setExistingProps($props){ } foreach ( - $props as - $propName => - $propValue + $props + as $propName + => $propValue ){ $this->ddSetProp([ 'object' => $this, @@ -168,7 +168,7 @@ private function ddSetProp($params){ /** * ddGetPropValues - * @version 1.0 (2020-05-06) + * @version 1.0.1 (2024-12-03) * * @throws \ReflectionException * @@ -189,8 +189,8 @@ private function ddGetPropValues($class = null){ if (!empty($reflectionProperties)){ foreach( - $reflectionProperties as - $reflectionProperty + $reflectionProperties + as $reflectionProperty ){ if (!$reflectionProperty->isPublic()){ $reflectionProperty->setAccessible(true); diff --git a/src/ObjectCollection/ObjectCollection.php b/src/ObjectCollection/ObjectCollection.php index dfcb0b2..52d7a7f 100644 --- a/src/ObjectCollection/ObjectCollection.php +++ b/src/ObjectCollection/ObjectCollection.php @@ -2,13 +2,11 @@ namespace DDTools; class ObjectCollection extends \DDTools\Base\Base { - protected - /** - * @property $items {array} - * @property $items[$itemIndex] {array|object} - */ - $items = [] - ; + /** + * @property $items {array} + * @property $items[$itemIndex] {array|object} + */ + protected $items = []; /** * __construct @@ -36,7 +34,7 @@ public function setItems($params = []){ /** * addItems - * @version 1.2.2 (2024-08-04) + * @version 1.2.3 (2024-12-03) * * @see README.md */ @@ -70,9 +68,9 @@ public function addItems($params = []){ // If need to convert type of items if (!is_null($params->itemType)){ foreach ( - $params->items as - $itemIndex => - $itemObject + $params->items + as $itemIndex + => $itemObject ){ $params->items[$itemIndex] = \DDTools\Tools\Objects::convertType([ 'object' => $itemObject, @@ -90,7 +88,7 @@ public function addItems($params = []){ /** * convertItemsType - * @version 1.0.5 (2024-08-04) + * @version 1.0.6 (2024-12-03) * * @see README.md */ @@ -112,9 +110,9 @@ public function convertItemsType($params = []){ // # Run foreach ( - $this->items as - $itemIndex => - $itemObject + $this->items + as $itemIndex + => $itemObject ){ if ( // If item is matched to filter @@ -138,7 +136,7 @@ public function convertItemsType($params = []){ /** * updateItems - * @version 1.0.5 (2024-08-04) + * @version 1.0.6 (2024-12-03) * * @see README.md */ @@ -163,9 +161,9 @@ public function updateItems($params = []){ $affectedCount = 0; foreach ( - $this->items as - $itemIndex => - $itemObject + $this->items + as $itemIndex + => $itemObject ){ if ( // If item is matched to filter @@ -200,7 +198,7 @@ public function updateItems($params = []){ /** * getItems - * @version 2.0.4 (2024-08-04) + * @version 2.0.5 (2024-12-03) * * @see README.md */ @@ -228,8 +226,8 @@ public function getItems($params = []){ // Filter items foreach ( - $this->items as - $itemObject + $this->items + as $itemObject ){ if ( // If item is matched to filter @@ -315,7 +313,7 @@ public function getOneItem($params = []){ /** * deleteItems - * @version 1.0.3 (2024-08-04) + * @version 1.0.4 (2024-12-03) * * @see README.md */ @@ -339,9 +337,9 @@ public function deleteItems($params = []){ $affectedCount = 0; foreach ( - $this->items as - $itemIndex => - $itemObject + $this->items + as $itemIndex + => $itemObject ){ if ( // If item is matched to filter @@ -412,7 +410,7 @@ protected function getOneItemData($params){ /** * isItemMatchFilter - * @version 2.0.3 (2024-08-04) + * @version 2.0.4 (2024-12-03) * * @param $params {stdClass|arrayAssociative} — The parameters object. @required * @param $params->itemObject {array|object} — An item to test. @required @@ -432,13 +430,13 @@ private function isItemMatchFilter($params){ // Iterate over “or” conditions foreach ( - $params->filter as - $orCondition + $params->filter + as $orCondition ){ // Iterate over “and” conditions foreach ( - $orCondition as - $andCondition + $orCondition + as $andCondition ){ // If the item has no the property if ( @@ -488,7 +486,7 @@ private function isItemMatchFilter($params){ /** * prepareItemsFilter - * @version 1.0.1 (2024-08-04) + * @version 1.0.2 (2024-12-03) * * @param $filter {string} * @@ -511,9 +509,9 @@ private function prepareItemsFilter($filter = ''){ // Iterate over “or” conditions foreach ( - $filter as - $orIndex => - $orCondition + $filter + as $orIndex + => $orCondition ){ $result[$orIndex] = []; @@ -523,9 +521,9 @@ private function prepareItemsFilter($filter = ''){ explode( '&&', $orCondition - ) as - $andIndex => - $andCondition + ) + as $andIndex + => $andCondition ){ // Condition object $result[$orIndex][$andIndex] = (object) [ diff --git a/src/Response/Response.php b/src/Response/Response.php index cdf82ff..c9ef614 100644 --- a/src/Response/Response.php +++ b/src/Response/Response.php @@ -2,46 +2,42 @@ namespace DDTools; class Response { - protected static - /** - * @property $allowedMetaKeys {array} — Allowed keys in $this->meta. - */ - $allowedMetaKeys = [ - 'code', - 'eTag', - 'success', - 'message' - ], - /** - * @property $allowedMetaMessageKeys {array} — Allowed keys in $this->meta['message']. - */ - $allowedMetaMessageKeys = [ - 'content', - 'title' - ], - /** - * @property $requiredMetaKeys {array} — Required keys in $this->meta. - */ - $requiredMetaKeys = [ - 'code', - 'success' - ], - /** - * @property $requiredMetaMessageKeys {array} — Required keys in $this->meta['message']. - */ - $requiredMetaMessageKeys = [ - 'content' - ] - ; + /** + * @property $allowedMetaKeys {array} — Allowed keys in $this->meta. + */ + protected static $allowedMetaKeys = [ + 'code', + 'eTag', + 'success', + 'message' + ]; + /** + * @property $allowedMetaMessageKeys {array} — Allowed keys in $this->meta['message']. + */ + protected static $allowedMetaMessageKeys = [ + 'content', + 'title' + ]; + /** + * @property $requiredMetaKeys {array} — Required keys in $this->meta. + */ + protected static $requiredMetaKeys = [ + 'code', + 'success' + ]; + /** + * @property $requiredMetaMessageKeys {array} — Required keys in $this->meta['message']. + */ + protected static $requiredMetaMessageKeys = [ + 'content' + ]; - protected - $meta, - $data - ; + protected $meta; + protected $data; /** * validateMeta - * @version 1.1.2 (2024-08-04) + * @version 1.1.3 (2024-12-03) * * @param $meta {arrayAssociative} — Is an array of meta data. The method excludes any values passed in $meta except “code”, “eTag”, “success”, * and “message”. $meta['code'] and $meta['success'] are required. If defined, $meta['message'] must be an associative array with content @@ -79,21 +75,21 @@ public function validateMeta($meta){ !count(array_diff( static::$requiredMetaKeys, $paramKeys - )) && + )) // And only allowed items are set - !count(array_diff( + && !count(array_diff( $paramKeys, static::$allowedMetaKeys - )) && + )) // code is int - is_int($meta['code']) && + && is_int($meta['code']) // success is bool - is_bool($meta['success']) && - ( + && is_bool($meta['success']) + && ( // message is not set - !isset($meta['message']) || + !isset($meta['message']) // Or is valid - $this->validateMetaMessage($meta['message']) + || $this->validateMetaMessage($meta['message']) ) ){ $result = true; @@ -105,7 +101,7 @@ public function validateMeta($meta){ /** * validateMetaMessage - * @version 1.1.1 (2024-08-04) + * @version 1.1.2 (2024-12-03) * * @param $message {arrayAssociative} — @reuired * @param $message['content'] {string} — @required @@ -125,14 +121,14 @@ public function validateMetaMessage($message){ !count(array_diff( static::$requiredMetaMessageKeys, $paramKeys - )) && + )) // And only allowed items are set - !count(array_diff( + && !count(array_diff( $paramKeys, static::$allowedMetaMessageKeys - )) && + )) // content is string - is_string($message['content']) + && is_string($message['content']) ){ $result = true; } @@ -143,7 +139,7 @@ public function validateMetaMessage($message){ /** * setMeta - * @version 1.4.3 (2024-08-04) + * @version 1.4.4 (2024-12-03) * * @desc Setter for $this->meta. * @@ -180,9 +176,9 @@ public function setMeta($meta = []){ ){ // Depends on success by default $meta['code'] = - $meta['success'] ? - 200 : - 400 + $meta['success'] + ? 200 + : 400 ; } @@ -238,7 +234,7 @@ public function setData($data){ /** * setMetaData - * @version 1.0.3 (2024-08-04) + * @version 1.0.4 (2024-12-03) * * @desc Setter for $this->meta and $this->data. * @@ -251,14 +247,14 @@ public function setMetaData($params){ if (!is_array($params)){ $params = \DDTools\Tools\Objects::convertType([ 'object' => $params, - 'type' => 'objectArray' + 'type' => 'objectArray', ]); } if ( \DDTools\Tools\Objects::isPropExists([ 'object' => $params, - 'propName' => 'meta' + 'propName' => 'meta', ]) ){ $this->setMeta($params['meta']); @@ -267,7 +263,7 @@ public function setMetaData($params){ if ( \DDTools\Tools\Objects::isPropExists([ 'object' => $params, - 'propName' => 'data' + 'propName' => 'data', ]) ){ $this->setData($params['data']); @@ -298,7 +294,7 @@ public function getData(){ /** * isSuccess - * @version 1.0.1 (2024-08-04) + * @version 1.0.2 (2024-12-03) * * @return {boolean} */ @@ -307,9 +303,9 @@ public function isSuccess(){ if ( // If meta is set - is_array($this->meta) && + is_array($this->meta) // And success - $this->meta['success'] + && $this->meta['success'] ){ $result = true; } diff --git a/src/Snippet/Snippet.php b/src/Snippet/Snippet.php index 59caf08..a1425b9 100644 --- a/src/Snippet/Snippet.php +++ b/src/Snippet/Snippet.php @@ -2,47 +2,45 @@ namespace DDTools; abstract class Snippet { - protected - /** - * @property $name {string} — Constructor fills it from namespace. - */ - $name = '', - - /** - * @property $version {string} — Set in children classes. - */ - $version = '', - - /** - * @property $paths {stdClass} - * @property $paths->snippet {string} — Full path to the snippet folder. - * @property $paths->src {string} — Ful path to `src`. - */ - $paths = [ - 'snippet' => '/', - 'src' => 'src/' - ], - - /** - * @property $params {stdClass} — Overwrite with defaults in children classes. - */ - $params = [], - - /** - * @property $paramsTypes {arrayAssociative} — Overwrite in child classes if you want to convert some parameters types. - * @property $paramsTypes[$paramName] {'integer'|'boolean'|'objectAuto'|'objectStdClass'|'objectArray'|'stringJsonAuto'|'stringJsonObject'|'stringJsonArray'} — The parameter type. - */ - $paramsTypes = [], - - /** - * @property $renamedParamsCompliance {arrayAssociative} — Overwrite in child classes if you want to rename some parameters with backward compatibility (see \ddTools::verifyRenamedParams). - */ - $renamedParamsCompliance = [] - ; + /** + * @property $name {string} — Constructor fills it from namespace. + */ + protected $name = ''; + + /** + * @property $version {string} — Set in children classes. + */ + protected $version = ''; + + /** + * @property $paths {stdClass} + * @property $paths->snippet {string} — Full path to the snippet folder. + * @property $paths->src {string} — Ful path to `src`. + */ + protected $paths = [ + 'snippet' => '/', + 'src' => 'src/' + ]; + + /** + * @property $params {stdClass} — Overwrite with defaults in children classes. + */ + protected $params = []; + + /** + * @property $paramsTypes {arrayAssociative} — Overwrite in child classes if you want to convert some parameters types. + * @property $paramsTypes[$paramName] {'integer'|'boolean'|'objectAuto'|'objectStdClass'|'objectArray'|'stringJsonAuto'|'stringJsonObject'|'stringJsonArray'} — The parameter type. + */ + protected $paramsTypes = []; + + /** + * @property $renamedParamsCompliance {arrayAssociative} — Overwrite in child classes if you want to rename some parameters with backward compatibility (see \ddTools::verifyRenamedParams). + */ + protected $renamedParamsCompliance = []; /** * __construct - * @version 1.1.2 (2024-08-04) + * @version 1.1.3 (2024-12-03) * * @param $params {stdClass|arrayAssociative|stringJsonObject|stringQueryFormatted} */ @@ -69,15 +67,15 @@ public function __construct($params = []){ dirname( __DIR__, 4 - ) . - '/snippets/' . - $this->name . - $this->paths->snippet + ) + . '/snippets/' + . $this->name + . $this->paths->snippet ; $this->paths->src = - $this->paths->snippet . - $this->paths->src + $this->paths->snippet + . $this->paths->src ; @@ -87,7 +85,7 @@ public function __construct($params = []){ /** * prepareParams - * @version 1.1.3 (2024-08-04) + * @version 1.1.4 (2024-12-03) * * @param $params {stdClass|arrayAssociative|stringJsonObject|stringQueryFormatted} * @@ -112,9 +110,9 @@ protected function prepareParams($params = []){ if (!empty($this->paramsTypes)){ foreach ( - $this->paramsTypes as - $paramName => - $paramType + $this->paramsTypes + as $paramName + => $paramType ){ $paramType = strtolower($paramType); @@ -172,7 +170,7 @@ public abstract function run(); /** * runSnippet - * @version 1.0.2 (2024-08-04) + * @version 1.0.3 (2024-12-03) * * @param $params {stdClass|arrayAssociative|stringJsonObject|stringQueryFormatted} * @param $params->name {string} @@ -204,31 +202,31 @@ public static function runSnippet($params){ dirname( __DIR__, 4 - ) . - '/snippets/' . - $params->name . - '/' + ) + . '/snippets/' + . $params->name + . '/' , 'snippetFile' => 'src/Snippet.php', 'requireFile' => 'require.php' ]; $requireData->snippetFile = - $requireData->snippetDir . - $requireData->snippetFile + $requireData->snippetDir + . $requireData->snippetFile ; $requireData->requireFile = - $requireData->snippetDir . - $requireData->requireFile + $requireData->snippetDir + . $requireData->requireFile ; if (file_exists($requireData->snippetFile)){ require_once($requireData->requireFile); $snippetClass = - '\\' . - $params->name . - '\Snippet' + '\\' + . $params->name + . '\Snippet' ; $snippetObject = new $snippetClass($params->params); diff --git a/src/Storage/DB/Storage.php b/src/Storage/DB/Storage.php index f97d96e..9180332 100644 --- a/src/Storage/DB/Storage.php +++ b/src/Storage/DB/Storage.php @@ -2,50 +2,46 @@ namespace DDTools\Storage\DB; class Storage extends \DDTools\Storage\Storage { - protected static - /** - * @property $columnsDefaultParams {stdClass} — Default parameters for all columns. If some items are not defined in child classes, parent values will be used (see static::initStatic). - * @property $columnsDefaultParams->{$paramName} {mixed} — Key is a property name, value is a default value that will be used if the property is undefined. - */ - $columnsDefaultParams = [ - 'attrs' => 'VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL', - 'isReadOnly' => false, - 'isPublic' => false, - 'isComparedCaseSensitive' => false, - 'isTagsAllowed' => false, - ] - ; + /** + * @property $columnsDefaultParams {stdClass} — Default parameters for all columns. If some items are not defined in child classes, parent values will be used (see static::initStatic). + * @property $columnsDefaultParams->{$paramName} {mixed} — Key is a property name, value is a default value that will be used if the property is undefined. + */ + protected static $columnsDefaultParams = [ + 'attrs' => 'VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL', + 'isReadOnly' => false, + 'isPublic' => false, + 'isComparedCaseSensitive' => false, + 'isTagsAllowed' => false, + ]; - protected - /** - * @property $nameAlias {string} — Short table name (e. g. 'web_users'), full table name will be built from it. Must be defined in child classes or passed to constructor. - * @property $nameFull {string} — Full table name. Will be built automatically from $this->nameAlias. - */ - $nameAlias = '', - $nameFull = '', - - /** - * @property $columns {\DDTools\ObjectCollection} — Table columns. - * @property $columns->items[$i] {stdClass} — Column data. - * @property $columns->items[$i]->name {string} — Column name. - * @property $columns->items[$i]->attrs {string} — Column attributes (empty value means static::$columnsDefaultParams->attrs). Default: —. - * @property $columns->items[$i]->isReadOnly {boolean} — Can column be modified? Default: false. - * @property $columns->items[$i]->isPublic {boolean} — Can column be used quite safely? Default: false. - * @property $columns->items[$i]->isComparedCaseSensitive {boolean} — Should column to be compared case-sensitive in where clauses? Default: false. - * @property $columns->items[$i]->isTagsAllowed {boolean} — Are HTML and MODX tags allowed? Default: false. - */ - $columns = [ - [ - 'name' => 'id', - 'attrs' => 'INTEGER(10) AUTO_INCREMENT PRIMARY KEY', - 'isReadOnly' => true, - ], - ] - ; + /** + * @property $nameAlias {string} — Short table name (e. g. 'web_users'), full table name will be built from it. Must be defined in child classes or passed to constructor. + * @property $nameFull {string} — Full table name. Will be built automatically from $this->nameAlias. + */ + protected $nameAlias = ''; + protected $nameFull = ''; + + /** + * @property $columns {\DDTools\ObjectCollection} — Table columns. + * @property $columns->items[$i] {stdClass} — Column data. + * @property $columns->items[$i]->name {string} — Column name. + * @property $columns->items[$i]->attrs {string} — Column attributes (empty value means static::$columnsDefaultParams->attrs). Default: —. + * @property $columns->items[$i]->isReadOnly {boolean} — Can column be modified? Default: false. + * @property $columns->items[$i]->isPublic {boolean} — Can column be used quite safely? Default: false. + * @property $columns->items[$i]->isComparedCaseSensitive {boolean} — Should column to be compared case-sensitive in where clauses? Default: false. + * @property $columns->items[$i]->isTagsAllowed {boolean} — Are HTML and MODX tags allowed? Default: false. + */ + protected $columns = [ + [ + 'name' => 'id', + 'attrs' => 'INTEGER(10) AUTO_INCREMENT PRIMARY KEY', + 'isReadOnly' => true, + ], + ]; /** * initStatic - * @version 1.1.3 (2024-08-04) + * @version 1.1.4 (2024-12-03) * * @desc Static “constructor”. * @@ -60,15 +56,15 @@ private static function initStatic(): void { // Parent (\DDTools\DB\Table::$columnsDefaultParams) (object) self::$columnsDefaultParams, // Child (e.g. \Something\Table\Base\Table::$columnsDefaultParams) - static::$columnsDefaultParams - ] + static::$columnsDefaultParams, + ], ]); } } /** * __construct - * @version 3.0.2 (2024-08-04) + * @version 3.0.3 (2024-12-03) * * @param [$params] {arrayAssociative|stdClass} — The parameters object. * @param [$params->nameAlias=''] {string} — Short table name (e. g. 'site_content'). You can define it in child classes or pass to the constructor directly. @@ -85,10 +81,10 @@ public function __construct($params = []){ $params = \DDTools\Tools\Objects::extend([ 'objects' => [ (object) [ - 'columns' => [] + 'columns' => [], ], - $params - ] + $params, + ], ]); // Init static @@ -101,7 +97,7 @@ public function __construct($params = []){ /** * construct_props - * @version 2.0.2 (2024-08-04) + * @version 2.0.3 (2024-12-03) * * @param $params {stdClass} — Parameters, see $this->__construct. * @@ -123,8 +119,8 @@ private function construct_props($params): void { if (!empty($params->columns)){ // Save additional columns to others foreach ( - $params->columns as - $columnParams + $params->columns + as $columnParams ){ // If column is set as a simple string name if (is_string($columnParams)){ @@ -153,7 +149,7 @@ private function construct_props($params): void { /** * construct_db - * @version 1.0.3 (2024-08-04) + * @version 1.0.4 (2024-12-03) * * @return {void} */ @@ -162,10 +158,10 @@ private function construct_db(): void { if (!empty($this->nameAlias)){ $isTableExist = boolval( \ddTools::$modx->db->getValue( - 'show tables like "' . - \ddTools::$modx->db->config['table_prefix'] . - $this->nameAlias . - '"' + 'show tables like "' + . \ddTools::$modx->db->config['table_prefix'] + . $this->nameAlias + . '"' ) ); @@ -188,13 +184,13 @@ private function construct_db(): void { } foreach ( - $this->columns->getItems() as - $columnData + $this->columns->getItems() + as $columnData ){ foreach ( - static::$columnsDefaultParams as - $propName => - $propDefaultValue + static::$columnsDefaultParams + as $propName + => $propDefaultValue ){ if ( !\DDTools\Tools\Objects::isPropExists([ @@ -215,13 +211,13 @@ private function construct_db(): void { ){ $columnsQuery[] = ( - $isTableExist ? - 'ADD ' : - '' - ) . - $columnData->name . - ' ' . - $columnData->attrs + $isTableExist + ? 'ADD ' + : '' + ) + . $columnData->name + . ' ' + . $columnData->attrs ; } } @@ -236,19 +232,19 @@ private function construct_db(): void { if ($isTableExist){ // Create missing columns $resultQuery = - 'ALTER TABLE ' . - $this->nameFull . - ' ' . - $columnsQuery + 'ALTER TABLE ' + . $this->nameFull + . ' ' + . $columnsQuery ; }else{ // Create table with needed columns $resultQuery = - 'CREATE TABLE IF NOT EXISTS ' . - $this->nameFull . - ' (' . - $columnsQuery . - ')' + 'CREATE TABLE IF NOT EXISTS ' + . $this->nameFull + . ' (' + . $columnsQuery + . ')' ; } @@ -320,7 +316,7 @@ protected function cols_getOneColParam($params = []){ /** * cols_getValidNames - * @version 1.1.4 (2024-08-04) + * @version 1.1.5 (2024-12-03) * * @desc Gets valid column names. * @@ -346,8 +342,8 @@ protected function cols_getValidNames($params = []): array { // If we don't need all esixt columns if ( - $params->colNames != '*' && - !empty($params->colNames) + $params->colNames != '*' + && !empty($params->colNames) ){ // If column names are set as single column name if (!is_array($params->colNames)){ @@ -369,7 +365,7 @@ protected function cols_getValidNames($params = []): array { /** * items_add - * @version 1.2.2 (2024-08-04) + * @version 1.2.3 (2024-12-03) * * @param $params {stdClass|arrayAssociative} — The parameters object. * @param $params->items {mixed} — An array of items. @@ -401,8 +397,8 @@ public function items_add($params): array { $result = []; foreach ( - $params->items as - $itemObject + $params->items + as $itemObject ){ $itemObject = (object) $itemObject; @@ -432,7 +428,7 @@ public function items_add($params): array { /** * items_update - * @version 1.6 (2024-08-06) + * @version 1.6.1 (2024-12-03) * * @param $params {stdClass|arrayAssociative} — The parameters object. * @param $params->data {object|array} — New item data. Existing item will be extended by this data. @@ -507,8 +503,8 @@ public function items_update($params): array { // Comma separated string or fail if ( - is_string($dbResult) && - !empty($dbResult) + is_string($dbResult) + && !empty($dbResult) ){ $dbResult = explode( ',', @@ -516,8 +512,8 @@ public function items_update($params): array { ); foreach ( - $dbResult as - $itemId + $dbResult + as $itemId ){ $result[] = \DDTools\Tools\Objects::extend([ 'objects' => [ @@ -668,8 +664,8 @@ public function items_get($params = []): array { * @desc Returns only used properties (columns) of $params->data. * * @param $params {stdClass|arrayAssociative} — The parameters object. - * @param $params->data {stdClass|arrayAssociative} — An array/object of item properties (e. g. you can use $_POST). Properties with only valid names will be returned, others will be deleted. - * @param $params->data->{$fieldName} {mixed} — Key is an item property name, value is a value. + * @param $params->data {stdClass|arrayAssociative} — An array/object of item properties (e. g. you can use $_POST). Properties with only valid names will be returned, others will be deleted. + * @param $params->data->{$fieldName} {mixed} — Key is an item property name, value is a value. * * @return {stdClass} */ @@ -696,7 +692,7 @@ protected function items_validateData($params = []) :\stdClass { /** * items_prepareWhere - * @version 1.4 (2024-08-06) + * @version 1.4.1 (2024-12-03) * * @desc Builds a where clause in the required internal format from externally passed parameters. * @@ -731,9 +727,9 @@ final protected function items_prepareWhere($params = []): string { $result = []; foreach ( - $params->where as - $propName => - $propValue + $params->where + as $propName + => $propValue ){ if (!is_array($propValue)){ $propValue = [$propValue]; @@ -752,11 +748,11 @@ final protected function items_prepareWhere($params = []): string { $this->cols_getOneColParam([ 'filter' => 'name == ' . $propName, 'paramName' => 'isComparedCaseSensitive', - ]) ? - 'BINARY ' : - '' - ) . - '"' . $this->escapeItemPropValue([ + ]) + ? 'BINARY ' + : '' + ) + . '"' . $this->escapeItemPropValue([ 'propName' => $propName, 'propValue' => $propValue_variantValue, ]) . '"' @@ -819,7 +815,7 @@ final protected function escapeItemPropValue($params): string { /** * buildSqlSetString - * @version 1.0.3 (2024-08-04) + * @version 1.0.4 (2024-12-03) * * @param $params {stdClass|arrayAssociative} — The parameters object. * @param $params->data {object|array} — Item data. @@ -833,9 +829,9 @@ final protected function buildSqlSetString($params): string { $result = []; foreach ( - $params->data as - $propName => - $propValue + $params->data + as $propName + => $propValue ){ $result[] = '`' . $propName . '` = "' . $this->escapeItemPropValue([ 'propName' => $propName, @@ -853,7 +849,7 @@ final protected function buildSqlSetString($params): string { /** * buildSqlLimitString - * @version 1.0.2 (2024-08-04) + * @version 1.0.3 (2024-12-03) * * @param [$params] {stdClass|arrayAssociative} — The parameters object. * @param [$params->limit=0] {integer|0} — Maximum number of items to return. `0` means all matching. @@ -875,20 +871,20 @@ final protected static function buildSqlLimitString($params = []): string { return // If limit is used - $params->limit > 0 ? - ( - 'LIMIT ' . + $params->limit > 0 + ? ( + 'LIMIT ' // Offset - ( - $params->offset > 0 ? - $params->offset . ', ' : - '' - ) . + . ( + $params->offset > 0 + ? $params->offset . ', ' + : '' + ) // Count - $params->limit - ) : + . $params->limit + ) // Without limit - '' + : '' ; } diff --git a/src/Storage/Storage.php b/src/Storage/Storage.php index fb44be9..5b81453 100644 --- a/src/Storage/Storage.php +++ b/src/Storage/Storage.php @@ -28,7 +28,7 @@ abstract public function items_add($params): array; /** * items_addOne - * @version 2.0.1 (2024-08-04) + * @version 2.0.2 (2024-12-03) * * @param $params {stdClass|arrayAssociative} — The parameters object. * @param $params->data {object|array} — An item. @@ -42,8 +42,8 @@ public function items_addOne($params): ?\stdClass { $result = $this->items_add([ 'items' => [ - $params->data - ] + $params->data, + ], ]); if (!empty($result)){ @@ -76,7 +76,7 @@ abstract public function items_update($params): array; /** * items_updateOne - * @version 1.2.1 (2024-08-04) + * @version 1.2.2 (2024-12-03) * * @param $params {stdClass|arrayAssociative} — The parameters object. * @param $params->data {object|array} — New item data. Existing item will be extended by this data. @@ -95,8 +95,8 @@ public function items_updateOne($params): ?\stdClass { 'isEnabledAddNotFound' => false, 'data' => [], ], - $params - ] + $params, + ], ]); $result = $this->items_update( @@ -106,7 +106,7 @@ public function items_updateOne($params): ?\stdClass { [ 'limit' => 1, ], - ] + ], ]) ); @@ -115,7 +115,7 @@ public function items_updateOne($params): ?\stdClass { }else{ if ($params->isEnabledAddNotFound){ $result = $this->items_addOne([ - 'data' => $params->data + 'data' => $params->data, ]); }else{ $result = null; @@ -143,7 +143,7 @@ abstract public function items_delete($params = []): void; /** * items_deleteOne - * @version 1.3 (2024-08-08) + * @version 1.3.1 (2024-12-03) * * @param [$params] {stdClass|arrayAssociative} — The parameters object. Default: —. * @param [$params->where=''] {stdClass|arrayAssociative|string|null} — SQL 'WHERE' clause. null or '' means that first found item will be deleted. @@ -161,7 +161,7 @@ public function items_deleteOne($params = []): void { [ 'limit' => 1, ], - ] + ], ]) ); } @@ -189,7 +189,7 @@ abstract public function items_get($params = []): array; /** * items_getOne - * @version 1.1.1 (2024-08-04) + * @version 1.1.2 (2024-12-03) * * @param [$params] {stdClass|arrayAssociative} — The parameters object. * @param [$params->where=''] {string|null} — SQL 'WHERE' clause. null or '' means that first found item will be returned. @@ -210,8 +210,8 @@ public function items_getOne($params = []){ 'propsToReturn' => '*', 'notFoundResult' => null, ], - $params - ] + $params, + ], ]); $result = $this->items_get([ diff --git a/src/Tools/Files.php b/src/Tools/Files.php index 430ba75..90f07ba 100644 --- a/src/Tools/Files.php +++ b/src/Tools/Files.php @@ -36,7 +36,7 @@ public static function createDir($params){ /** * copyDir - * @version 2.0.4 (2024-08-04) + * @version 2.0.5 (2024-12-03) * * @desc Copies a required folder with all contents recursively. * @@ -86,8 +86,8 @@ public static function copyDir($params){ ); foreach ( - $fileNames as - $fileName + $fileNames + as $fileName ){ // Если это папка, обработаем её if (is_dir($params->sourcePath . $fileName)){ @@ -108,7 +108,7 @@ public static function copyDir($params){ /** * removeDir - * @version 1.0.8 (2024-08-04) + * @version 1.0.9 (2024-12-03) * * @desc Removes a required folder with all contents recursively. * @@ -132,8 +132,8 @@ public static function removeDir($path){ ); foreach ( - $fileNames as - $fileName + $fileNames + as $fileName ){ // Если это папка, обработаем её if (is_dir($path . '/' . $fileName)){ @@ -148,7 +148,7 @@ public static function removeDir($path){ /** * modifyImage - * @version 2.6.5 (2024-08-04) + * @version 2.6.6 (2024-12-03) * * @see README.md * @@ -178,11 +178,11 @@ public static function modifyImage($params){ // Include PHP.libraries.phpThumb require_once( - 'Files' . - DIRECTORY_SEPARATOR . - 'phpThumb' . - DIRECTORY_SEPARATOR . - 'phpthumb.class.php' + 'Files' + . DIRECTORY_SEPARATOR + . 'phpThumb' + . DIRECTORY_SEPARATOR + . 'phpthumb.class.php' ); // Prepare source image addresses @@ -191,17 +191,17 @@ public static function modifyImage($params){ 'sourceFullPathName', 'outputFullPathName', 'watermarkImageFullPathName' - ] as - $paramName + ] + as $paramName ){ if ( // If the parameter is set \DDTools\Tools\Objects::isPropExists([ 'object' => $params, 'propName' => $paramName - ]) && + ]) // And set as relative path - substr( + && substr( $params->{$paramName}, 0, strlen(\ddTools::$modx->getConfig('base_path')) @@ -210,8 +210,8 @@ public static function modifyImage($params){ ){ // Convert relative path to absolute if needed $params->{$paramName} = - \ddTools::$modx->getConfig('base_path') . - $params->{$paramName} + \ddTools::$modx->getConfig('base_path') + . $params->{$paramName} ; } } @@ -236,8 +236,8 @@ public static function modifyImage($params){ // Если хотя бы один из размеров оригинала оказался нулевым (например, это не изображение) — на(\s?)бок if ( - $originalImg->width == 0 || - $originalImg->height == 0 + $originalImg->width == 0 + || $originalImg->height == 0 ){ return; } @@ -250,8 +250,8 @@ public static function modifyImage($params){ // Если по каким-то причинам высота не задана if ( - $params->height == '' || - $params->height == 0 + $params->height == '' + || $params->height == 0 ){ // Вычислим соответственно пропорциям $params->height = @@ -261,8 +261,8 @@ public static function modifyImage($params){ } // Если по каким-то причинам ширина не задана if ( - $params->width == '' || - $params->width == 0 + $params->width == '' + || $params->width == 0 ){ // Вычислим соответственно пропорциям $params->width = @@ -273,9 +273,9 @@ public static function modifyImage($params){ // Если превьюшка уже есть и имеет нужный размер, ничего делать не нужно if ( - $originalImg->width == $params->width && - $originalImg->height == $params->height && - file_exists($params->outputFullPathName) + $originalImg->width == $params->width + && $originalImg->height == $params->height + && file_exists($params->outputFullPathName) ){ return; } diff --git a/src/Tools/Objects.php b/src/Tools/Objects.php index 849a089..463b304 100644 --- a/src/Tools/Objects.php +++ b/src/Tools/Objects.php @@ -434,7 +434,7 @@ public static function extend($params){ /** * extend_getPropMetadata - * @version 1.1 (2024-08-19) + * @version 1.1.1 (2024-12-03) * * @param $params {stdClass|arrayAssociative} — The parameters object. * @param $params->resultObject {object|array} @@ -520,11 +520,11 @@ private static function extend_getPropMetadata($params): \stdClass { ) // NULL || is_null($params->additionalPropValue) - ) ? + ) // Additional is empty — don't use it - false: + ? false // Additional is not empty — use it - true + : true ; if ( From 73a02e2f6242561e071d82f06de948c3cb83d164 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Wed, 4 Dec 2024 02:23:50 +0400 Subject: [PATCH 2/5] * `\DDTools\Storage\DB\Storage`: Column names are quoted when creating or updating to avoid of errors when their names are equal to some reserved keywords, e. g. `repeat`. --- src/Storage/DB/Storage.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Storage/DB/Storage.php b/src/Storage/DB/Storage.php index 9180332..155e93f 100644 --- a/src/Storage/DB/Storage.php +++ b/src/Storage/DB/Storage.php @@ -149,7 +149,7 @@ private function construct_props($params): void { /** * construct_db - * @version 1.0.4 (2024-12-03) + * @version 1.0.5 (2024-12-03) * * @return {void} */ @@ -215,7 +215,7 @@ private function construct_db(): void { ? 'ADD ' : '' ) - . $columnData->name + . '`' . $columnData->name . '`' . ' ' . $columnData->attrs ; From fdd6f6d3e8490d87da28eff1cf4788e1200cb9ac Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Wed, 4 Dec 2024 02:34:34 +0400 Subject: [PATCH 3/5] * `\DDTools\Storage\DB\Storage::items_get`: Column names are quoted to avoid of errors when their names are equal to some reserved keywords, e. g. `repeat`. --- src/Storage/DB/Storage.php | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Storage/DB/Storage.php b/src/Storage/DB/Storage.php index 155e93f..38c5017 100644 --- a/src/Storage/DB/Storage.php +++ b/src/Storage/DB/Storage.php @@ -570,7 +570,7 @@ public function items_delete($params = []): void { /** * items_get - * @version 1.5 (2024-08-06) + * @version 1.5.1 (2024-12-04) * * @param [$params] {stdClass|arrayAssociative} — The parameters object. * @param [$params->where=''] {stdClass|arrayAssociative|string|null} — SQL 'WHERE' clause. null or '' means that all items will be returned. @@ -611,9 +611,13 @@ public function items_get($params = []): array { if (!empty($params->propsToReturn)){ $sqlResult = \ddTools::$modx->db->select( // Fields - implode( - ',', - $params->propsToReturn + ( + '`' + . implode( + '`,`', + $params->propsToReturn + ) + . '`' ), // Table $this->nameFull, From 67c4051555c28cf49fd1780718d0ea907893b97d Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Wed, 4 Dec 2024 03:04:51 +0400 Subject: [PATCH 4/5] * `\DDTools\Storage\DB\Storage::items_prepareWhere`: Column names are quoted in `where` clouse to avoid of errors when their names are equal to some reserved keywords, e. g. `repeat`. --- src/Storage/DB/Storage.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Storage/DB/Storage.php b/src/Storage/DB/Storage.php index 38c5017..c4e4694 100644 --- a/src/Storage/DB/Storage.php +++ b/src/Storage/DB/Storage.php @@ -696,7 +696,7 @@ protected function items_validateData($params = []) :\stdClass { /** * items_prepareWhere - * @version 1.4.1 (2024-12-03) + * @version 1.4.2 (2024-12-03) * * @desc Builds a where clause in the required internal format from externally passed parameters. * @@ -763,7 +763,7 @@ final protected function items_prepareWhere($params = []): string { ; } - $resultItem = $propName . ' '; + $resultItem = '`' . $propName . '` '; if (count($propValue) > 1){ $resultItem .= From 9005df164f7e9b0710c999ff07f2c6301cccb9a9 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Wed, 4 Dec 2024 03:20:39 +0400 Subject: [PATCH 5/5] Prerelease --- CHANGELOG.md | 7 ++++++- CHANGELOG_ru.md | 9 +++++++-- composer.json | 2 +- modx.ddtools.class.php | 2 +- 4 files changed, 15 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c514d0..6e82d4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ # (MODX)EvolutionCMS.libraries.ddTools changelog +## Version 0.64.1 (2024-12-04) + +* \* `\DDTools\Storage\DB\Storage`: Column names are quoted in all queries to avoid of errors when their names are equal to some reserved keywords, e. g. `repeat`. + + ## Version 0.64 (2024-09-06) * \+ `\DDTools\Tools\Objects::extend` → Parameters → `$params->extendableProperties`: The new optional parameter. Allows to use for extending not all properties from additional objects or arrays (see README → Examples). @@ -153,7 +158,7 @@ * \+ `$meta['success']`: Is not required anymore and by default will be equal to `true`. * \+ `$meta['code']`: Is not required anymore and by default will be equal to `200` or `400` depending on `$meta['success']`. * \+ `$meta`: - * \+ Can also be set as stdClass, stringJsonObject, stringHjsonObject, stringQueryFormatted. + * \+ Can also be set as stdClass, stringJsonObject, stringHjsonObject, stringQueryFormatted. * \+ Is not required anymore and by default will be equal to `['success' => true, 'code' => 200]`. * \+ `setMetaMessage`: If `$this->meta` is not set, it will be set with default values of `success` and `code`. diff --git a/CHANGELOG_ru.md b/CHANGELOG_ru.md index 389e435..6236fb3 100644 --- a/CHANGELOG_ru.md +++ b/CHANGELOG_ru.md @@ -1,7 +1,12 @@ # (MODX)EvolutionCMS.libraries.ddTools changelog -## Version 0.64 (2024-09-06) +## Версия 0.64.1 (2024-12-04) + +* \* `\DDTools\Storage\DB\Storage`: Имена колонок берутся в кавычки во всех запросах, чтобы избежать ошибок, когда они равны каким-нибудь зарезервированным ключевым словам, например `repeat`. + + +## Версия 0.64 (2024-09-06) * \+ `\DDTools\Tools\Objects::extend` → Параметры → `$params->extendableProperties`: Новый необязательный параметр. Позволяет использовать для расширения не все свойства из дополнительных объектов или массивов (см. README → Примеры). * \+ `\DDTools\Storage\Storage` → `items_update`, `items_updateOne`, `items_delete`, `items_deleteOne`, `items_get`, `items_getOne` → Параметры: @@ -153,7 +158,7 @@ * \+ `$meta['success']`: Больше не обязателен и по умолчанию будет равен `true`. * \+ `$meta['code']`: Больше не обязателен и по умолчанию будет равен `200` или `400` в зависимости от `$meta['success']`. * \+ `$meta`: - * \+ Также может быть задан как stdClass, stringJsonObject, stringHjsonObject, stringQueryFormatted. + * \+ Также может быть задан как stdClass, stringJsonObject, stringHjsonObject, stringQueryFormatted. * \+ Больше не обязателен и по умолчанию будет равен `['success' => true, 'code' => 200]`. * \+ `setMetaMessage`: Если `$this->meta` не задано, будет задано со значениями по умолчанию `success` и `code`. diff --git a/composer.json b/composer.json index 0396a73..1240db1 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "dd/evolutioncms-libraries-ddtools", "type": "modxevo-library-ddtools", - "version": "0.64.0", + "version": "0.64.1", "description": "A library with various tools facilitating your work.", "keywords": [ "modx", diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index c40fe05..bec1c5b 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -1,7 +1,7 @@