From 7630c7d9c744129f884e619c978a1834c686ed89 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Thu, 1 Aug 2024 19:25:07 +0400 Subject: [PATCH 01/12] + `\DDTools\Tools\Cache`: The new class. Allows you to cache some data (e. g. a snippet result) to a file in the `assets/cache/ddCache` folder (see README). --- README.md | 90 +++++++++++++++++++ require.php | 1 + src/Tools/Cache.php | 208 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 299 insertions(+) create mode 100644 src/Tools/Cache.php diff --git a/README.md b/README.md index 2891ab8..4e08f0a 100644 --- a/README.md +++ b/README.md @@ -557,6 +557,96 @@ For example, it can be helpful while using placeholders like `[+size.width+]`. * `array` +### `\DDTools\Tools\Cache` + +You can cache some data (e. g. a snippet result) to a file. + +* All cache files are stored in the `assets/cache/ddCache` folder. +* The name of each cache file is `[+prefix+][+resourceId+]-[+name+].php`. +* Each cache file can contain a string, array or stdClass. + + +#### `\DDTools\Tools\Cache::create($params)`, `\DDTools\Tools\Cache::get($params)` + +* `$params` + * Description: The object of parameters. + * Valid values: + * `stdClass` + * `arrayAssociative` + * **Required** + +* `$params->resourceId` + * Description: Resource ID related to cache (e. g. document ID). + * Valid values: `integer` + * **Required** + +* `$params->name` + * Description: Unique cache name. + * Valid values: `string` + * **Required** + +* `$params->prefix` + * Description: Cache file prefix. Useful if you want to cache some custom data that is not related to any documents. + * Valid values: `string` + * Default value: `'doc'` + + +#### `\DDTools\Tools\Cache::create($params)` + +Saves custom data to a cache file. + +* `$params->data` + * Description: Data to save. + * Valid values: + * `string` + * `array` + * `stdClass` + * **Required** + + +#### `\DDTools\Tools\Cache::get($params)` + +Retrieves data from a cache file. + + +##### Returns + +* `$result` + * Description: Cached data. + * Valid values: + * Type of returned data depends on type of saved data: + * `string` + * `array` + * `stdClass` + * `null` — means that the cache file does not exist + + +#### `\DDTools\Tools\Cache::clear($params)` + +Deletes one or more cache files. + +* `$params` + * Description: The object of parameters. + * Valid values: + * `stdClass` + * `arrayAssociative` + * Default value: — + +* `$params->resourceId` + * Description: Resource ID related to cache (e. g. document ID). + * Valid values: + * `integer` + * `null` — cache of all resources will be cleared independent of `$params->prefix` + * Default value: `null` + +* `$params->prefix` + * Description: Cache file prefix. Useful if you want to cache some custom data that is not related to any documents. + * Valid values: + * `string` + * `'*'` — means any prefix + * Default value: `'doc'` + + ### `\DDTools\ObjectCollection` Class representing a collection of some objects or arrays. diff --git a/require.php b/require.php index bfa46f3..2707c1c 100644 --- a/require.php +++ b/require.php @@ -5,6 +5,7 @@ require_once('src/ObjectTools/ObjectTools.php'); require_once('src/FilesTools/FilesTools.php'); +require_once('src/Tools/Cache.php'); require_once('src/ObjectCollection/ObjectCollection.php'); require_once('src/Response/Response.php'); require_once('src/Storage/Storage.php'); diff --git a/src/Tools/Cache.php b/src/Tools/Cache.php new file mode 100644 index 0000000..10568d7 --- /dev/null +++ b/src/Tools/Cache.php @@ -0,0 +1,208 @@ +'; + private static int $contentPrefixLen = 37; + + /** + * initStatic + * @version 2.0 (2024-08-01) + * + * @desc Static “constructor”. + * + * @return {void} + */ + private static function initStatic(): void { + if (is_null(static::$cacheDir)){ + static::$cacheDir = + //path to `assets` + dirname( + __DIR__, + 4 + ) + . '/cache/ddCache' + ; + + if (!is_dir(static::$cacheDir)){ + \DDTools\FilesTools::createDir([ + 'path' => static::$cacheDir, + ]); + } + } + } + + /** + * create + * @version 2.1.2 (2024-08-01) + * + * @param $params {stdClass|arrayAssociative} — The object of parameters. + * @param $params->resourceId {integer} — Resource ID related to cache (e. g. document ID). + * @param $params->name {string} — Unique cache name for the resource. + * @param $params->data {string|array|stdClass} — Data to save. + * @param [$params->prefix='doc'] {string} — Cache prefix. + * + * @return {void} + */ + public static function create($params): void { + static::initStatic(); + + $params = (object) $params; + + //str|obj|arr + $dataType = + is_object($params->data) + ? 'obj' + : ( + is_array($params->data) + ? 'arr' + //All other types are considered as string (because of this we don't use the gettype function) + : 'str' + ) + ; + + if ($dataType != 'str'){ + $params->data = \DDTools\ObjectTools::convertType([ + 'object' => $params->data, + 'type' => 'stringJsonAuto', + ]); + } + + //Save cache file + file_put_contents( + //Cache file path + static::buildCacheFilePath($params), + //Cache content + ( + static::$contentPrefix + . $dataType + . $params->data + ) + ); + } + + /** + * get + * @version 2.1.2 (2024-08-01) + * + * @param $params {stdClass|arrayAssociative} — The object of parameters. + * @param $params->resourceId {integer} — Document ID related to cache. + * @param $params->name {string} — Unique cache name for the document. + * @param [$params->prefix='doc'] {string} — Cache prefix. + * + * @return {null|string|array|stdClass} — `null` means that the cache file does not exist. + */ + public static function get($params){ + static::initStatic(); + + $result = null; + + $filePath = static::buildCacheFilePath($params); + + if (is_file($filePath)){ + //Cut PHP-code prefix + $result = substr( + file_get_contents($filePath), + static::$contentPrefixLen + ); + + //str|obj|arr + $dataType = substr( + $result, + 0, + 3 + ); + + //Cut dataType + $result = substr( + $result, + 3 + ); + + if ($dataType != 'str'){ + $result = \DDTools\ObjectTools::convertType([ + 'object' => $result, + 'type' => + $dataType == 'obj' + ? 'objectStdClass' + : 'objectArray' + , + ]); + } + } + + return $result; + } + + /** + * clear + * @version 2.1.2 (2024-08-01) + * + * @param Clear cache files for specified document or every documents. + * + * @param [$params] {stdClass|arrayAssociative} — The object of parameters. + * @param [$params->resourceId=null] {integer|null} — Resource ID related to cache (e. g. document ID). Default: null (cache of all resources will be cleared independent of `$params->prefix`). + * @param [$params->prefix='doc'] {string|'*'} — Cache prefix. + * + * @return {void} + */ + public static function clear($params = []): void { + static::initStatic(); + + $params = \DDTools\ObjectTools::extend([ + 'objects' => [ + (object) [ + 'resourceId' => null, + 'prefix' => 'doc', + ], + $params, + ], + ]); + + //Clear all cache + if (empty($params->resourceId)){ + \DDTools\FilesTools::removeDir(static::$cacheDir); + //Clear cache for specified documents + }else{ + $files = glob( + static::$cacheDir + . '/' . $params->prefix . $params->resourceId . '-*.php' + ); + + foreach ( + $files + as $filepath + ){ + unlink($filepath); + } + } + } + + /** + * buildCacheFilePath + * @version 2.1.1 (2024-08-01) + * + * @param $params {stdClass|arrayAssociative} — The object of parameters. + * @param $params->resourceId {integer} — Document ID related to cache. + * @param $params->name {string} — Unique cache name for the document. + * @param [$params->prefix='doc'] {string} — Cache prefix. + * + * @return {string} + */ + private static function buildCacheFilePath($params): string { + $params = \DDTools\ObjectTools::extend([ + 'objects' => [ + (object) [ + 'prefix' => 'doc', + ], + $params, + ], + ]); + + return + static::$cacheDir + . '/' . $params->prefix . $params->resourceId . '-' . $params->name . '.php' + ; + } +} \ No newline at end of file From fdd51962e09e0af5452cbac0890d55036b956aed Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Thu, 1 Aug 2024 19:31:11 +0400 Subject: [PATCH 02/12] =?UTF-8?q?*=20`\DDTools\Tools\Cache::create`,=20`\D?= =?UTF-8?q?DTools\Tools\Cache::get`=20=E2=86=92=20Parameters=20=E2=86=92?= =?UTF-8?q?=20`$params->suffix`:=20Has=20been=20renamed=20from=20`$params-?= =?UTF-8?q?>name`.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +++--- src/Tools/Cache.php | 14 +++++++------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 4e08f0a..9927041 100644 --- a/README.md +++ b/README.md @@ -562,7 +562,7 @@ For example, it can be helpful while using placeholders like `[+size.width+]`. You can cache some data (e. g. a snippet result) to a file. * All cache files are stored in the `assets/cache/ddCache` folder. -* The name of each cache file is `[+prefix+][+resourceId+]-[+name+].php`. +* The name of each cache file is `[+prefix+][+resourceId+]-[+suffix+].php`. * Each cache file can contain a string, array or stdClass. @@ -580,8 +580,8 @@ You can cache some data (e. g. a snippet result) to a file. * Valid values: `integer` * **Required** -* `$params->name` - * Description: Unique cache name. +* `$params->suffix` + * Description: Cache suffix. You can use several suffixes with the same `$params->resourceId` to cache some parts within a resource. * Valid values: `string` * **Required** diff --git a/src/Tools/Cache.php b/src/Tools/Cache.php index 10568d7..b803320 100644 --- a/src/Tools/Cache.php +++ b/src/Tools/Cache.php @@ -35,11 +35,11 @@ private static function initStatic(): void { /** * create - * @version 2.1.2 (2024-08-01) + * @version 3.0 (2024-08-01) * * @param $params {stdClass|arrayAssociative} — The object of parameters. * @param $params->resourceId {integer} — Resource ID related to cache (e. g. document ID). - * @param $params->name {string} — Unique cache name for the resource. + * @param $params->suffix {string} — Cache suffix. You can use several suffixes with the same `$params->resourceId` to cache some parts within a resource. * @param $params->data {string|array|stdClass} — Data to save. * @param [$params->prefix='doc'] {string} — Cache prefix. * @@ -84,11 +84,11 @@ public static function create($params): void { /** * get - * @version 2.1.2 (2024-08-01) + * @version 3.0 (2024-08-01) * * @param $params {stdClass|arrayAssociative} — The object of parameters. * @param $params->resourceId {integer} — Document ID related to cache. - * @param $params->name {string} — Unique cache name for the document. + * @param $params->suffix {string} — Cache suffix. You can use several suffixes with the same `$params->resourceId` to cache some parts within a resource. * @param [$params->prefix='doc'] {string} — Cache prefix. * * @return {null|string|array|stdClass} — `null` means that the cache file does not exist. @@ -181,11 +181,11 @@ public static function clear($params = []): void { /** * buildCacheFilePath - * @version 2.1.1 (2024-08-01) + * @version 3.0 (2024-08-01) * * @param $params {stdClass|arrayAssociative} — The object of parameters. * @param $params->resourceId {integer} — Document ID related to cache. - * @param $params->name {string} — Unique cache name for the document. + * @param $params->suffix {string} — Cache suffix. You can use several suffixes with the same `$params->resourceId` to cache some parts within a resource. * @param [$params->prefix='doc'] {string} — Cache prefix. * * @return {string} @@ -202,7 +202,7 @@ private static function buildCacheFilePath($params): string { return static::$cacheDir - . '/' . $params->prefix . $params->resourceId . '-' . $params->name . '.php' + . '/' . $params->prefix . $params->resourceId . '-' . $params->suffix . '.php' ; } } \ No newline at end of file From 593ec7f4907f6cfafc880099a60e3cefc7d59131 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Thu, 1 Aug 2024 20:15:27 +0400 Subject: [PATCH 03/12] =?UTF-8?q?+=20`\DDTools\Tools\Cache::clear`=20?= =?UTF-8?q?=E2=86=92=20Parameters=20=E2=86=92=20`$params->suffix`:=20The?= =?UTF-8?q?=20new=20optional=20parameter.=20Allows=20deleting=20cache=20fi?= =?UTF-8?q?les=20with=20a=20specified=20suffix.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 +++++++ src/Tools/Cache.php | 7 ++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9927041..2f9999d 100644 --- a/README.md +++ b/README.md @@ -645,6 +645,13 @@ Deletes one or more cache files. * `string` * `'*'` — means any prefix * Default value: `'doc'` + +* `$params->suffix` + * Description: Cache suffix. + * Valid values: + * `string` + * `'*'` — means any suffix + * Default value: `'*'` ### `\DDTools\ObjectCollection` diff --git a/src/Tools/Cache.php b/src/Tools/Cache.php index b803320..2e5e6d0 100644 --- a/src/Tools/Cache.php +++ b/src/Tools/Cache.php @@ -137,13 +137,14 @@ public static function get($params){ /** * clear - * @version 2.1.2 (2024-08-01) + * @version 2.2 (2024-08-01) * * @param Clear cache files for specified document or every documents. * * @param [$params] {stdClass|arrayAssociative} — The object of parameters. * @param [$params->resourceId=null] {integer|null} — Resource ID related to cache (e. g. document ID). Default: null (cache of all resources will be cleared independent of `$params->prefix`). * @param [$params->prefix='doc'] {string|'*'} — Cache prefix. + * @param [$params->suffix='*'] {string|'*'} — Cache suffix. * * @return {void} */ @@ -155,6 +156,7 @@ public static function clear($params = []): void { (object) [ 'resourceId' => null, 'prefix' => 'doc', + 'suffix' => '*', ], $params, ], @@ -166,8 +168,7 @@ public static function clear($params = []): void { //Clear cache for specified documents }else{ $files = glob( - static::$cacheDir - . '/' . $params->prefix . $params->resourceId . '-*.php' + static::buildCacheFilePath($params) ); foreach ( From 39cb4510ca820bfce629d52ea9d781c31a3ac033 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Thu, 1 Aug 2024 20:23:36 +0400 Subject: [PATCH 04/12] * `\DDTools\Tools\Cache`: File name format of cache files has been changed. --- README.md | 2 +- src/Tools/Cache.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2f9999d..7d810df 100644 --- a/README.md +++ b/README.md @@ -562,7 +562,7 @@ For example, it can be helpful while using placeholders like `[+size.width+]`. You can cache some data (e. g. a snippet result) to a file. * All cache files are stored in the `assets/cache/ddCache` folder. -* The name of each cache file is `[+prefix+][+resourceId+]-[+suffix+].php`. +* The name of each cache file is `[+prefix+]-[+resourceId+]-[+suffix+].php`. * Each cache file can contain a string, array or stdClass. diff --git a/src/Tools/Cache.php b/src/Tools/Cache.php index 2e5e6d0..ee1e339 100644 --- a/src/Tools/Cache.php +++ b/src/Tools/Cache.php @@ -182,7 +182,7 @@ public static function clear($params = []): void { /** * buildCacheFilePath - * @version 3.0 (2024-08-01) + * @version 4.0 (2024-08-01) * * @param $params {stdClass|arrayAssociative} — The object of parameters. * @param $params->resourceId {integer} — Document ID related to cache. @@ -203,7 +203,7 @@ private static function buildCacheFilePath($params): string { return static::$cacheDir - . '/' . $params->prefix . $params->resourceId . '-' . $params->suffix . '.php' + . '/' . $params->prefix . '-' . $params->resourceId . '-' . $params->suffix . '.php' ; } } \ No newline at end of file From 656fa63f5f524cbaa3f1f4cfb71fa4f2c321d212 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Fri, 2 Aug 2024 10:13:16 +0400 Subject: [PATCH 05/12] * Refactoring. --- require.php | 3 ++- src/{Base/BaseClass.php => backwardCompatibility.php} | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) rename src/{Base/BaseClass.php => backwardCompatibility.php} (82%) diff --git a/require.php b/require.php index 2707c1c..ade6341 100644 --- a/require.php +++ b/require.php @@ -1,7 +1,6 @@ \ No newline at end of file diff --git a/src/Base/BaseClass.php b/src/backwardCompatibility.php similarity index 82% rename from src/Base/BaseClass.php rename to src/backwardCompatibility.php index b41feb3..2ee37fd 100644 --- a/src/Base/BaseClass.php +++ b/src/backwardCompatibility.php @@ -1,7 +1,6 @@ Date: Fri, 2 Aug 2024 11:37:53 +0400 Subject: [PATCH 06/12] * `\DDTools\Tools\Objects`: The class has been renamed from `\DDTools\ObjectTools` (with backward compatibility). --- README.md | 72 +++++++++---------- modx.ddtools.class.php | 44 ++++++------ require.php | 2 +- src/Base/AncestorTrait.php | 4 +- src/Base/Base.php | 8 +-- src/FilesTools/FilesTools.php | 10 +-- src/ObjectCollection/ObjectCollection.php | 44 ++++++------ src/Response/Response.php | 20 +++--- src/Snippet/Snippet.php | 20 +++--- src/Storage/DB/Storage.php | 60 ++++++++-------- src/Storage/Storage.php | 14 ++-- src/Tools/Cache.php | 10 +-- .../ObjectTools.php => Tools/Objects.php} | 18 +++-- .../Objects}/hjson/HJSONException.php | 0 .../Objects}/hjson/HJSONParser.php | 0 .../Objects}/hjson/HJSONUtils.php | 0 src/backwardCompatibility.php | 4 +- 17 files changed, 169 insertions(+), 161 deletions(-) rename src/{ObjectTools/ObjectTools.php => Tools/Objects.php} (97%) rename src/{ObjectTools => Tools/Objects}/hjson/HJSONException.php (100%) rename src/{ObjectTools => Tools/Objects}/hjson/HJSONParser.php (100%) rename src/{ObjectTools => Tools/Objects}/hjson/HJSONUtils.php (100%) diff --git a/README.md b/README.md index 7d810df..b6a1ade 100644 --- a/README.md +++ b/README.md @@ -338,10 +338,10 @@ Modify your images: create thumbnails, crop, resize, fill background color or ad * Default value: — -### `\DDTools\ObjectTools` +### `\DDTools\Tools\Objects` -#### `\DDTools\ObjectTools::isPropExists($params)` +#### `\DDTools\Tools\Objects::isPropExists($params)` Checks if the object, class or array has a property / element. This is a “syntactic sugar” for checking an element in one way regardless of the “object” type. @@ -371,7 +371,7 @@ Second, the different order of parameters in the native PHP functions makes us c * **Required** -#### `\DDTools\ObjectTools::getPropValue($params)` +#### `\DDTools\Tools\Objects::getPropValue($params)` Get the value of an object property or an array element in any nesting level in one way regardless of the “object” type. @@ -416,7 +416,7 @@ Get the value of an object property or an array element in any nesting level in * `$params->notFoundResult` — if property not exists -#### `\DDTools\ObjectTools::convertType($params)` +#### `\DDTools\Tools\Objects::convertType($params)` Converts an object type. Arrays, [JSON](https://en.wikipedia.org/wiki/JSON) and [Query string](https://en.wikipedia.org/wiki/Query_string) objects are also supported. @@ -466,7 +466,7 @@ Arrays, [JSON](https://en.wikipedia.org/wiki/JSON) and [Query string](https://en * `stringJsonArray` -#### `\DDTools\ObjectTools::extend($params)` +#### `\DDTools\Tools\Objects::extend($params)` Merge the contents of two or more objects or arrays together into the first one. @@ -513,7 +513,7 @@ Merge the contents of two or more objects or arrays together into the first one. * Default value: `true` -#### `\DDTools\ObjectTools::unfold($params)` +#### `\DDTools\Tools\Objects::unfold($params)` Converts a multidimensional array/object into an one-dimensional one joining the keys with `$params->keySeparator`. For example, it can be helpful while using placeholders like `[+size.width+]`. @@ -1447,10 +1447,10 @@ Returns: ``` -### `\DDTools\ObjectTools` +### `\DDTools\Tools\Objects` -#### `\DDTools\ObjectTools::convertType($params)` +#### `\DDTools\Tools\Objects::convertType($params)` ##### Convert a JSON or Query encoded string to an array @@ -1461,7 +1461,7 @@ Just call this method and don't care about it. ```php //We can pass string in JSON format -\DDTools\ObjectTools::convertType([ +\DDTools\Tools\Objects::convertType([ 'object' => '{ "pagetitle": "Test title", "published": "0" @@ -1470,7 +1470,7 @@ Just call this method and don't care about it. ]); //Or Query string -\DDTools\ObjectTools::convertType([ +\DDTools\Tools\Objects::convertType([ 'object' => 'pagetitle=Test title&published=0', 'type' => 'objectArray' ]); @@ -1489,7 +1489,7 @@ Both calls return: ##### Convert a Query encoded string to a JSON object string ```php -\DDTools\ObjectTools::convertType([ +\DDTools\Tools\Objects::convertType([ 'object' => 'firstName=Hans&lastName=Zimmer', 'type' => 'stringJsonAuto' ]); @@ -1508,7 +1508,7 @@ Returns: ##### Convert a JSON object to a JSON array ```php -\DDTools\ObjectTools::convertType([ +\DDTools\Tools\Objects::convertType([ 'object' => '{ "firstName": "Ramin", "lastName": "Djawadi" @@ -1530,7 +1530,7 @@ Returns: ##### Convert a HJSON encoded string to an object ```php -\DDTools\ObjectTools::convertType([ +\DDTools\Tools\Objects::convertType([ 'object' => "{ //This is HJSON, not JSON, so we can use comments insides keys: and values can be specified without quotes, @@ -1560,7 +1560,7 @@ A simple syntax and easy to read.', ##### Convert an associative array to a string of HTML attributes ```php -\DDTools\ObjectTools::convertType([ +\DDTools\Tools\Objects::convertType([ 'object' => [ 'data-name' => 'KINO', //Will be converted to 1 @@ -1587,13 +1587,13 @@ data-name='KINO' data-is-active='1' data-members='["Viktor Tsoi","Yuri Kasparyan ``` -#### `\DDTools\ObjectTools::extend($params)` +#### `\DDTools\Tools\Objects::extend($params)` ##### Merge two objects, modifying the first ```php -var_export(\DDTools\ObjectTools::extend([ +var_export(\DDTools\Tools\Objects::extend([ 'objects' => [ (object) [ 'cat' => 'mew', @@ -1631,7 +1631,7 @@ stdClass::__set_state(array( ##### Also you can extend arrays ```php -var_export(\DDTools\ObjectTools::extend([ +var_export(\DDTools\Tools\Objects::extend([ 'objects' => [ [ 'cat' => 'mew', @@ -1669,7 +1669,7 @@ array( ##### Moreover, objects can extend arrays and vice versa ```php -var_export(\DDTools\ObjectTools::extend([ +var_export(\DDTools\Tools\Objects::extend([ 'objects' => [ [ 'name' => 'jokes', @@ -1707,7 +1707,7 @@ array( By default, empty field values (e. g. `''`) are treated as other values and will replace non-empty ones. ```php -var_export(\DDTools\ObjectTools::extend([ +var_export(\DDTools\Tools\Objects::extend([ 'objects' => [ (object) [ 'firstName' => 'John', @@ -1737,7 +1737,7 @@ Empty `lastName` from the second object replaced non-empty `lastName` from the f If you want to ignore empty values, just use `$params->overwriteWithEmpty` == `false`: ```php -var_export(\DDTools\ObjectTools::extend([ +var_export(\DDTools\Tools\Objects::extend([ 'objects' => [ (object) [ 'firstName' => 'John', @@ -1764,13 +1764,13 @@ stdClass::__set_state(array( ``` -#### `\DDTools\ObjectTools::unfold($params)` +#### `\DDTools\Tools\Objects::unfold($params)` ##### Unfold an object ```php -var_export(\DDTools\ObjectTools::unfold([ +var_export(\DDTools\Tools\Objects::unfold([ 'object' => (object) [ 'name' => 'Elon Musk', 'address' => (object) [ @@ -1799,7 +1799,7 @@ stdClass::__set_state(array ( ##### Unfold an array ```php -var_export(\DDTools\ObjectTools::unfold([ +var_export(\DDTools\Tools\Objects::unfold([ 'object' => [ 'a' => 'a val', 'b' => [ @@ -1830,7 +1830,7 @@ array ( ##### Use custom key separator ```php -var_export(\DDTools\ObjectTools::unfold([ +var_export(\DDTools\Tools\Objects::unfold([ 'object' => [ 'name' => 'Elon Musk', 'parents' => [ @@ -1877,7 +1877,7 @@ $data = [ ```php var_export( - \DDTools\ObjectTools::unfold([ + \DDTools\Tools\Objects::unfold([ 'object' => $data, ]) ); @@ -1902,7 +1902,7 @@ array ( ```php var_export( - \DDTools\ObjectTools::unfold([ + \DDTools\Tools\Objects::unfold([ 'object' => $data, 'isCrossTypeEnabled' => true, ]) @@ -1923,14 +1923,14 @@ array ( ``` -#### `\DDTools\ObjectTools::isPropExists($params)` +#### `\DDTools\Tools\Objects::isPropExists($params)` Checks if the object, class or array has a property / element using the same syntax. You can pass an object: ```php -var_export(\DDTools\ObjectTools::isPropExists([ +var_export(\DDTools\Tools\Objects::isPropExists([ 'object' => (object) [ 'firstName' => 'John', 'lastName' => 'Lennon' @@ -1942,7 +1942,7 @@ var_export(\DDTools\ObjectTools::isPropExists([ Or an array: ```php -var_export(\DDTools\ObjectTools::isPropExists([ +var_export(\DDTools\Tools\Objects::isPropExists([ 'object' => [ 'firstName' => 'Paul', 'lastName' => 'McCartney' @@ -1954,7 +1954,7 @@ var_export(\DDTools\ObjectTools::isPropExists([ Both calls return `true`. -#### `\DDTools\ObjectTools::getPropValue($params)` +#### `\DDTools\Tools\Objects::getPropValue($params)` ##### Get the value of an object property or an array element using the same syntax @@ -1962,7 +1962,7 @@ Both calls return `true`. You can pass an object: ```php -var_export(\DDTools\ObjectTools::getPropValue([ +var_export(\DDTools\Tools\Objects::getPropValue([ 'object' => (object) [ 'name' => 'Floyd', 'weight' => 7 @@ -1974,7 +1974,7 @@ var_export(\DDTools\ObjectTools::getPropValue([ Or an array: ```php -var_export(\DDTools\ObjectTools::getPropValue([ +var_export(\DDTools\Tools\Objects::getPropValue([ 'object' => [ 'name' => 'Floyd', 'weight' => 7 @@ -2027,7 +2027,7 @@ $sourceObject = (object) [ There's nothing special, just look at this example for the full picture. ```php -var_export(\DDTools\ObjectTools::getPropValue([ +var_export(\DDTools\Tools\Objects::getPropValue([ 'object' => $sourceObject, 'propName' => 'PinkFloyd' ])); @@ -2066,7 +2066,7 @@ array ( Let's make it a little more interesting: let's get the 4th element of the second-level indexed array. ```php -var_export(\DDTools\ObjectTools::getPropValue([ +var_export(\DDTools\Tools\Objects::getPropValue([ 'object' => $sourceObject, 'propName' => 'PinkFloyd.4' ])); @@ -2090,7 +2090,7 @@ No matter what type of element is used in any nesting level, the method will wor So let's get Roger's name. As you remember, he is stdClass as opposed to the other members who are associative arrays. ```php -var_export(\DDTools\ObjectTools::getPropValue([ +var_export(\DDTools\Tools\Objects::getPropValue([ 'object' => $sourceObject, 'propName' => 'PinkFloyd.2.name' ])); @@ -2106,7 +2106,7 @@ Returns: ###### Of course, it works fine with single-level objects that contain `'.'` in their property names ```php -var_export(\DDTools\ObjectTools::getPropValue([ +var_export(\DDTools\Tools\Objects::getPropValue([ 'object' => [ '1973.03.01' => 'The Dark Side of the Moon', '1975.09.12' => 'Wish You Were Here' diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index 78168aa..9ce5d92 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -304,7 +304,7 @@ public static function explodeAssoc( /** * sort2dArray - * @version 1.3 (2022-12-23) + * @version 1.3.1 (2024-08-02) * * @desc Sorts 2-dimensional array by multiple columns (like in SQL) using Hoare's method, also referred to as quicksort. The sorting is stable. * @@ -323,7 +323,7 @@ public static function sort2dArray( $i = 0 ){ //В качестве эталона получаем сортируемое значение (по первому условию сортировки) первого элемента - $currentItem_comparisonValue = \DDTools\ObjectTools::getPropValue([ + $currentItem_comparisonValue = \DDTools\Tools\Objects::getPropValue([ 'object' => array_values($array)[0], 'propName' => $sortBy[$i] ]); @@ -347,7 +347,7 @@ public static function sort2dArray( $arrayItemKey => $arrayItem ){ - $arrayItem_comparisonValue = \DDTools\ObjectTools::getPropValue([ + $arrayItem_comparisonValue = \DDTools\Tools\Objects::getPropValue([ 'object' => $arrayItem, 'propName' => $sortBy[$i] ]); @@ -496,7 +496,7 @@ public static function parseFileNameVersion($file){ /** * convertUrlToAbsolute - * @version 1.0 (2022-09-05) + * @version 1.0.1 (2024-08-02) * * @desc Converts relative URLs to absolute. * @@ -509,7 +509,7 @@ public static function parseFileNameVersion($file){ */ public static function convertUrlToAbsolute($params){ //# Prepare params - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -956,7 +956,7 @@ public static function parseText($params = []){ /** * parseText_parepareParams - * @version 1.0.1 (2024-06-17) + * @version 1.0.2 (2024-08-02) * * @param $params {stdClass|arrayAssociative} — The object of parameters. See $this->parseText. * @@ -986,7 +986,7 @@ private static function parseText_parepareParams($params = []): \stdClass { 'returnCorrectedOnly' => false, ]); - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -1006,7 +1006,7 @@ private static function parseText_parepareParams($params = []): \stdClass { /** * parseText_prepareData - * @version 1.0 (2024-06-06) + * @version 1.0.1 (2024-08-02) * * @param $params {stdClass|arrayAssociative} — The object of parameters. See $this->parseText. * @param $params->data {stdClass|array|string} @@ -1023,7 +1023,7 @@ private static function parseText_prepareData($params = []): \stdClass { !is_object($params->data) && !is_array($params->data) ){ - $params->data = \DDTools\ObjectTools::convertType([ + $params->data = \DDTools\Tools\Objects::convertType([ 'object' => $params->data, 'type' => 'objectArray' ]); @@ -1039,7 +1039,7 @@ private static function parseText_prepareData($params = []): \stdClass { 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\ObjectTools::unfold([ + $unfoldedValue = \DDTools\Tools\Objects::unfold([ 'object' => [ $key => $value ], @@ -1055,7 +1055,7 @@ private static function parseText_prepareData($params = []): \stdClass { } //Also add object value as JSON - $value = \DDTools\ObjectTools::convertType([ + $value = \DDTools\Tools\Objects::convertType([ 'object' => $value, 'type' => 'stringJsonAuto' ]); @@ -1329,7 +1329,7 @@ private static function createDocument_prepareAlias($sourceString){ /** * createDocument - * @version 1.5 (2020-06-21) + * @version 1.5.1 (2024-08-02) * * @desc Create a new document. * @@ -1345,7 +1345,7 @@ public static function createDocument( $docGroups = false ){ //Defaults - $docData = \DDTools\ObjectTools::extend([ + $docData = \DDTools\Tools\Objects::extend([ 'objects' => [ (object) [ 'pagetitle' => 'New resource', @@ -1507,7 +1507,7 @@ public static function createDocument( /** * updateDocument - * @version 1.5 (2021-03-15) + * @version 1.5.1 (2024-08-02) * * @desc Update document(s). Cache of the updated docs and their parents will be cleared. * @@ -1532,7 +1532,7 @@ public static function updateDocument( return false; } - $docData = \DDTools\ObjectTools::extend([ + $docData = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -2730,7 +2730,7 @@ function_exists('idn_to_utf8') ? /** * verifyRenamedParams - * @version 1.7.1 (2021-03-09) + * @version 1.7.2 (2024-08-02) * * @see README.md */ @@ -2747,7 +2747,7 @@ public static function verifyRenamedParams($params){ ]); } - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -2991,7 +2991,7 @@ public static function getResponse(){ /** * encodedStringToArray - * @version 1.2 (2020-06-02) + * @version 1.2.1 (2024-08-02) * * @desc Converts encoded strings to arrays. * Supported formats: @@ -3003,7 +3003,7 @@ public static function getResponse(){ * @return {array} */ public static function encodedStringToArray($inputString){ - $result = \DDTools\ObjectTools::convertType([ + $result = \DDTools\Tools\Objects::convertType([ 'object' => $inputString, 'type' => 'objectArray' ]); @@ -3027,15 +3027,15 @@ public static function encodedStringToArray($inputString){ /** * unfoldArray - * @version 1.1 (2021-11-16) + * @version 1.1.1 (2024-08-02) * - * @see README.md (\DDTools\ObjectTools::unfold) + * @see README.md (\DDTools\Tools\Objects::unfold) */ public static function unfoldArray( $array, $keyPrefix = '' ){ - return \DDTools\ObjectTools::unfold([ + return \DDTools\Tools\Objects::unfold([ 'object' => $array, 'keyPrefix' => $keyPrefix ]); diff --git a/require.php b/require.php index ade6341..cb3d966 100644 --- a/require.php +++ b/require.php @@ -2,7 +2,7 @@ require_once('src/Base/Base.php'); require_once('src/Base/AncestorTrait.php'); -require_once('src/ObjectTools/ObjectTools.php'); +require_once('src/Tools/Objects.php'); require_once('src/FilesTools/FilesTools.php'); require_once('src/Tools/Cache.php'); require_once('src/ObjectCollection/ObjectCollection.php'); diff --git a/src/Base/AncestorTrait.php b/src/Base/AncestorTrait.php index fb4e31d..880bf56 100644 --- a/src/Base/AncestorTrait.php +++ b/src/Base/AncestorTrait.php @@ -84,7 +84,7 @@ final public static function getChildClassName($params): string { /** * createChildInstance - * @version 1.2.2 (2024-02-06) + * @version 1.2.3 (2024-08-02) * * @see README.md */ @@ -94,7 +94,7 @@ final public static function createChildInstance($params){ $objectClass = static::getChildClassName($params); return new $objectClass( - \DDTools\ObjectTools::isPropExists([ + \DDTools\Tools\Objects::isPropExists([ 'object' => $params, 'propName' => 'params', ]) diff --git a/src/Base/Base.php b/src/Base/Base.php index df5b35b..f98d4b7 100644 --- a/src/Base/Base.php +++ b/src/Base/Base.php @@ -85,7 +85,7 @@ public static function getClassName(): \stdClass { /** * setExistingProps - * @version 1.4 (2022-01-08) + * @version 1.4.1 (2024-08-02) * * @see README.md * @@ -93,7 +93,7 @@ public static function getClassName(): \stdClass { */ public function setExistingProps($props){ if (is_string($props)){ - $props = \DDTools\ObjectTools::convertType([ + $props = \DDTools\Tools\Objects::convertType([ 'object' => $props, 'type' => 'objectStdClass' ]); @@ -224,14 +224,14 @@ public function toArray(){ /** * toJSON - * @version 1.1 (2022-12-26) + * @version 1.1.1 (2024-08-02) * * @see README.md * * @return {stringJsonObject} */ public function toJSON(){ - return \DDTools\ObjectTools::convertType([ + return \DDTools\Tools\Objects::convertType([ 'object' => $this->toArray(), 'type' => 'stringJsonAuto' ]); diff --git a/src/FilesTools/FilesTools.php b/src/FilesTools/FilesTools.php index 61a4dc5..13bd206 100644 --- a/src/FilesTools/FilesTools.php +++ b/src/FilesTools/FilesTools.php @@ -148,7 +148,7 @@ public static function removeDir($path){ /** * modifyImage - * @version 2.6.2 (2021-03-09) + * @version 2.6.3 (2024-08-02) * * @see README.md * @@ -156,7 +156,7 @@ public static function removeDir($path){ */ public static function modifyImage($params){ //Defaults - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ (object) [ 'transformMode' => 'resize', @@ -168,7 +168,7 @@ public static function modifyImage($params){ ] ]); - if (!\DDTools\ObjectTools::isPropExists([ + if (!\DDTools\Tools\Objects::isPropExists([ 'object' => $params, 'propName' => 'outputFullPathName' ])){ @@ -194,7 +194,7 @@ public static function modifyImage($params){ ){ if ( //If the parameter is set - \DDTools\ObjectTools::isPropExists([ + \DDTools\Tools\Objects::isPropExists([ 'object' => $params, 'propName' => $paramName ]) && @@ -374,7 +374,7 @@ public static function modifyImage($params){ //If need to overlay image with watermark - if (\DDTools\ObjectTools::isPropExists([ + if (\DDTools\Tools\Objects::isPropExists([ 'object' => $params, 'propName' => 'watermarkImageFullPathName' ])){ diff --git a/src/ObjectCollection/ObjectCollection.php b/src/ObjectCollection/ObjectCollection.php index 24c437a..342b003 100644 --- a/src/ObjectCollection/ObjectCollection.php +++ b/src/ObjectCollection/ObjectCollection.php @@ -36,13 +36,13 @@ public function setItems($params = []){ /** * addItems - * @version 1.2 (2021-12-02) + * @version 1.2.1 (2024-08-02) * * @see README.md */ public function addItems($params = []){ //# Prepare params - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -58,7 +58,7 @@ public function addItems($params = []){ if (!is_null($params->items)){ //Items must be an array if (!is_array($params->items)){ - $params->items = \DDTools\ObjectTools::convertType([ + $params->items = \DDTools\Tools\Objects::convertType([ 'object' => $params->items, 'type' => 'objectArray' ]); @@ -74,7 +74,7 @@ public function addItems($params = []){ $itemIndex => $itemObject ){ - $params->items[$itemIndex] = \DDTools\ObjectTools::convertType([ + $params->items[$itemIndex] = \DDTools\Tools\Objects::convertType([ 'object' => $itemObject, 'type' => $params->itemType ]); @@ -90,13 +90,13 @@ public function addItems($params = []){ /** * convertItemsType - * @version 1.0.3 (2023-12-25) + * @version 1.0.4 (2024-08-02) * * @see README.md */ public function convertItemsType($params = []){ //# Prepare params - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -125,7 +125,7 @@ public function convertItemsType($params = []){ ){ $this->setOneItemData([ 'index' => $itemIndex, - 'data' => \DDTools\ObjectTools::convertType([ + 'data' => \DDTools\Tools\Objects::convertType([ 'object' => $this->getOneItemData([ 'itemObject' => $itemObject ]), @@ -138,13 +138,13 @@ public function convertItemsType($params = []){ /** * updateItems - * @version 1.0.3 (2023-12-25) + * @version 1.0.4 (2024-08-02) * * @see README.md */ public function updateItems($params = []){ //# Prepare params - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -176,7 +176,7 @@ public function updateItems($params = []){ ){ $this->setOneItemData([ 'index' => $itemIndex, - 'data' => \DDTools\ObjectTools::extend([ + 'data' => \DDTools\Tools\Objects::extend([ 'objects' => [ $this->getOneItemData([ 'itemObject' => $itemObject @@ -200,13 +200,13 @@ public function updateItems($params = []){ /** * getItems - * @version 2.0.2 (2022-12-28) + * @version 2.0.3 (2024-08-02) * * @see README.md */ public function getItems($params = []){ //# Prepare params - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -244,7 +244,7 @@ public function getItems($params = []){ //Save only field value instead of object if needed if (!is_null($params->propAsResultValue)){ - $resultItemObject = \DDTools\ObjectTools::getPropValue([ + $resultItemObject = \DDTools\Tools\Objects::getPropValue([ 'object' => $itemData, 'propName' => $params->propAsResultValue ]); @@ -255,7 +255,7 @@ public function getItems($params = []){ //Save item if (!is_null($params->propAsResultKey)){ $result[ - \DDTools\ObjectTools::getPropValue([ + \DDTools\Tools\Objects::getPropValue([ 'object' => $itemData, 'propName' => $params->propAsResultKey ]) @@ -280,13 +280,13 @@ public function getItems($params = []){ /** * getOneItem - * @version 1.0.1 (2021-12-02) + * @version 1.0.2 (2024-08-02) * * @see README.md */ public function getOneItem($params = []){ //# Prepare params - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -315,13 +315,13 @@ public function getOneItem($params = []){ /** * deleteItems - * @version 1.0.1 (2022-12-28) + * @version 1.0.2 (2024-08-02) * * @see README.md */ public function deleteItems($params = []){ //# Prepare params - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -412,7 +412,7 @@ protected function getOneItemData($params){ /** * isItemMatchFilter - * @version 2.0.1 (2022-12-28) + * @version 2.0.2 (2024-08-02) * * @param $params {stdClass|arrayAssociative} — Parameters, the pass-by-name style is used. @required * @param $params->itemObject {array|object} — An item to test. @required @@ -442,7 +442,7 @@ private function isItemMatchFilter($params){ ){ //If the item has no the property if ( - !\DDTools\ObjectTools::isPropExists([ + !\DDTools\Tools\Objects::isPropExists([ 'object' => $itemData, 'propName' => $andCondition->propName ]) @@ -454,7 +454,7 @@ private function isItemMatchFilter($params){ //== }elseif ($andCondition->operator == '=='){ $result = - \DDTools\ObjectTools::getPropValue([ + \DDTools\Tools\Objects::getPropValue([ 'object' => $itemData, 'propName' => $andCondition->propName ]) == @@ -463,7 +463,7 @@ private function isItemMatchFilter($params){ //!= }else{ $result = - \DDTools\ObjectTools::getPropValue([ + \DDTools\Tools\Objects::getPropValue([ 'object' => $itemData, 'propName' => $andCondition->propName ]) != diff --git a/src/Response/Response.php b/src/Response/Response.php index d0ef43d..da210ab 100644 --- a/src/Response/Response.php +++ b/src/Response/Response.php @@ -143,7 +143,7 @@ public function validateMetaMessage($message){ /** * setMeta - * @version 1.4.1 (2023-03-29) + * @version 1.4.2 (2024-08-02) * * @desc Setter for $this->meta. * @@ -154,7 +154,7 @@ public function validateMetaMessage($message){ public function setMeta($meta = []){ //If $meta is set as stdClass, stringJsonObject, stringHjsonObject or stringQueryFormatted if (!is_array($meta)){ - $meta = \DDTools\ObjectTools::convertType([ + $meta = \DDTools\Tools\Objects::convertType([ 'object' => $meta, 'type' => 'objectArray' ]); @@ -162,7 +162,7 @@ public function setMeta($meta = []){ //If success is not set if ( - !\DDTools\ObjectTools::isPropExists([ + !\DDTools\Tools\Objects::isPropExists([ 'object' => $meta, 'propName' => 'success' ]) @@ -173,7 +173,7 @@ public function setMeta($meta = []){ //If code is not set if ( - !\DDTools\ObjectTools::isPropExists([ + !\DDTools\Tools\Objects::isPropExists([ 'object' => $meta, 'propName' => 'code' ]) @@ -238,7 +238,7 @@ public function setData($data){ /** * setMetaData - * @version 1.0.1 (2023-03-29) + * @version 1.0.2 (2024-08-02) * * @desc Setter for $this->meta and $this->data. * @@ -249,14 +249,14 @@ public function setData($data){ public function setMetaData($params){ //If $meta is set as stdClass, stringJsonObject, stringHjsonObject or stringQueryFormatted if (!is_array($params)){ - $params = \DDTools\ObjectTools::convertType([ + $params = \DDTools\Tools\Objects::convertType([ 'object' => $params, 'type' => 'objectArray' ]); } if ( - \DDTools\ObjectTools::isPropExists([ + \DDTools\Tools\Objects::isPropExists([ 'object' => $params, 'propName' => 'meta' ]) @@ -265,7 +265,7 @@ public function setMetaData($params){ } if ( - \DDTools\ObjectTools::isPropExists([ + \DDTools\Tools\Objects::isPropExists([ 'object' => $params, 'propName' => 'data' ]) @@ -339,14 +339,14 @@ public function toArray(){ /** * toJSON - * @version 1.0.1 (2021-03-10) + * @version 1.0.2 (2024-08-02) * * @desc Converts this object to JSON string. * * @return string */ public function toJSON(){ - return \DDTools\ObjectTools::convertType([ + return \DDTools\Tools\Objects::convertType([ 'object' => $this->toArray(), 'type' => 'stringJsonObject' ]); diff --git a/src/Snippet/Snippet.php b/src/Snippet/Snippet.php index a1a1936..5af9654 100644 --- a/src/Snippet/Snippet.php +++ b/src/Snippet/Snippet.php @@ -87,7 +87,7 @@ public function __construct($params = []){ /** * prepareParams - * @version 1.1.1 (2021-03-29) + * @version 1.1.2 (2024-08-02) * * @param $params {stdClass|arrayAssociative|stringJsonObject|stringQueryFormatted} * @@ -96,7 +96,7 @@ public function __construct($params = []){ protected function prepareParams($params = []){ $this->params = (object) $this->params; - $params = \DDTools\ObjectTools::convertType([ + $params = \DDTools\Tools\Objects::convertType([ 'object' => $params, 'type' => 'objectStdClass' ]); @@ -120,7 +120,7 @@ protected function prepareParams($params = []){ //Convert defaults if ( - \DDTools\ObjectTools::isPropExists([ + \DDTools\Tools\Objects::isPropExists([ 'object' => $this->params, 'propName' => $paramName ]) @@ -130,7 +130,7 @@ protected function prepareParams($params = []){ }elseif ($paramType == 'boolean'){ $this->params->{$paramName} = boolval($this->params->{$paramName}); }else{ - $this->params->{$paramName} = \DDTools\ObjectTools::convertType([ + $this->params->{$paramName} = \DDTools\Tools\Objects::convertType([ 'object' => $this->params->{$paramName}, 'type' => $paramType ]); @@ -139,7 +139,7 @@ protected function prepareParams($params = []){ //Convert given if ( - \DDTools\ObjectTools::isPropExists([ + \DDTools\Tools\Objects::isPropExists([ 'object' => $params, 'propName' => $paramName ]) @@ -149,7 +149,7 @@ protected function prepareParams($params = []){ }elseif ($paramType == 'boolean'){ $params->{$paramName} = boolval($params->{$paramName}); }else{ - $params->{$paramName} = \DDTools\ObjectTools::convertType([ + $params->{$paramName} = \DDTools\Tools\Objects::convertType([ 'object' => $params->{$paramName}, 'type' => $paramType ]); @@ -158,7 +158,7 @@ protected function prepareParams($params = []){ } } - $this->params = \DDTools\ObjectTools::extend([ + $this->params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults $this->params, @@ -172,7 +172,7 @@ public abstract function run(); /** * runSnippet - * @version 1.0 (2021-02-18) + * @version 1.0.1 (2024-08-02) * * @param $params {stdClass|arrayAssociative|stringJsonObject|stringQueryFormatted} * @param $params->name {string} @@ -184,14 +184,14 @@ public abstract function run(); public static function runSnippet($params){ $result = ''; - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ 'name' => '', 'params' => [] ], - \DDTools\ObjectTools::convertType([ + \DDTools\Tools\Objects::convertType([ 'object' => $params, 'type' => 'objectStdClass' ]) diff --git a/src/Storage/DB/Storage.php b/src/Storage/DB/Storage.php index b1c8ede..53ca45d 100644 --- a/src/Storage/DB/Storage.php +++ b/src/Storage/DB/Storage.php @@ -45,7 +45,7 @@ class Storage extends \DDTools\Storage\Storage { /** * initStatic - * @version 1.1.1 (2023-12-29) + * @version 1.1.2 (2024-08-02) * * @desc Static “constructor”. * @@ -55,7 +55,7 @@ private static function initStatic(): void { //If is not inited before (type of static::$columnsDefaultParams is just used as flag) if (!is_object(static::$columnsDefaultParams)){ //Merge columnsDefaultParams from parent and child static props - static::$columnsDefaultParams = \DDTools\ObjectTools::extend([ + static::$columnsDefaultParams = \DDTools\Tools\Objects::extend([ 'objects' => [ //Parent (\DDTools\DB\Table::$columnsDefaultParams) (object) self::$columnsDefaultParams, @@ -68,7 +68,7 @@ private static function initStatic(): void { /** * __construct - * @version 3.0 (2024-01-04) + * @version 3.0.1 (2024-08-02) * * @param $params {arrayAssociative|stdClass} — Parameters, the pass-by-name style is used. Default: —. * @param $params->nameAlias {string} — Short table name (e. g. 'site_content'). You can define it in child classes or pass to the constructor directly. Default: ''. @@ -82,7 +82,7 @@ private static function initStatic(): void { * @param $params->columns[$i]->isTagsAllowed {boolean} — Are HTML and MODX tags allowed? Default: static::$columnsDefaultParams->isTagsAllowed. */ public function __construct($params = []){ - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ (object) [ 'columns' => [] @@ -101,7 +101,7 @@ public function __construct($params = []){ /** * construct_props - * @version 2.0 (2024-01-04) + * @version 2.0.1 (2024-08-02) * * @param $params {stdClass} — Parameters, see $this->__construct. @required * @@ -135,7 +135,7 @@ private function construct_props($params): void { $this->columns->addItems([ 'items' => [ - \DDTools\ObjectTools::extend([ + \DDTools\Tools\Objects::extend([ 'objects' => [ //Column data (object) [ @@ -153,7 +153,7 @@ private function construct_props($params): void { /** * construct_db - * @version 1.0.1 (2024-01-04) + * @version 1.0.2 (2024-08-02) * * @return {void} */ @@ -197,7 +197,7 @@ private function construct_db(): void { $propDefaultValue ){ if ( - !\DDTools\ObjectTools::isPropExists([ + !\DDTools\Tools\Objects::isPropExists([ 'object' => $columnData, 'propName' => $propName ]) @@ -260,7 +260,7 @@ private function construct_db(): void { /** * cols_getColsParams - * @version 3.0 (2023-12-28) + * @version 3.0.1 (2024-08-02) * * @param $params {arrayAssociative|stdClass} — Parameters, the pass-by-name style is used. Default: —. * @param $params->paramName {'name'|'attrs'} — Column property to return. Default: 'name'. @@ -270,7 +270,7 @@ private function construct_db(): void { * @return $result[$columnName] {string} — Key is column name, value is column property defined by $params->paramName. */ protected function cols_getColsParams($params = []): array { - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -290,7 +290,7 @@ protected function cols_getColsParams($params = []): array { /** * cols_getOneColParam - * @version 2.0 (2023-12-28) + * @version 2.0.1 (2024-08-02) * * @param $params {arrayAssociative|stdClass} — Parameters, the pass-by-name style is used. Default: —. * @param $params->filter {string} — Filter clause for column properties, see `\DDTools\ObjectCollection`. Default: ''. @@ -299,7 +299,7 @@ protected function cols_getColsParams($params = []): array { * @return {mixed|null} — `null` means that column or property is not exist. */ protected function cols_getOneColParam($params = []){ - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -310,7 +310,7 @@ protected function cols_getOneColParam($params = []){ ] ]); - return \DDTools\ObjectTools::getPropValue([ + return \DDTools\Tools\Objects::getPropValue([ 'object' => $this->columns->getOneItem([ 'filter' => $params->filter, ]), @@ -320,7 +320,7 @@ protected function cols_getOneColParam($params = []){ /** * cols_getValidNames - * @version 1.1.2 (2023-12-28) + * @version 1.1.3 (2024-08-02) * * @desc Gets valid column names. * @@ -332,7 +332,7 @@ protected function cols_getOneColParam($params = []){ * @return $result[$i] {string} */ protected function cols_getValidNames($params = []): array { - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ (object) [ 'colNames' => '*' @@ -369,7 +369,7 @@ protected function cols_getValidNames($params = []): array { /** * items_add - * @version 1.2 (2023-12-28) + * @version 1.2.1 (2024-08-02) * * @param $params {stdClass|arrayAssociative} — The object of parameters. @required * @param $params->items {mixed} — An array of items. @required @@ -392,7 +392,7 @@ public function items_add($params): array { //Items must be an array if (!is_array($params->items)){ - $params->items = \DDTools\ObjectTools::convertType([ + $params->items = \DDTools\Tools\Objects::convertType([ 'object' => $params->items, 'type' => 'objectArray' ]); @@ -432,7 +432,7 @@ public function items_add($params): array { /** * items_update - * @version 1.3.3 (2024-01-16) + * @version 1.3.4 (2024-08-02) * * @param $params {stdClass|arrayAssociative} — The object of parameters. @required * @param $params->data {object|array} — New item data. Existing item will be extended by this data. @required @@ -447,7 +447,7 @@ public function items_add($params): array { * @return $result[$itemIndex]->id {integer} — ID of added item. */ public function items_update($params): array { - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -518,7 +518,7 @@ public function items_update($params): array { $dbResult as $itemId ){ - $result[] = \DDTools\ObjectTools::extend([ + $result[] = \DDTools\Tools\Objects::extend([ 'objects' => [ (object) [ 'id' => $itemId @@ -535,7 +535,7 @@ public function items_update($params): array { /** * items_delete - * @version 1.1 (2023-12-26) + * @version 1.1.1 (2024-08-02) * * @param $params {stdClass|arrayAssociative} — The object of parameters. Default: —. * @param $params->where {stdClass|arrayAssociative|string} — SQL 'WHERE' clause. Default: '' (all items will be deleted). @@ -547,7 +547,7 @@ public function items_update($params): array { * @return {void} */ public function items_delete($params = []): void { - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -572,7 +572,7 @@ public function items_delete($params = []): void { /** * items_get - * @version 1.2 (2023-12-26) + * @version 1.2.1 (2024-08-02) * * @param $params {stdClass|arrayAssociative} — The object of parameters. Default: —. * @param $params->where {stdClass|arrayAssociative|string} — SQL 'WHERE' clause. Default: '' (all items will be returned). @@ -589,7 +589,7 @@ public function items_delete($params = []): void { * @return $result[$itemIndex|$itemFieldValue] {stdClass|mixed} — A item object or item property value if specified in `$params->propAsResultValue`. */ public function items_get($params = []): array { - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -632,7 +632,7 @@ public function items_get($params = []): array { //Save only field value instead of object if needed if (!is_null($params->propAsResultValue)){ - $resultItemObject = \DDTools\ObjectTools::getPropValue([ + $resultItemObject = \DDTools\Tools\Objects::getPropValue([ 'object' => $itemData, 'propName' => $params->propAsResultValue ]); @@ -643,7 +643,7 @@ public function items_get($params = []): array { //Save item if (!is_null($params->propAsResultKey)){ $result[ - \DDTools\ObjectTools::getPropValue([ + \DDTools\Tools\Objects::getPropValue([ 'object' => $itemData, 'propName' => $params->propAsResultKey ]) @@ -693,7 +693,7 @@ protected function items_validateData($params = []) :\stdClass { /** * buildSqlWhereString - * @version 1.1.2 (2023-12-28) + * @version 1.1.3 (2024-08-02) * * @desc Builds where clause string from array. * @@ -704,7 +704,7 @@ protected function items_validateData($params = []) :\stdClass { * @return {string} */ final protected function buildSqlWhereString($params = []): string { - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ (object) [ 'where' => '' @@ -818,7 +818,7 @@ final protected function buildSqlSetString($params): string { /** * buildSqlLimitString - * @version 1.0 (2023-12-08) + * @version 1.0.1 (2024-08-02) * * @param $params {stdClass|arrayAssociative} — The object of parameters. Default: —. * @param $params->limit {integer|0} — Maximum number of items to return. `0` means all matching. Default: 0. @@ -827,7 +827,7 @@ final protected function buildSqlSetString($params): string { * @return {string} */ final protected static function buildSqlLimitString($params = []): string { - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ diff --git a/src/Storage/Storage.php b/src/Storage/Storage.php index 63106c7..e826470 100644 --- a/src/Storage/Storage.php +++ b/src/Storage/Storage.php @@ -75,7 +75,7 @@ abstract public function items_update($params): array; /** * items_updateOne - * @version 1.1 (2024-01-11) + * @version 1.1.1 (2024-08-02) * * @param $params {stdClass|arrayAssociative} — The object of parameters. @required * @param $params->data {object|array} — New item data. Existing item will be extended by this data. @required @@ -87,7 +87,7 @@ abstract public function items_update($params): array; * @return $result->id {integer} — ID of added item. */ public function items_updateOne($params): ?\stdClass { - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ @@ -99,7 +99,7 @@ public function items_updateOne($params): ?\stdClass { ]); $result = $this->items_update( - \DDTools\ObjectTools::extend([ + \DDTools\Tools\Objects::extend([ 'objects' => [ $params, [ @@ -141,7 +141,7 @@ abstract public function items_delete($params = []): void; /** * items_deleteOne - * @version 1.0 (2024-01-16) + * @version 1.0.1 (2024-08-02) * * @param $params {stdClass|arrayAssociative} — The object of parameters. Default: —. * @param $params->where {stdClass|arrayAssociative|string} — SQL 'WHERE' clause. Default: '' (first found item will be deleted). @@ -152,7 +152,7 @@ abstract public function items_delete($params = []): void; */ public function items_deleteOne($params = []): void { $this->items_delete( - \DDTools\ObjectTools::extend([ + \DDTools\Tools\Objects::extend([ 'objects' => [ $params, [ @@ -185,7 +185,7 @@ abstract public function items_get($params = []): array; /** * items_getOne - * @version 1.0 (2023-12-08) + * @version 1.0.1 (2024-08-02) * * @param $params {stdClass|arrayAssociative} — The object of parameters. Default: —. * @param $params->where {string} — SQL 'WHERE' clause. Default: '' (first found item will be returned). @@ -197,7 +197,7 @@ abstract public function items_get($params = []): array; * @return {stdClass|mixed} — Found item object or $params->notFoundResult. */ public function items_getOne($params = []){ - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ //Defaults (object) [ diff --git a/src/Tools/Cache.php b/src/Tools/Cache.php index ee1e339..e68c3bd 100644 --- a/src/Tools/Cache.php +++ b/src/Tools/Cache.php @@ -35,7 +35,7 @@ private static function initStatic(): void { /** * create - * @version 3.0 (2024-08-01) + * @version 3.0.1 (2024-08-02) * * @param $params {stdClass|arrayAssociative} — The object of parameters. * @param $params->resourceId {integer} — Resource ID related to cache (e. g. document ID). @@ -63,7 +63,7 @@ public static function create($params): void { ; if ($dataType != 'str'){ - $params->data = \DDTools\ObjectTools::convertType([ + $params->data = \DDTools\Tools\Objects::convertType([ 'object' => $params->data, 'type' => 'stringJsonAuto', ]); @@ -121,7 +121,7 @@ public static function get($params){ ); if ($dataType != 'str'){ - $result = \DDTools\ObjectTools::convertType([ + $result = \DDTools\Tools\Objects::convertType([ 'object' => $result, 'type' => $dataType == 'obj' @@ -151,7 +151,7 @@ public static function get($params){ public static function clear($params = []): void { static::initStatic(); - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ (object) [ 'resourceId' => null, @@ -192,7 +192,7 @@ public static function clear($params = []): void { * @return {string} */ private static function buildCacheFilePath($params): string { - $params = \DDTools\ObjectTools::extend([ + $params = \DDTools\Tools\Objects::extend([ 'objects' => [ (object) [ 'prefix' => 'doc', diff --git a/src/ObjectTools/ObjectTools.php b/src/Tools/Objects.php similarity index 97% rename from src/ObjectTools/ObjectTools.php rename to src/Tools/Objects.php index 82a81dc..e73e91d 100644 --- a/src/ObjectTools/ObjectTools.php +++ b/src/Tools/Objects.php @@ -1,7 +1,7 @@ [ //Defaults (object) [ @@ -107,7 +107,7 @@ public static function getPropValue($params){ //If first-level exists if ( - \DDTools\ObjectTools::isPropExists([ + \DDTools\Tools\Objects::isPropExists([ 'object' => $params->object, 'propName' => $propNames[0] ]) @@ -147,7 +147,7 @@ public static function getPropValue($params){ /** * convertType - * @version 1.3 (2023-10-01) + * @version 1.3.1 (2024-08-02) * * @see README.md */ @@ -194,16 +194,22 @@ public static function convertType($params){ if (is_null($result)){ //Include PHP.libraries.hjson require_once( + 'Objects' . + DIRECTORY_SEPARATOR . 'hjson' . DIRECTORY_SEPARATOR . 'HJSONException.php' ); require_once( + 'Objects' . + DIRECTORY_SEPARATOR . 'hjson' . DIRECTORY_SEPARATOR . 'HJSONUtils.php' ); require_once( + 'Objects' . + DIRECTORY_SEPARATOR . 'hjson' . DIRECTORY_SEPARATOR . 'HJSONParser.php' diff --git a/src/ObjectTools/hjson/HJSONException.php b/src/Tools/Objects/hjson/HJSONException.php similarity index 100% rename from src/ObjectTools/hjson/HJSONException.php rename to src/Tools/Objects/hjson/HJSONException.php diff --git a/src/ObjectTools/hjson/HJSONParser.php b/src/Tools/Objects/hjson/HJSONParser.php similarity index 100% rename from src/ObjectTools/hjson/HJSONParser.php rename to src/Tools/Objects/hjson/HJSONParser.php diff --git a/src/ObjectTools/hjson/HJSONUtils.php b/src/Tools/Objects/hjson/HJSONUtils.php similarity index 100% rename from src/ObjectTools/hjson/HJSONUtils.php rename to src/Tools/Objects/hjson/HJSONUtils.php diff --git a/src/backwardCompatibility.php b/src/backwardCompatibility.php index 2ee37fd..7636efd 100644 --- a/src/backwardCompatibility.php +++ b/src/backwardCompatibility.php @@ -3,4 +3,6 @@ abstract class BaseClass extends \DDTools\Base\Base { use \DDTools\Base\AncestorTrait; -} \ No newline at end of file +} + +class ObjectTools extends \DDTools\Tools\Objects {} \ No newline at end of file From b5db7cec3b5902aefcb9842e07c0cb87aec74e4c Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Fri, 2 Aug 2024 11:57:21 +0400 Subject: [PATCH 07/12] * `\DDTools\Tools\Files`: The class has been renamed from `\DDTools\FilesTools` (with backward compatibility). --- README.md | 4 ++-- modx.ddtools.class.php | 16 ++++++++-------- require.php | 3 ++- src/Tools/Cache.php | 8 ++++---- .../FilesTools.php => Tools/Files.php} | 8 +++++--- .../Files}/phpThumb/phpthumb.bmp.php | 0 .../Files}/phpThumb/phpthumb.class.php | 0 .../Files}/phpThumb/phpthumb.filters.php | 0 .../Files}/phpThumb/phpthumb.functions.php | 0 .../Files}/phpThumb/phpthumb.gif.php | 0 .../Files}/phpThumb/phpthumb.ico.php | 0 .../Files}/phpThumb/phpthumb.unsharp.php | 0 src/backwardCompatibility.php | 3 ++- 13 files changed, 23 insertions(+), 19 deletions(-) rename src/{FilesTools/FilesTools.php => Tools/Files.php} (98%) rename src/{FilesTools => Tools/Files}/phpThumb/phpthumb.bmp.php (100%) rename src/{FilesTools => Tools/Files}/phpThumb/phpthumb.class.php (100%) rename src/{FilesTools => Tools/Files}/phpThumb/phpthumb.filters.php (100%) rename src/{FilesTools => Tools/Files}/phpThumb/phpthumb.functions.php (100%) rename src/{FilesTools => Tools/Files}/phpThumb/phpthumb.gif.php (100%) rename src/{FilesTools => Tools/Files}/phpThumb/phpthumb.ico.php (100%) rename src/{FilesTools => Tools/Files}/phpThumb/phpthumb.unsharp.php (100%) diff --git a/README.md b/README.md index b6a1ade..bd8a684 100644 --- a/README.md +++ b/README.md @@ -263,10 +263,10 @@ You can use the `exctract` function to turn the array into variables of the curr * Valid values: `mixed` -### `\DDTools\FilesTools` +### `\DDTools\Tools\Files` -#### `\DDTools\FilesTools::modifyImage($params)` +#### `\DDTools\Tools\Files::modifyImage($params)` Modify your images: create thumbnails, crop, resize, fill background color or add watermark. diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index 9ce5d92..fd47677 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -112,7 +112,7 @@ class ddTools { /** * __construct - * @version 1.0.4 (2020-02-11) + * @version 1.0.5 (2024-08-02) */ private function __construct(){ global $modx; @@ -129,7 +129,7 @@ private function __construct(){ } //We need to include required files if Composer is not used - if(!class_exists('\DDTools\FilesTools')){ + if(!class_exists('\DDTools\Tools\Files')){ require_once( __DIR__ . DIRECTORY_SEPARATOR . @@ -3043,7 +3043,7 @@ public static function unfoldArray( /** * createDir - * @version 1.0 (2019-10-22) + * @version 1.0.1 (2024-08-02) * * @desc Makes directory using `$modx->config['new_folder_permissions']`. Nested directories will be created too. Doesn't throw an exception if the folder already exists. * @@ -3053,12 +3053,12 @@ public static function unfoldArray( * @return {boolean} — Success status. */ public static function createDir($params){ - return \DDTools\FilesTools::createDir($params); + return \DDTools\Tools\Files::createDir($params); } /** * copyDir - * @version 1.1 (2018-10-02) + * @version 1.1.1 (2024-08-02) * * @desc Copies a required folder with all contents recursively. * @@ -3071,7 +3071,7 @@ public static function copyDir( $sourcePath, $destinationPath ){ - return \DDTools\FilesTools::copyDir([ + return \DDTools\Tools\Files::copyDir([ 'sourcePath' => $sourcePath, 'destinationPath' => $destinationPath ]); @@ -3079,7 +3079,7 @@ public static function copyDir( /** * removeDir - * @version 1.1 (2018-10-02) + * @version 1.1.1 (2024-08-02) * * @desc Removes a required folder with all contents recursively. * @@ -3088,7 +3088,7 @@ public static function copyDir( * @return {boolean} */ public static function removeDir($path){ - return \DDTools\FilesTools::removeDir($path); + return \DDTools\Tools\Files::removeDir($path); } /** diff --git a/require.php b/require.php index cb3d966..ed03052 100644 --- a/require.php +++ b/require.php @@ -3,8 +3,9 @@ require_once('src/Base/AncestorTrait.php'); require_once('src/Tools/Objects.php'); -require_once('src/FilesTools/FilesTools.php'); +require_once('src/Tools/Files.php'); require_once('src/Tools/Cache.php'); + require_once('src/ObjectCollection/ObjectCollection.php'); require_once('src/Response/Response.php'); require_once('src/Storage/Storage.php'); diff --git a/src/Tools/Cache.php b/src/Tools/Cache.php index e68c3bd..3f1ba03 100644 --- a/src/Tools/Cache.php +++ b/src/Tools/Cache.php @@ -8,7 +8,7 @@ class Cache { /** * initStatic - * @version 2.0 (2024-08-01) + * @version 2.0.1 (2024-08-02) * * @desc Static “constructor”. * @@ -26,7 +26,7 @@ private static function initStatic(): void { ; if (!is_dir(static::$cacheDir)){ - \DDTools\FilesTools::createDir([ + \DDTools\Tools\Files::createDir([ 'path' => static::$cacheDir, ]); } @@ -137,7 +137,7 @@ public static function get($params){ /** * clear - * @version 2.2 (2024-08-01) + * @version 2.2.1 (2024-08-02) * * @param Clear cache files for specified document or every documents. * @@ -164,7 +164,7 @@ public static function clear($params = []): void { //Clear all cache if (empty($params->resourceId)){ - \DDTools\FilesTools::removeDir(static::$cacheDir); + \DDTools\Tools\Files::removeDir(static::$cacheDir); //Clear cache for specified documents }else{ $files = glob( diff --git a/src/FilesTools/FilesTools.php b/src/Tools/Files.php similarity index 98% rename from src/FilesTools/FilesTools.php rename to src/Tools/Files.php index 13bd206..e43f3db 100644 --- a/src/FilesTools/FilesTools.php +++ b/src/Tools/Files.php @@ -1,7 +1,7 @@ Date: Fri, 2 Aug 2024 16:17:20 +0400 Subject: [PATCH 08/12] =?UTF-8?q?*=20`\DDTools\Tools\Cache`:=20The=20follo?= =?UTF-8?q?wing=20pulic=20methods=20have=20been=20renamed:=20=09*=20`creat?= =?UTF-8?q?e`=20=E2=86=92=20`save`.=20=09*=20`clear`=20=E2=86=92=20`delete?= =?UTF-8?q?`.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +++--- src/Tools/Cache.php | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index bd8a684..af0d241 100644 --- a/README.md +++ b/README.md @@ -566,7 +566,7 @@ You can cache some data (e. g. a snippet result) to a file. * Each cache file can contain a string, array or stdClass. -#### `\DDTools\Tools\Cache::create($params)`, `\DDTools\Tools\Cache::get($params)` +#### `\DDTools\Tools\Cache::save($params)`, `\DDTools\Tools\Cache::get($params)` * `$params` * Description: The object of parameters. @@ -591,7 +591,7 @@ You can cache some data (e. g. a snippet result) to a file. * Default value: `'doc'` -#### `\DDTools\Tools\Cache::create($params)` +#### `\DDTools\Tools\Cache::save($params)` Saves custom data to a cache file. @@ -621,7 +621,7 @@ Retrieves data from a cache file. * `null` — means that the cache file does not exist -#### `\DDTools\Tools\Cache::clear($params)` +#### `\DDTools\Tools\Cache::delete($params)` Deletes one or more cache files. diff --git a/src/Tools/Cache.php b/src/Tools/Cache.php index 3f1ba03..ef42c2e 100644 --- a/src/Tools/Cache.php +++ b/src/Tools/Cache.php @@ -34,8 +34,8 @@ private static function initStatic(): void { } /** - * create - * @version 3.0.1 (2024-08-02) + * save + * @version 3.0.2 (2024-08-02) * * @param $params {stdClass|arrayAssociative} — The object of parameters. * @param $params->resourceId {integer} — Resource ID related to cache (e. g. document ID). @@ -45,7 +45,7 @@ private static function initStatic(): void { * * @return {void} */ - public static function create($params): void { + public static function save($params): void { static::initStatic(); $params = (object) $params; @@ -136,8 +136,8 @@ public static function get($params){ } /** - * clear - * @version 2.2.1 (2024-08-02) + * delete + * @version 2.2.2 (2024-08-02) * * @param Clear cache files for specified document or every documents. * @@ -148,7 +148,7 @@ public static function get($params){ * * @return {void} */ - public static function clear($params = []): void { + public static function delete($params = []): void { static::initStatic(); $params = \DDTools\Tools\Objects::extend([ From 07546d0518c7bec4ed6bb8b4c7cbf9fdd3520fd6 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Fri, 2 Aug 2024 18:03:00 +0400 Subject: [PATCH 09/12] * Minor changes (code style). --- CHANGELOG.md | 94 +++++++++ CHANGELOG_ru.md | 96 ++++++++- README.md | 531 +++++++++++++++++++++++++----------------------- 3 files changed, 471 insertions(+), 250 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bdfdb5d..c937bf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,10 +2,12 @@ ## Version 0.62.1 (2024-06-17) + * \* `\ddTools::parseText` → Parameters → `$params->isCompletelyParsingEnabled`: Broken support for deprecated name `$params->mergeAll` has been fixed. ## Version 0.62 (2024-06-14) + * \+ `\ddTools::isEmpty`: The new public static method. Determines whether a variable is empty. * \* `\ddTools::parseText` → Parameters: * \+ `$params->data`: Both objects and arrays are supported regardless of nesting level. @@ -26,26 +28,32 @@ ## Version 0.61 (2023-10-01) + * \+ `\DDTools\ObjectTools::convertType` → Parameters → `$params->type` → Valid values → `'stringHtmlAttrs'`: The new available value. Allows conversion to an HTML attributes string (see README → Examples). ## Version 0.60 (2023-05-14) + * \+ `\ddTools::getTpl`: The new public method (see README). ## Version 0.59 (2023-03-30) + * \+ `\ddTools::parseText`: In addition to accessing nested properties via placeholders like `'[+prop.subProp+]'`, you can get whole object as JSON via placeholders like `'[+prop+]'` (see README → Examples). ## Version 0.58.1 (2023-03-29) + * \* `\DDTools\ObjectTools::convertType` → Parameters → `$params->type` → Valid values → `'stringQueryFormatted'`: A mistake has been fixed. The incorrect value `'stringQueryFormated'` is also supported for backward compatibility. ## Version 0.58 (2023-03-21) + * \+ `\DDTools\Base\AncestorTrait::createChildInstance` → Parameters → `$params->parentDir`: Is no longer required and by default is equal to dirname of a class that uses this trait. ## Version 0.57 (2023-03-09) + * \+ `\DDTools\ObjectTools::getPropValue` → Parameters → `$params->propName`: The method can now get the value of an object property or an array element in any nesting level. Just use `'.'` to get nested properties. Several examples (see full examples in README): * \* `somePlainProp` — get first-level property. @@ -54,6 +62,7 @@ ## Version 0.56 (2023-01-29) + * \+ `\ddTools::sort2dArray` → Parameters → `$array[$i]`: Can also be set as object. * \* `\DDTools\Base\Base`: * \* The class has been renamed from `\DDTools\BaseClass`. Backward compatibility is maintained (you can still use `\DDTools\BaseClass`, but it is not recommended). @@ -67,21 +76,25 @@ ## Version 0.55.1 (2022-12-03) + * \* `\DDTools\FilesTools::modifyImage`: Included PHP.libraries.phpThumb has been updated from 1.7.15-202004301145 to 1.7.19-202210110924 (now supports WebP, PHP8, etc). ## Version 0.55 (2022-09-05) + * \+ `\ddTools::convertUrlToAbsolute`: The new public method. Converts relative URLs to absolute. See more info and examples in README.md. * \* README: Various improvements. ## Version 0.54 (2022-01-08) + * \+ `\DDTools\BaseClass::setExistingProps` → Parameters → `$props`: Can also be set as a [JSON](https://en.wikipedia.org/wiki/JSON), [HJSON](https://hjson.github.io/) or [Query formatted](https://en.wikipedia.org/wiki/Query_string) string. * \* Included PHP.libraries.HJSON has been updated from 2.1 to 2.2. * \+ README → Installation → Update using (MODX)EvolutionCMS.libraries.ddInstaller. ## Version 0.53 (2021-12-13) + * \+ `\DDTools\ObjectCollection`: The new class representing a collection of some objects or arrays. See more info and examples in README. * \* `\ddTools::parseText` → Parameters → `$params->data`: A bug with multidimensional objects has been fixed. * \* README: @@ -90,10 +103,12 @@ ## Version 0.52.1 (2021-11-17) + * \* `\ddTools::parseText`: Fixed working when `$params->data` is a multidimensional object. ## Version 0.52 (2021-11-16) + * \+ `\DDTools\ObjectTools::unfold`: The new method. Converts a multidimensional array/object into an one-dimensional one joining the keys with `$params->keySeparator`. For example, it can be helpful while using placeholders like `[+size.width+]`. @@ -101,10 +116,12 @@ ## Version 0.51 (2021-11-08) + * \+ `\DDTools\ObjectTools::convertType`: Added the ability to return `stringQueryFormatted`. ## Version 0.50 (2021-05-11) + * \+ `\DDTools\Response`: * \+ `setMetaData`: The new public method. Setter for `$this->meta` and `$this->data`. * \+ `setMeta` → Parameters: @@ -117,10 +134,12 @@ ## Version 0.49.1 (2021-04-27) + * \* `\DDTools\ObjectTools::extend`: Improved deep cloning objects to arrays. ## Version 0.49 (2021-04-25) + * \* `\ddTools::parseText`: * \+ Parameters → `$params->data`: Can also be set as JSON, HJSON or Query string. * \* `\DDTools\ObjectTools::extend` is used instead of `array_merge`. @@ -128,46 +147,55 @@ ## Version 0.48.2 (2021-03-31) + * \* `\DDTools\ObjectTools::extend`: Added deep object cloning to prevent references. ## Version 0.48.1 (2021-03-29) + * \* `\DDTools\Snippet::prepareParams`: Type of only existing params will be converted. ## Version 0.48 (2021-03-25) + * \+ `\DDTools\Snippet`: * \+ `$paramsTypes`: The new property. Overwrite in child classes if you want to convert some parameters types. * \+ `prepareParams`: The parameter types will be converted respectively with `$this->paramsTypes`. ## Version 0.47 (2021-03-20) + * \+ `\DDTools\ObjectTools::convertType`: * \+ Added [HJSON](https://hjson.github.io/) support (closes #7). * \+ Improved detection of failed `json_decode` attempt. ## Version 0.46 (2021-03-15) + * \+ `\ddTools::updateDocument`: Added default values for the following parameters: * \+ `$docData->editedon`: If it isn't set, it will be equal to current date-time (`time()`). * \+ `$docData->editedby`: If it isn't set, it will be equal to `1`. ## Version 0.45.1 (2021-03-12) + * \* `\DDTools\ObjectTools::extend`: * \* Recursion is called only if source value is an object or array. * \* Optimization. ## Version 0.45 (2021-03-11) + * \+ `\DDTools\Response::isSuccess`: The new public method. ## Version 0.44 (2021-03-10) + * \+ `\DDTools\Snippet::prepareParams`: The new method. ## Version 0.43 (2021-03-10) + * \* Attention! PHP >= 5.6 is required. * \* `\DDTools\Response`: * \- Child version classes are not used anymore. @@ -182,6 +210,7 @@ ## Version 0.42 (2021-02-24) + * \* `\ddTools::verifyRenamedParams`: * \+ If `$params->params` set as an object, the method will return an instance of stdClass. * \* `\DDTools\ObjectTools::extend` is used instead of `array_merge`. @@ -191,15 +220,18 @@ ## Version 0.41 (2020-12-15) + * \+ `\ddTools::getDocumentIdByUrl`: Supports domains in IDNA ASCII-compatible format. ## Version 0.40.1 (2020-06-22) + * \* `\ddTools::createDocument`, `\ddTools::updateDocument`: Document field values will be prepared by `$modx->db->escape()`. * \+ `\ddTools::createDocument` → Parameters → `$docData->pagetitle`: Can't be equal to `''`, so will be equal to `'New resource'` in this case. ## Version 0.40 (2020-06-19) + * \* `\DDTools\FilesTools::modifyImage`: * \+ Supports `.ico` and `.bmp`. * \+ `$params->watermarkImageFullPathName`: The new parameter. You can overlay your image with needed watermark image. @@ -215,11 +247,13 @@ ## Version 0.39 (2020-06-07) + * \+ `\ddTools::createDocument` → Parameters → `$docData->alias`: Will be transliterated from `$docData->pagetitle` if empty or not set. * \* README → Documentation → Installation → Using Composer: Fixed the library name. ## Version 0.38.1 (2020-06-02) + * \* `\DDTools\ObjectTools::convertType`: Fixed type of deep objects when `$params->type` == `'objectarray'`. * \* README: * \- Home page. @@ -227,6 +261,7 @@ ## Version 0.38 (2020-06-02) + * \+ `\DDTools\ObjectTools::convertType`: The new method. Converts an object type. Arrays, JSON and Query string objects are also supported. * \* `\ddTools::encodedStringToArray`: * \* Now uses `\DDTools\ObjectTools::convertType`. @@ -234,22 +269,26 @@ ## Version 0.37.1 (2020-05-28) + * \* `ddTools::createDocument`: * \* Parameters → `$docData->pagetitle`: Is not required anymore and by default will be equal to `'New resource'`. * \* Small refactoring. ## Version 0.37 (2020-05-24) + * \* `\ddTools::sort2dArray`: * \+ Associative arrays are also supported. * \* Small refactoring. ## Version 0.36 (2020-05-18) + * \+ `\ddTools::prepareDocData`, `\ddTools::createDocument`, `\ddTools::updateDocument`: Also can take document fields as stdClass, not only as an associative array. ## Version 0.35.1 (2020-05-08) + * \* Composer.json: * \+ `authors`. * \* `name`: Changed from `dd/modxevo-library-ddtools` to `dd/evolutioncms-libraries-ddtools`. @@ -257,6 +296,7 @@ ## Version 0.35 (2020-05-06) + * \+ `\DDTools\BaseClass::toArray`. Returns all properties of this object as an associative array independent of their visibility. * \+ `\DDTools\BaseClass::toJSON`. Returns all properties of this object as an JSON string independent of their visibility. * \+ `\DDTools\BaseClass::__toString()`. The same as `\DDTools\BaseClass::toJSON()`. @@ -266,6 +306,7 @@ ## Version 0.34 (2020-04-30) + * \+ `\DDTools\ObjectTools::extend`: * \+ Added the ability to prevent fields overwriting with empty values (`$params->overwriteWithEmpty`). * \+ Objects can extend arrays and vice versa. @@ -276,15 +317,18 @@ ## Version 0.33.1 (2020-04-29) + * \* `\DDTools\ObjectTools::extend`: Fixed array deep extending error if an original array item is not exist. ## Version 0.33 (2020-04-28) + * \+ `\DDTools\ObjectTools::extend`: Arrays can also be extended. * \* CHANGELOG: Fixed misprints. ## Version 0.32 (2020-04-25) + * \* `\ddTools::verifyRenamedParams`: * \* Pass-by-name style is used (with backward compatibility). * \+ Added an ability to prevent writing to the CMS event log (see `$params->writeToLog`). @@ -298,11 +342,13 @@ ## Version 0.31 (2020-04-23) + * \+ `\DDTools\ObjectTools::extend`. Merge the contents of two or more objects together into the first object (see README.md). * \* README: Style improvements. ## Version 0.30 (2020-02-11) + * \* Attention! (MODX)EvolutionCMS >= 1.1 is required. * \+ `\ddTools::getDocumentParentIds`. Gets the parent ID(s) of the required level. * \+ `\ddTools::clearCache`. Clears cache of required document(s) and their parents. @@ -310,22 +356,27 @@ ## Version 0.29.1 (2019-12-15) + * \* `\DDTools\BaseClass::setProp`: Do nothing if property is not exist. ## Version 0.29 (2019-12-14) + * \+ `\DDTools\BaseClass::setExistingProps`: Can set properties of all parent and child classes. ## Version 0.28 (2019-10-22) + * \+ `\DDTools\FilesTools::createDir` (and `\ddTools::createDir` as alias): Makes directory using `$modx->config['new_folder_permissions']`. Nested directories will be created too. Doesn't throw an exception if the folder already exists. ## Version 0.27 (2019-09-19) + * \+ `\ddTools::encodedStringToArray`: Can take an array too (sometimes it's convenient to not think about it). ## Version 0.26 (2019-09-09) + * \* Attention! Backward compatibility with 0.25 is broken. * \- `\DDTools\ObjectTools`. * \+ `\DDTools\BaseClass`. @@ -334,21 +385,25 @@ ## Version 0.25 (2019-06-27) + * \+ `\DDTools\ObjectTools::setExistingProps`: The new method. Sets existing object properties. * \+ `\DDTools\ObjectTools::createChildInstance`: The new method. Creates an instance of the needed child class (e. g. `\ddSendFeedback\Sender\Telegram\Sender`). ## Version 0.24 (2018-12-25) + * \+ `\ddTools::parseSource`: Uncashed snippets will be evaled too. * \* Some refactoring and alpha functional. ## Version 0.23 (2018-06-26) + * \+ `\ddTools::parseText`: `$params->data` can be set now as `stdClass`. * \* `\ddTools::encodedStringToArray`: Fixed event logging if `$inputString` is empty. ## Version 0.22 (2018-06-17) + * \+ `\ddTools::sendMail`: SMTP support added. _Many thanks to [@Aharito](https://github.com/Aharito)._ * \+ `\ddTools::createDocument`, `\ddTools::updateDocument`: TV-dates wich set as unix time will be converted to correct system date format. * \+ `\ddTools::prepareDocData`: The new method. Prepare document data from single array of fields and TVs: separate them and get TVs additional data if needed. @@ -356,39 +411,47 @@ ## Version 0.21 (2017-12-09) + * \+ `\ddTools::$tables`: Added all MODX tables except deprecated `keyword_xref`, `site_content_metatags`, `site_keywords` and `site_metatags`. ## Version 0.20 (2017-10-10) + * \+ `\ddTools::getPlaceholdersFromText`: The new method. Finds all placeholders' names and returns them as an array. * \* `\ddTools::escapeForJS`: Fixed excessive backslach escaping. ## Version 0.19 (2017-10-09) + * \* `\ddTools::sendMail`: Fixed displaying of the file in the mail agent. * \* `\ddTools::escapeForJS`: Added backslach escaping. _Many thanks to [@Aharito](https://github.com/Aharito)._ * \* The library now works correctly without Composer. ## Version 0.18 (2017-02-10) + * \+ `\ddTools::logEvent`: The new method. Adds an alert message to the MODX event log with additional debug info (backtrace, snippet name, document id, etc). * \+ `\ddTools::encodedStringToArray`: The new method. Converts encoded strings to arrays. Supported formats: [JSON](https://en.wikipedia.org/wiki/JSON) and [Query string](https://en.wikipedia.org/wiki/Query_string). ## Version 0.17 (2017-01-10) + * \+ `\ddTools::parseText`: Added support of nested arrays in `$params->data`. ## Version 0.16.2 (2016-12-16) + * \* `\ddTools::generateRandomString`: The `$chars` parameter setting was fixed. ## Version 0.16.1 (2016-11-01) + * \* `\ddTools::screening`: Was renamed as `\ddTools::escapeForJS` (with backward compatibility). * \* `\ddTools::orderedParamsToNamed`: Now is public. But be advised that this is beta-version! ## Version 0.16 (2016-10-29) + * \* Attention! PHP >= 5.4 is required. * \* `\ddTools::parseText`: Updated to 1.3.1: * \* Refactoring, the method now using [named parameters](https://en.wikipedia.org/wiki/Named_parameter) (with backward compatibility). @@ -403,25 +466,30 @@ ## Version 0.15.4 (2016-06-17) + * \* `\ddTools::verifyRenamedParams`: Updated to 1.1.1: * \+ An ability to use multiple old names was added (see the `$compliance` parameter). * \* Minor refactoring, code style and description changes. ## Version 0.15.3 (2016-01-12) + * \* `\ddTools::sendMail`: The content and headers of an email are now passed to the `mail` function separately. This fixes empty email contents in some email clients. ## Version 0.15.2 (2016-01-11) + * \* `\ddTools::updateDocument`: The method now uses `mysqli_info` if `$modx->db->conn` is an instance of the `mysqli` class or `mysql_info` otherwise. ## Version 0.15.1 (2015-12-29) + * \* The `$modx->getVersionData` method existence check was moved under the isset $modx condition. * \* `\ddTools::getTemplateVarOutput`: The check for existence of `$row['id']` was changed to an isset check. ## Version 0.15 (2015-12-25) + * \+ `\ddTools::copyDir`: The new method. It allows copying a folder with all its contents recursively. * \* `\ddTools::updateDocument`: The method now uses `mysqli_info` instead of `mysql_info`. * \* `\ddTools::getDocuments`: user access options are now completely ignored while retrieving. It’s done because the method is supposed to be a low level implementation, so it’s implied that a structure of a higher level will be dealing with user access. @@ -430,14 +498,17 @@ ## Version 0.14.3 (2015-12-13) + * \+ An `isset` check for the global `$modx` variable has been added to prevent an error when calling the `$modx->getFullTableName` method. ## Version 0.14.2 (2015-11-05) + * \+ Added a global statement at the beginning to make sure that `$modx` is available. Without the statement an error occurs while autoloading via Composer. ## Version 0.14.1 (2015-11-03) + * \* The following methods need their `$publication` and `$deleted` parameters to be set as `'all'` to return the required documents regardless of their publication and / or removal status(es). The previous value (`false`) is still supported but causes a warning in the log and will be dropped sometime: * \* `\ddTools::getDocuments`. * \* `\ddTools::getDocument`. @@ -449,32 +520,39 @@ ## Version 0.14 (2015-10-05) + * \* The structure of the repository has been completely changed to meet the Composer requirements. ## Version 0.13.3 (2015-09-17) + * \* `\ddTools::createDocument`: The `path` of a new document now properly depends on the `alias` / `id` of its parent. ## Version 0.13.2 (2015-09-07) + * \* `\ddTools::createDocument`: The method has been slightly changed. The MODX `documentMap` and `aliasListing` config arrays are now being modified properly while the method is called. ## Version 0.13.1 (2015-08-17) + * \* `\ddTools::sendMail`: The method was slightly changed to eliminate errors in PHP 5.4−5.6 during headers validation: * \* All double `\r\n` and singe `\r\n` were replaced with single `PHP_EOL`. * \* Leading or trailing `PHP_EOL`'s are now trimmed in email content. ## Version 0.13 (2014-07-13) + * \+ `\ddTools::sendMail`: The new method. It sends emails. ## Version 0.12 (2014-05-23) + * \+ `\ddTools::verifyRenamedParams`: The new method. It checks an array for deprecated parameters and writes warning messages into the MODX event log. It returns an associative array, in which the correct parameter names are the keys and the parameter values are the values. You can use the `exctract` function to turn the array into variables of the current symbol table. ## Version 0.11.1 (2014-04-11) + * \* The following methods have been slightly updated in accordance with MODX 1.0.13: * \* `\ddTools::getDocuments`. * \* `\ddTools::getTemplateVars`. @@ -484,43 +562,51 @@ ## Version 0.11 (2014-02-11) + * \+ `\ddTools::ddTools::sort2dArray`: The new method. It sorts 2-dimensional array by multiple columns (like in SQL) using Hoare’s method, also referred to as quicksort. The sorting is stable. * \* Small changes for compatibility with old MODX versions. * \* Bugfix: The method `\ddTools::unfoldArray` didn’t used to be static. ## Version 0.10 (2013-10-17) + * \+ `\ddTools::unfoldArray`: The new method. Converts a multidimensional array into an one-dimensional one joining the keys with `'.'` (see the description & examples). * \* `\ddTools::$documentFields`: The field `alias_visible` will be added to the array only if the version of MODX is later than 1.0.11 for backward compatibility. * \* The array `\ddTools::$tables` with its elements is declared directly in the class to make it clear. ## Version 0.9.2 (2013-10-17) + * \* Attention! MODX >= 1.0.12 is required. * \* `\ddTools::$documentFields`: The field `alias_visible` has been added to the array (MODX 1.0.12). ## Version 0.9.1 (2013-10-10) + * \* `\ddTools::parseFileNameVersion`: Updated to 1.1: * \* File extension is currently returned along with file name & version. ## Version 0.9 (2013-09-03) + * \+ `\ddTools::getDocumentIdByUrl`: The new method. It gets ID of a document by its URL. ## Version 0.8.1 (2013-07-11) + * \* `\ddTools::explodeAssoc`: Updated to 1.1.1: * \* The processing of an empty string as input argument has been added (the method returns an empty array in such cases). ## Version 0.8 (2013-07-06) + * \+ `\ddTools::parseFileNameVersion`: The new method. It parses a file path and gets its name & version. * \* `\ddTools::regEmptyClientScript`: Updated to 1.0.1: * \* Bugfix: A current version use is checked when an empty value assigns to `$modx->sjscripts` or `$modx->jscripts`. ## Version 0.7 (2013-05-15) + * \+ `\ddTools::getDocumentChildren`: The new method (which is analog of the native one). The method gets fields values of child documents. The values can be got regardless of their documents publication status, that is unavailable in the native method. * \* `\ddTools::getDocumentChildrenTVarOutput`: Updated to 1.1: * \* `published` parameter can be === `false`, then documents publication status does not matter. @@ -528,6 +614,7 @@ ## Version 0.6.1 (2013-04-26) + * \* Bugfix: The following methods were not static: * \* `\ddTools::getDocuments`. * \* `\ddTools::getDocument`. @@ -536,6 +623,7 @@ ## Version 0.6 (2013-03-26) + * \+ A few standard methods to work with documents were added. The methods return results regardless of documents published status: * \+ `\ddTools::getDocuments`. It gets required documents (documents fields). * \+ `\ddTools::getDocument`. It gets required documents (document field). @@ -545,16 +633,19 @@ ## Version 0.5 (2013-03-12) + * \+ `\ddTools::removeDir`: The new method. It removes a required folder with all contents recursively. * \+ `\ddTools::regEmptyClientScript`: The new method. It adds a required JS-file into a required MODX inner list according to its version and name and is used to register the scripts, that had already been connected manually. ## Version 0.4.1 (2013-02-28) + * \* `\ddTools::explodeAssoc`: Updated to 1.1: * \* The empty value check while key→value splitting has been added (if value is empty then empty string inserts). ## Version 0.4 (2012-10-26) + * \* `\ddTools::updateDocument`: Updated to 1.2: * \* The updateDocument name error has been corrected. * \* Id parameter takes the value of a positive integer or an array. @@ -564,10 +655,12 @@ ## Version 0.3 (2012-04-11) + * \+ `\ddTools::getDocumentChildrenTVarOutput`: The new method. It gets necessary children of document. ## Version 0.2 (2012-03-21) + * \* Attention! Backward compatibility is broken. * \+ `\ddTools::$documentFields`: The new field. It contains array of document fields names. * \+ `\ddTools::$tables`: The new field. It contains full names of some db tables. @@ -586,6 +679,7 @@ ## Version 0.1 (2012-02-03) + * \+ The first release. diff --git a/CHANGELOG_ru.md b/CHANGELOG_ru.md index 8b8085a..0420c10 100644 --- a/CHANGELOG_ru.md +++ b/CHANGELOG_ru.md @@ -2,10 +2,12 @@ ## Версия 0.62.1 (2024-06-17) + * \* `\ddTools::parseText` → Parameters → `$params->isCompletelyParsingEnabled`: Неработающая поддержка устаревшего названия `$params->mergeAll` исправлена. ## Версия 0.62 (2024-06-14) + * \+ `\ddTools::isEmpty`: Новый публичный статичный метод. Проверяет, пуста ли переменная. * \* `\ddTools::parseText` → Параметры: * \+ `$params->data`: Поддерживаются как объекты, так и массивы одновременно, независимо от уровня вложенности. @@ -26,26 +28,32 @@ ## Версия 0.61 (2023-10-01) + * \+ `\DDTools\ObjectTools::convertType` → Параметры → `$params->type` → Допустимые значения → `'stringHtmlAttrs'`: Новое значение. Позволяет преобразовать в строку HTML-атрибутов (см. README → Примеры). ## Версия 0.60 (2023-05-14) + * \+ `\ddTools::getTpl`: Новый публичный метод (см. README). ## Версия 0.59 (2023-03-30) + * \+ `\ddTools::parseText`: Помимо доступа свойствам вложенных объектов через плейсхоледры вида `'[+prop.subProp+]'`, вы также можете получить весь объект в JSON через плейсхолдеры вида `'[+prop+]'` (см. README → Примеры). ## Версия 0.58.1 (2023-03-29) + * \* `\DDTools\ObjectTools::convertType` → Параметры → `$params->type` → Допустимые значения → `'stringQueryFormatted'`: Исправлена ошибка в написании. Некорректное значение `'stringQueryFormated'` также поддерживается для обратной совместимости. ## Версия 0.58 (2023-03-21) + * \+ `\DDTools\Base\AncestorTrait::createChildInstance` → Параметры → `$params->parentDir`: Больше не обязателен и по умолчанию равен папке класса, использующего этот трейт. ## Версия 0.57 (2023-03-09) + * \+ `\DDTools\ObjectTools::getPropValue` → Параметры → `$params->propName`: Теперь метод умеет получать значение свойства объекта или элемента массива на любом уровне вложенности. Просто используйте `'.'` в параметре для получения свойств вложенных элементов. Несколько примеров (см. полные примеры в README): * \* `somePlainProp` — получить свойство первого уровня. @@ -54,6 +62,7 @@ ## Версия 0.56 (2023-01-29) + * \+ `\ddTools::sort2dArray` → Параметры → `$array[$i]`: Также может быть задан, как объект. * \* `\DDTools\Base\Base`: * \* Класс переименован из `\DDTools\BaseClass`. Обратная совместимость сохранена (множно использовать `\DDTools\BaseClass`, но не рекомендуется). @@ -67,21 +76,25 @@ ## Версия 0.55.1 (2022-12-03) + * \* `\DDTools\FilesTools::modifyImage`: PHP.libraries.phpThumb, включённая в репозиторий, обновлена с 1.7.15-202004301145 до 1.7.19-202210110924 (теперь поддерживает WebP, PHP8, etc). ## Версия 0.55 (2022-09-05) + * \+ `\ddTools::convertUrlToAbsolute`: Новый публичный метод. Конвертирует относительные URL в абсолютные. См. больше информации и примеры в README. * \* README: Различные улучшения. ## Версия 0.54 (2022-01-08) + * \+ `\DDTools\BaseClass::setExistingProps` → Параметры → `$props`: Также может быть задан как строка в формете [JSON](https://ru.wikipedia.org/wiki/JSON), [HJSON](https://hjson.github.io/) или [Query](https://en.wikipedia.org/wiki/Query_string). * \* PHP.libraries.HJSON, включённая в репозиторий, обновлена с 2.1 до 2.2. * \+ README → Установка → Обновление используя (MODX)EvolutionCMS.libraries.ddInstaller. ## Версия 0.53 (2021-12-13) + * \+ `\DDTools\ObjectCollection`: Новый класс, представляющий коллекцию некоторых объектов или массивов. См. больше информации и примеры в README. * \* `\ddTools::parseText` → Параметры → `$params->data`: Исправлена ошибка с многомерными объектами. * \* README: @@ -90,10 +103,12 @@ ## Версия 0.52.1 (2021-11-17) + * \* `\ddTools::parseText`: Исправлена работа, Когда `$params->data` является многомерным объектом. ## Версия 0.52 (2021-11-16) + * \+ `\DDTools\ObjectTools::unfold`: Новый метод. Преобразует многомерный массив в одномерный, при этом ключи результирующего массива сливаются через `$params->keySeparator`. Например, это может быть полезно при необходимости использования «вложенных плэйсхолдеров» (`[+size.width+]`). @@ -101,10 +116,12 @@ ## Версия 0.51 (2021-11-08) + * \+ `\DDTools\ObjectTools::convertType`: Добавлена возможность конвертировать в `stringQueryFormatted`. ## Версия 0.50 (2021-05-11) + * \+ `\DDTools\Response`: * \+ `setMetaData`: Новый публичный метод. Сеттер для `$this->meta` и `$this->data`. * \+ `setMeta` → Параметры: @@ -117,10 +134,12 @@ ## Версия 0.49.1 (2021-04-27) + * \* `\DDTools\ObjectTools::extend`: Улучшено глубокое клонирование объектов в массивы. ## Версия 0.49 (2021-04-25) + * \* `\ddTools::parseText`: * \+ Параметры → `$params->data`: Также может быть задан как JSON, HJSON или Query string. * \* `\DDTools\ObjectTools::extend` исползуется вместо `array_merge`. @@ -128,46 +147,55 @@ ## Версия 0.48.2 (2021-03-31) + * \* `\DDTools\ObjectTools::extend`: Добавлено глубокое клонирование объектов для предотвращения ссылок. ## Версия 0.48.1 (2021-03-29) + * \* `\DDTools\Snippet::prepareParams`: Тип только существующих параметров будет преобразован. ## Версия 0.48 (2021-03-25) + * \+ `\DDTools\Snippet`: * \+ `$paramsTypes`: Новое свойство. Перекройте в дочерних классах если вы хотите сконвертировать типы параметров. * \+ `prepareParams`: Типы параметров будут сконвертированы соответственно с `$this->paramsTypes`. ## Версия 0.47 (2021-03-20) + * \+ `\DDTools\ObjectTools::convertType`: * \+ Добавлена поддержка [HJSON](https://hjson.github.io/) (closes #7). * \+ Улучшено обнаружение неудачной попытки `json_decode`. ## Версия 0.46 (2021-03-15) + * \+ `\ddTools::updateDocument`: Добавлены значения по умолчанию для следующих параметров: * \+ `$docData->editedon`: Если не задан — будет равен текущей дате-времени (`time()`). * \+ `$docData->editedby`: Если не задан — будет равен `1`. ## Версия 0.45.1 (2021-03-12) + * \* `\DDTools\ObjectTools::extend`: * \* Рекурсия вызывается только в том случае, если исходным значением является объект или массив. * \* Оптимизация. ## Версия 0.45 (2021-03-11) + * \+ `\DDTools\Response::isSuccess`: Новый публичный метод. ## Версия 0.44 (2021-03-10) + * \+ `\DDTools\Snippet::prepareParams`: Новый метод. ## Версия 0.43 (2021-03-10) + * \* Внимание! Требуется PHP >= 5.6. * \* `\DDTools\Response`: * \- Дочерние версионные классы больше не используются. @@ -182,6 +210,7 @@ ## Версия 0.42 (2021-02-24) + * \* `\ddTools::verifyRenamedParams`: * \+ Если `$params->params` задан, как объект — метод вернёт экземпляр stdClass. * \* `\DDTools\ObjectTools::extend` исползуется вместо `array_merge`. @@ -191,15 +220,18 @@ ## Версия 0.41 (2020-12-15) + * \+ `\ddTools::getDocumentIdByUrl`: Поддерживает домены в формате IDNA ASCII. ## Версия 0.40.1 (2020-06-22) + * \* `\ddTools::createDocument`, `\ddTools::updateDocument`: Значения полей документов перед записью обрабатываются `$modx->db->escape()`. * \+ `\ddTools::createDocument` → Параметры → `$docData->pagetitle`: Не может быть равен `''`, так что будет равен `'New resource'` в этом случае. ## Версия 0.40 (2020-06-19) + * \* `\DDTools\FilesTools::modifyImage`: * \+ Поддерживает `.ico` и `.bmp`. * \+ `$params->watermarkImageFullPathName`: Новый параметр. Вы можете накладывать на ваши изображения водяные знаки (изображение в формате PNG). @@ -215,11 +247,13 @@ ## Версия 0.39 (2020-06-07) + * \+ `\ddTools::createDocument` → Параметры → `$docData->alias`: Будет транлитерирован из `$docData->pagetitle` если пуст или не задан. * \* README → Документация → Установка → Используя Composer: Исправлено имя библиотеки. ## Версия 0.38.1 (2020-06-02) + * \* `\DDTools\ObjectTools::convertType`: Исправлен тип вложенных объектов при `$params->type` == `'objectarray'`. * \* README: * \- Home page. @@ -227,6 +261,7 @@ ## Версия 0.38 (2020-06-02) + * \+ `\DDTools\ObjectTools::convertType`: Новый метод. Преобразует тип объекта. Массивы, JSON и Query string объекты также поддерживаются. * \* `\ddTools::encodedStringToArray`: * \* Теперь использует `\DDTools\ObjectTools::convertType`. @@ -234,22 +269,26 @@ ## Версия 0.37.1 (2020-05-28) + * \* `ddTools::createDocument`: * \* Параметры → `$docData->pagetitle`: Больше не обязтелен и по умолчанию будет равен `'New resource'`. * \* Небольшой рефакторинг. ## Версия 0.37 (2020-05-24) + * \* `\ddTools::sort2dArray`: * \+ Ассоциативные массивы также поддерживаются. * \* Небольшой рефакторинг. ## Версия 0.36 (2020-05-18) + * \+ `\ddTools::prepareDocData`, `\ddTools::createDocument`, `\ddTools::updateDocument`: Также могут принимать поля документа как `stdClass`, не только в виде ассоциативного массива. ## Версия 0.35.1 (2020-05-08) + * \* Composer.json: * \+ `authors`. * \* `name`: Изменено с `dd/modxevo-library-ddtools` на `dd/evolutioncms-libraries-ddtools`. @@ -257,6 +296,7 @@ ## Версия 0.35 (2020-05-06) + * \+ `\DDTools\BaseClass::toArray`. Новый метод. Возвращает все свойства этого экземпляра объекта в виде ассоциативного массива вне зависимости от их видимости. * \+ `\DDTools\BaseClass::toJSON`. Новый метод. Возвращает все свойства этого экземпляра объекта в виде JSON строки вне зависимости от их видимости. * \+ `\DDTools\BaseClass::__toString()`. Новый метод. Аналогичен `\DDTools\BaseClass::toJSON()`. @@ -266,6 +306,7 @@ ## Версия 0.34 (2020-04-30) + * \+ `\DDTools\ObjectTools::extend`: * \+ Добавлена возможность предотвратить перезапись полей пустыми значениями (`$params->overwriteWithEmpty`). * \+ Объекты могут расширять массивы и наоборот. @@ -276,15 +317,18 @@ ## Версия 0.33.1 (2020-04-29) + * \* `\DDTools\ObjectTools::extend`: Исправлена ошибка при глубоком расширении массивов, когда оригинальный элемент массива не существует. ## Версия 0.33 (2020-04-28) + * \+ `\DDTools\ObjectTools::extend`: Массивы также могут быть расширены. * \* CHANGELOG: Исправлены опечатки. ## Версия 0.32 (2020-04-25) + * \* `\ddTools::verifyRenamedParams`: * \* Метод теперь использует [именованные параметры](https://en.wikipedia.org/wiki/Named_parameter) (с сохранением обратной совместимости). * \+ Добавлена возможность предотвратить записи в лог событий CMS (см. `$params->writeToLog`). @@ -298,11 +342,13 @@ ## Версия 0.31 (2020-04-23) + * \+ `\DDTools\ObjectTools::extend`. Новый метод. Сливает содержимое двух и более объектов вместе в первый объект (см. README.md). * \* README: Стиль улучшен. ## Версия 0.30 (2020-02-11) + * \* Внимание! Требуется (MODX)EvolutionCMS >= 1.1. * \+ `\ddTools::getDocumentParentIds`. Новый метод. Получает ID родителя(лей) необходимого уровня. * \+ `\ddTools::clearCache`. Новый метод. Очищает кэш необхоидмых документов и их родителей. @@ -310,22 +356,27 @@ ## Версия 0.29.1 (2019-12-15) + * \* `\DDTools\BaseClass::setProp`: Ничего не делает, если свойство существует. ## Версия 0.29 (2019-12-14) + * \+ `\DDTools\BaseClass::setExistingProps`: Также устанавливает совйства всех родительских и дочерних классов объекта. ## Версия 0.28 (2019-10-22) + * \+ `\DDTools\FilesTools::createDir` (и `\ddTools::createDir`, как псевдоним): Новый метод. Создаёт папку, используя `$modx->config['new_folder_permissions']`. Вложенные папки также будут созданы. Не выбрасывает ошибку, если папка уже существует. ## Версия 0.27 (2019-09-19) + * \+ `\ddTools::encodedStringToArray`: Может также принимать массивы (иногда удобно не думать об этом). ## Версия 0.26 (2019-09-09) + * \* Внимание! Обратная совместимость с версией 0.25 нарушена. * \- `\DDTools\ObjectTools`. * \+ `\DDTools\BaseClass`. @@ -334,21 +385,25 @@ ## Версия 0.25 (2019-06-27) + * \+ `\DDTools\ObjectTools::setExistingProps`: Новый метод. Устанавливает существующие свойства объекта. * \+ `\DDTools\ObjectTools::createChildInstance`: Новый метод. Создает экземпляр требуемого дочернего класса (пример использования в `\ddSendFeedback\Sender\Telegram\Sender`). ## Версия 0.24 (2018-12-25) + * \+ `\ddTools::parseSource`: Некэшируемые сниппеты также будут выполнены. * \* Некоторый рефакторинг и альфа-функционал. ## Версия 0.23 (2018-06-26) + * \+ `\ddTools::parseText`: `$params->data` теперь может быть задан как `stdClass`. * \* `\ddTools::encodedStringToArray`: Исправлено лишнее логирование в журнал MODX при пустом значении `$inputString`. ## Версия 0.22 (2018-06-17) + * \+ `\ddTools::sendMail`: Добавлена поддержка SMTP. _Спасибо, [@Aharito](https://github.com/Aharito)._ * \+ `\ddTools::createDocument`, `\ddTools::updateDocument`: TV-даты, заданные в формате unixtime будут сконвертированы в правильный системынй формат даты. * \+ `\ddTools::prepareDocData`: Новый метод. Подготавливает данные документа из единого массива полей и TV документа: разделяет их и получает дополнительные данные TV, если нужно. @@ -356,39 +411,47 @@ ## Версия 0.21 (2017-12-09) + * \+ `\ddTools::$tables`: Добавлены все таблицы MODX, за исключением устаревших `keyword_xref`, `site_content_metatags`, `site_keywords` и `site_metatags`. ## Версия 0.20 (2017-10-10) + * \+ `\ddTools::getPlaceholdersFromText`: Новый метод. Находит все имена плейсхолдеров и возвращает их как массив. * \* `\ddTools::escapeForJS`: Поправлено чрезмерное экранирование. ## Версия 0.19 (2017-10-09) + * \* `\ddTools::sendMail`: Исправлено отображение файла в почте. * \* `\ddTools::escapeForJS`: Добавлено экранирование `\`. _Большое спасибо, [@Aharito](https://github.com/Aharito)._ * \* Библиотека работает корректно без Composer. ## Версия 0.18 (2017-02-10) + * \+ `\ddTools::logEvent`: Новый метод. Записывает сообщение в системный лог с дополнительной отладочной информацией (cтэк вызовов, имя сниппета, в котором произошёл вызов, ID документа и т. п.). * \+ `\ddTools::encodedStringToArray`: Новый метод. Преобразовывает закодированную строку в массив. Поддерживаемые форматы: [JSON](https://ru.wikipedia.org/wiki/JSON) и [Query string](https://en.wikipedia.org/wiki/Query_string). ## Версия 0.17 (2017-01-10) + * \+ `\ddTools::parseText`: Добавлена поддержка вложенных массивов в `$params->data`. ## Версия 0.16.2 (2016-12-16) -* \* `\ddTools::generateRandomString`: Исправлен параметр `$chars`. + +* \* `\ddTools::generateRandomSring`: Исправлен параметр `$chars`. ## Версия 0.16.1 (2016-11-01) + * \* `\ddTools::escapeForJS`: Переименован из `\ddTools::screening` (с сохранением обратной совместимости). * \* `\ddTools::orderedParamsToNamed`: Метод теперь публичный. Но имейте ввиду, что это пока beta-версия! ## Версия 0.16 (2016-10-29) + * \* Внимание! Требуется PHP >= 5.4. * \* `\ddTools::parseText` обновлён до 1.3.1: * \* Рефакторинг, метод теперь использует [именованные параметры](https://en.wikipedia.org/wiki/Named_parameter) (с сохранением обратной совместимости). @@ -403,25 +466,30 @@ ## Версия 0.15.4 (2016-06-17) + * \* `\ddTools::verifyRenamedParams` обновлён до 1.1.1: * \+ Добавлена возможность использования нескольких старых имён в параметре `$compliance`. * \* Небольной рефакторинг, стиль кода и описание. ## Версия 0.15.3 (2016-01-12) + * \* `\ddTools::sendMail`: Теперь заголовки и контент письма передаются в `mail` раздельно. Это исправляет ситуацию, когда в некоторых почтовиках не было видно контента писем. ## Версия 0.15.2 (2016-01-11) + * \* `\ddTools::updateDocument`: Метод теперь использует функцию `mysqli_info`, если `$modx->db->conn` является экземпляром класса `mysqli`, иначе используется `mysql_info`. ## Версия 0.15.1 (2015-12-29) + * \* Провека на существование метода `getVersionData` перенесена под условие `isset` (`$modx`) * \* `\ddTools::getTemplateVarOutput`: Проверка на существование `$row['id']` теперь делается через `isset`. ## Версия 0.15 (2015-12-25) + * \+ `\ddTools::copyDir`: Новый метод. Рекурсивно копирует содержимое папки в новое место. * \* `\ddTools::updateDocument`: Теперь в методе используется `mysqli_info` вместо `mysql_info`. * \* `\ddTools::getDocuments`: Наличие или отсутствие прав у текущего пользователя на чтение документов, которые запрашиваются, теперь полностью игнорируется. Это было сделано, потому что этот метод низкоуровневый, т. е. подразумевается, что какой-то более высокоуровненвый компонент, ответственный за доступ к ресурсам, должен разрешить или запретить получение документов, если требуется. @@ -430,14 +498,17 @@ ## Версия 0.14.3 (2015-12-13) + * \+ Добавлена `isset`-проверка для глобальной переменной, чтобы не вылетали ошибки при использовании метода `$modx->getFullTableName`. ## Версия 0.14.2 (2015-11-05) + * \+ Переменная `$modx` объявлена глобальной, чтобы избежать ошибки, возникающей при автозагрузке ddTools из Composer. ## Версия 0.14.1 (2015-11-03) + * \* Следующие методы были обновлены. Теперь чтобы получить документы/поля/TV вне зависимости от публикации и удаления документа, нужно передать строку `'all'` в параметры `$published` и `$deleted` соответственно, а не `false`, как это было раньше. Старое значение `false` тоже поддерживается, но при этом пишется предупреждение в лог MODX, и эта поддержка будет убрана в будущем. * \* `\ddTools::getDocuments`. * \* `\ddTools::getDocument`. @@ -450,32 +521,39 @@ ## Версия 0.14 (2015-10-05) + * \* Полностью изменена структура репозитория, чтобы было удобнее устанавливать через Composer. ## Версия 0.13.3 (2015-09-17) + * \* `\ddTools::createDocument`: теперь адрес нового документа собирается правильно, в зависимости от `path` родителя и его `alias`’а, либо `id`, если `alias`’а нет. ## Версия 0.13.2 (2015-09-07) + * \* `\ddTools::createDocument`: Теперь массивы из конфига MODX `documentMap` и `aliasListing` дополняются данными о созданном документе. ## Версия 0.13.1 (2015-08-17) + * \* `\ddTools::sendMail`: Метод был обновлён, чтобы избежать ошибок в PHP 5.4−5.6 из-за валидации заголовков: * \* Все двойные `\r\n` и одинарные `\r\n` были заменены на один PHP_EOL. * \* К содержимому письма теперь применяется функция `trim`, чтобы убрать `PHP_EOL`'ы в начале и конце контента. ## Версия 0.13 (2014-07-13) + * \+ `\ddTools::sendMail`: Новый метод. Отправляет e-mail. ## Версия 0.12 (2014-05-23) + * \+ `\ddTools::verifyRenamedParams`: Новый метод. Проверяет наличие устаревших названий параметров и записывает предупреждение в журнал событий MODX. Возвращает ассоциативный массив, где ключ — правильное имя параметра, а значение — значение. Используйте функцию `extract`, чтобы извлечь результат в переменные. ## Версия 0.11.1 (2014-04-11) + * \* Следующие методы обновлены в соответствии с MODX 1.0.13: * \* `\ddTools::getDocuments`. * \* `\ddTools::getTemplateVars`. @@ -485,43 +563,51 @@ ## Версия 0.11 (2014-02-11) + * \+ `\ddTools::ddTools::sort2dArray`: Новый метод. Сортирует двумерный массив по нескольким колонкам (как в SQL) по методу Хоара. Сортировка устойчивая. * \* Небольшие изменения для совместимости со старыми версиями MODX. * \* `\ddTools::unfoldArray`: Исправлена ошибка, метод не был статичным. ## Версия 0.10 (2013-10-17) + * \+ `\ddTools::unfoldArray`: Новый метод. Преобразует многомерный массив в одномерный, при этом ключи результирующего массива сливаются через `'.'` (см. описание и примеры). * \* `\ddTools::$documentFields`: Поле `alias_visible` добавляется в массив только если версия MODX > 1.0.11 для совместимости с более ранними версиями. * \* Массив `ddTools:$tables` с элементами для наглядности объявляется непосредственно в классе ## Версия 0.9.2 (2013-10-17) + * \* Внимание! Требуется MODX >= 1.0.12. * \* `\ddTools::$documentFields`: В массив добавлено поле `alias_visible` (MODX 1.0.12). ## Версия 0.9.1 (2013-10-10) + * \* `\ddTools::parseFileNameВерсия` обновлён до 1.1: * \* Помимо имени и версии файла возвращается ещё и его расширение. ## Версия 0.9 (2013-09-03) + * \+ `\ddTools::getDocumentIdByUrl`: Новый метод. Метод получает ID документа по его адресу (URL). ## Версия 0.8.1 (2013-07-11) + * \* `\ddTools::explodeAssoc` обновлён до 1.1.1: * \* Добавлена обработка пустой строки на входе (в этом случае возвращается пустой массив). ## Версия 0.8 (2013-07-06) + * \+ `\ddTools::parseFileNameВерсия`: Новый метод. Разбирает строку файла, получая из неё его имя версию. * \* `\ddTools::regEmptyClientScript` обновлён до 1.0.1: * \* Исправление: Перед записью пустых значений в `$modx->sjscripts` и `$modx->jscripts` добавлена проверка на используемость текущей версии. ## Версия 0.7 (2013-05-15) + * \+ `\ddTools::getDocumentChildren`: Новый метод, аналогичный стандартному. Получает необходимые дочерние документы (значения их полей). Отличие от стандартного в возможности получать результаты вне зависимости от публикации и удалённости документа. * \+ `\ddTools::getDocumentChildrenTVarOutput` обновлён до 1.1: * \+ Параметр `published` теперь тоже может принимать значение `false`, при котором будут получены все документы вне зависимости от их публикации. @@ -529,6 +615,7 @@ ## Версия 0.6.1 (2013-04-26) + * \* Исправление, следующие методы не были статичными: * \* `\ddTools::getDocuments`. * \* `\ddTools::getDocument`. @@ -537,6 +624,7 @@ ## Версия 0.6 (2013-03-26) + * \+ Добавлено несколько аналогичных стандартным методов по работе с документами, основное отличие которых в возможности возвращать результаты вне зависимости от публикации документа: * \+ `\ddTools::getDocuments`. Получает необходимые документы (поля документов). * \+ `\ddTools::getDocument`. Получает данные о необходимом документе (поля документа). @@ -546,16 +634,19 @@ ## Версия 0.5 (2013-03-12) + * \+ `\ddTools::removeDir`: Новый метод. Удаляет папку со всеми вложенными файлами и папками (рекурсивно). * \+ `\ddTools::regEmptyClientScript`: Новый метод. Добавляет необходимый файл JavaScript в нужный внутренний список MODX в соответствии с его именем и версией. Предназначен для регистрации скриптов, которые уже были подключены в ручную. ## Версия 0.4.1 (2013-02-28) + * \* `\ddTools::explodeAssoc` обновлён до 1.1: * \* Добавлена проверка на пустоту при разбивке между ключом и значением (если значения нет, вставляется пустая строка). ## Версия 0.4 (2012-10-26) + * \* Внимание! Нарушена обратная совместимость. * \* `\ddTools::updateDocument` обновлён до 1.2: * \+ Парамтер `$id` может быть массивом или числом. @@ -566,10 +657,12 @@ ## Версия 0.3 (2012-04-11) + * \+ `\ddTools::getDocumentChildrenTVarOutput`: Новый метод, позволяющий получать необходимые дочерние документы. ## Версия 0.2 (2012-03-21) + * \* Внимание! Нарушена обратная совместимость. * \+ `\ddTools::$documentFields`: Новое статическое поле, содержащее массив имён полей документа. * \+ `\ddTools::$tables`: Новое статическое поле, содержащее полные имена некоторых таблиц. @@ -588,6 +681,7 @@ ## Версия 0.1 (2012-02-03) + * \+ Первый релиз. diff --git a/README.md b/README.md index af0d241..6975a6b 100644 --- a/README.md +++ b/README.md @@ -34,14 +34,14 @@ Just run the following PHP code in your sources or [Console](https://github.com/ ```php //Include (MODX)EvolutionCMS.libraries.ddInstaller require_once( - $modx->getConfig('base_path') . - 'assets/libs/ddInstaller/require.php' + $modx->getConfig('base_path') + . 'assets/libs/ddInstaller/require.php' ); //Update (MODX)EvolutionCMS.libraries.ddTools \DDInstaller::install([ 'url' => 'https://github.com/DivanDesign/EvolutionCMS.libraries.ddTools', - 'type' => 'library' + 'type' => 'library', ]); ``` @@ -728,10 +728,10 @@ Gets an array of required collection items. * Thus, ``` ' - "gender" == "female" || - "gender" == "male" && - "firstName" != "Bill" && - "lastName" + "gender" == "female" + || "gender" == "male" + && "firstName" != "Bill" + && "lastName" ' ``` returns: @@ -743,19 +743,19 @@ Gets an array of required collection items. * Quoted property names and values are optional, this is valid too: ``` ' - gender == female || - gender == male && - firstName != Bill && - lastName + gender == female + || gender == male + && firstName != Bill + && lastName ' ``` * Single quotes are also supported as double quotes: ``` " - gender == 'a' || - gender == 'b' && - firstName != 'Bill' && - lastName + gender == 'a' + || gender == 'b' + && firstName != 'Bill' + && lastName " ``` * Spaces, tabs and line breaks are optional, this is valid too: `gender==female||gender==male&&firstName!=Bill&&lastName`. @@ -1309,7 +1309,7 @@ $url = 'https://example.com/some/page?q=42#hash'; \ddTools::convertUrlToAbsolute([ 'url' => $url, //The parameter is optional and is used here just for clarity. By default it will be equal to domain of your site. - 'host' => 'example.com' + 'host' => 'example.com', ]); ``` @@ -1329,8 +1329,8 @@ And we want to save backward compatibility, the snippet must work with the old n ```php //Include (MODX)EvolutionCMS.libraries.ddTools require_once( - $modx->getConfig('base_path') . - 'assets/libs/ddTools/modx.ddtools.class.php' + $modx->getConfig('base_path') + . 'assets/libs/ddTools/modx.ddtools.class.php' ); //Backward compatibility @@ -1340,8 +1340,8 @@ extract(\ddTools::verifyRenamedParams([ 'compliance' => [ //The new name => The old name 'docField' => 'getEmail', - 'docId' => 'getId' - ] + 'docId' => 'getId', + ], ])); ``` @@ -1357,15 +1357,15 @@ extract(\ddTools::verifyRenamedParams([ //The new name => The old names 'email_docField' => [ 'docField', - 'getEmail' + 'getEmail', ], 'email_docId' => [ 'docId', - 'getId' - ] + 'getId', + ], ], //Also you can prevent writing to the CMS event log if you want - 'writeToLog' => false + 'writeToLog' => false, ])); ``` @@ -1389,8 +1389,8 @@ extract(\ddTools::verifyRenamedParams([ 'text' => '

Question your loyalty to your country and government and strive for a more just and peaceful society.

', 'authorFirstName' => 'Leo', 'authorLastName' => 'Tolstoy', - 'date' => '1904' - ] + 'date' => '1904', + ], ]); ``` @@ -1421,8 +1421,8 @@ Returns: 'firstName' => 'Leo', 'lastName' => 'Tolstoy', ], - 'date' => '1904' - ] + 'date' => '1904', + ], ], //For nested data you can use placeholders like '[+meta.date+]' for getting a property //Or like '[+meta+]' to get whole object as JSON @@ -1432,7 +1432,7 @@ Returns: [+text+]

[+meta.author.firstName+] [+meta.author.lastName+], [+meta.date+].

- ' + ', ]); ``` @@ -1466,13 +1466,13 @@ Just call this method and don't care about it. "pagetitle": "Test title", "published": "0" }', - 'type' => 'objectArray' + 'type' => 'objectArray', ]); //Or Query string \DDTools\Tools\Objects::convertType([ 'object' => 'pagetitle=Test title&published=0', - 'type' => 'objectArray' + 'type' => 'objectArray', ]); ``` @@ -1481,7 +1481,7 @@ Both calls return: ```php [ 'pagetitle' => 'Test title', - 'published' => '0' + 'published' => '0', ]; ``` @@ -1491,7 +1491,7 @@ Both calls return: ```php \DDTools\Tools\Objects::convertType([ 'object' => 'firstName=Hans&lastName=Zimmer', - 'type' => 'stringJsonAuto' + 'type' => 'stringJsonAuto', ]); ``` @@ -1513,7 +1513,7 @@ Returns: "firstName": "Ramin", "lastName": "Djawadi" }', - 'type' => 'stringJsonArray' + 'type' => 'stringJsonArray', ]); ``` @@ -1541,7 +1541,7 @@ Returns: A simple syntax and easy to read. ''' }", - 'type' => 'objectStdClass' + 'type' => 'objectStdClass', ]); ``` @@ -1551,8 +1551,9 @@ Returns: stdClass::__set_state(array( 'keys' => 'and values can be specified without quotes,', 'multilineValues' => 'Write multiline strings with proper whitespace handling. -Starts and ends with triple quotes. -A simple syntax and easy to read.', + Starts and ends with triple quotes. + A simple syntax and easy to read.' + , )) ``` @@ -1576,7 +1577,7 @@ A simple syntax and easy to read.', 'Oleg Valinsky', ], ], - 'type' => 'stringHtmlAttrs' + 'type' => 'stringHtmlAttrs', ]); ``` @@ -1593,24 +1594,26 @@ data-name='KINO' data-is-active='1' data-members='["Viktor Tsoi","Yuri Kasparyan ##### Merge two objects, modifying the first ```php -var_export(\DDTools\Tools\Objects::extend([ - 'objects' => [ - (object) [ - 'cat' => 'mew', - 'dog' => (object) [ - 'name' => 'Floyd', - 'weight' => 6 +var_export( + \DDTools\Tools\Objects::extend([ + 'objects' => [ + (object) [ + 'cat' => 'mew', + 'dog' => (object) [ + 'name' => 'Floyd', + 'weight' => 6, + ], + 'rabbit' => 42, ], - 'rabbit' => 42 - ], - (object) [ - 'dog' => (object) [ - 'weight' => 10 + (object) [ + 'dog' => (object) [ + 'weight' => 10, + ], + 'bird' => 0, ], - 'bird' => 0 - ] - ] -])); + ], + ]) +); ``` Returns: @@ -1631,24 +1634,26 @@ stdClass::__set_state(array( ##### Also you can extend arrays ```php -var_export(\DDTools\Tools\Objects::extend([ - 'objects' => [ - [ - 'cat' => 'mew', - 'dog' => [ - 'name' => 'Floyd', - 'weight' => 6 +var_export( + \DDTools\Tools\Objects::extend([ + 'objects' => [ + [ + 'cat' => 'mew', + 'dog' => [ + 'name' => 'Floyd', + 'weight' => 6, + ], + 'rabbit' => 42, ], - 'rabbit' => 42 - ], - [ - 'dog' => (object) [ - 'weight' => 10 + [ + 'dog' => (object) [ + 'weight' => 10, + ], + 'bird' => 0, ], - 'bird' => 0 - ] - ] -])); + ], + ]) +); ``` Returns: @@ -1669,22 +1674,24 @@ array( ##### Moreover, objects can extend arrays and vice versa ```php -var_export(\DDTools\Tools\Objects::extend([ - 'objects' => [ - [ - 'name' => 'jokes', - 'countries' => (object) [ - 'usa' => 'democracy', - 'china' => 'chinese democracy' +var_export( + \DDTools\Tools\Objects::extend([ + 'objects' => [ + [ + 'name' => 'jokes', + 'countries' => (object) [ + 'usa' => 'democracy', + 'china' => 'chinese democracy', + ], + ], + (object) [ + 'countries' => [ + 'china' => 'democracy too', + ], ], ], - (object) [ - 'countries' => [ - 'china' => 'democracy too' - ] - ] - ] -])); + ]) +); ``` Returns: @@ -1707,19 +1714,21 @@ array( By default, empty field values (e. g. `''`) are treated as other values and will replace non-empty ones. ```php -var_export(\DDTools\Tools\Objects::extend([ - 'objects' => [ - (object) [ - 'firstName' => 'John', - 'lastName' => 'Tesla', - 'discipline' => 'Electrical engineering' +var_export( + \DDTools\Tools\Objects::extend([ + 'objects' => [ + (object) [ + 'firstName' => 'John', + 'lastName' => 'Tesla', + 'discipline' => 'Electrical engineering', + ], + (object) [ + 'firstName' => 'Nikola', + 'lastName' => '', + ], ], - (object) [ - 'firstName' => 'Nikola', - 'lastName' => '' - ] - ] -])); + ]) +); ``` Returns: @@ -1728,7 +1737,7 @@ Returns: stdClass::__set_state(array( 'firstName' => 'Nikola', 'lastName' => '', - 'discipline' => 'Electrical engineering' + 'discipline' => 'Electrical engineering', )) ``` @@ -1737,20 +1746,22 @@ Empty `lastName` from the second object replaced non-empty `lastName` from the f If you want to ignore empty values, just use `$params->overwriteWithEmpty` == `false`: ```php -var_export(\DDTools\Tools\Objects::extend([ - 'objects' => [ - (object) [ - 'firstName' => 'John', - 'lastName' => 'Tesla', - 'discipline' => 'Electrical engineering' +var_export( + \DDTools\Tools\Objects::extend([ + 'objects' => [ + (object) [ + 'firstName' => 'John', + 'lastName' => 'Tesla', + 'discipline' => 'Electrical engineering', + ], + (object) [ + 'firstName' => 'Nikola', + 'lastName' => '', + ], ], - (object) [ - 'firstName' => 'Nikola', - 'lastName' => '' - ] - ], - 'overwriteWithEmpty' => false -])); + 'overwriteWithEmpty' => false, + ]) +); ``` Returns: @@ -1759,7 +1770,7 @@ Returns: stdClass::__set_state(array( 'firstName' => 'Nikola', 'lastName' => 'Tesla', - 'discipline' => 'Electrical engineering' + 'discipline' => 'Electrical engineering', )) ``` @@ -1770,17 +1781,19 @@ stdClass::__set_state(array( ##### Unfold an object ```php -var_export(\DDTools\Tools\Objects::unfold([ - 'object' => (object) [ - 'name' => 'Elon Musk', - 'address' => (object) [ - 'line1' => '3500 Deer Creek Road', - 'city' => 'Palo Alto', - 'state' => 'California', - 'country' => 'United States' - ] - ] -])); +var_export( + \DDTools\Tools\Objects::unfold([ + 'object' => (object) [ + 'name' => 'Elon Musk', + 'address' => (object) [ + 'line1' => '3500 Deer Creek Road', + 'city' => 'Palo Alto', + 'state' => 'California', + 'country' => 'United States', + ], + ], + ]) +); ``` Returns: @@ -1791,7 +1804,7 @@ stdClass::__set_state(array ( 'address.line1' => '3500 Deer Creek Road', 'address.city' => 'Palo Alto', 'address.state' => 'California', - 'address.country' => 'United States' + 'address.country' => 'United States', )) ``` @@ -1799,19 +1812,21 @@ stdClass::__set_state(array ( ##### Unfold an array ```php -var_export(\DDTools\Tools\Objects::unfold([ - 'object' => [ - 'a' => 'a val', - 'b' => [ - 'b1' => 'b1 val', - 'b2' => [ - 'b21' => 'b21 val', - 'b22' => 'b22 val' - ] +var_export( + \DDTools\Tools\Objects::unfold([ + 'object' => [ + 'a' => 'a val', + 'b' => [ + 'b1' => 'b1 val', + 'b2' => [ + 'b21' => 'b21 val', + 'b22' => 'b22 val', + ], + ], + 'c' => 'c val', ], - 'c' => 'c val' - ] -])); + ]) +); ``` Returns: @@ -1822,7 +1837,7 @@ array ( 'b.b1' => 'b1 val', 'b.b2.b21' => 'b21 val', 'b.b2.b22' => 'b22 val', - 'c' => 'c val' + 'c' => 'c val', ) ``` @@ -1830,16 +1845,18 @@ array ( ##### Use custom key separator ```php -var_export(\DDTools\Tools\Objects::unfold([ - 'object' => [ - 'name' => 'Elon Musk', - 'parents' => [ - 'mother' => 'Maye Musk', - 'father' => 'Errol Musk' - ] - ], - 'keySeparator' => '_' -])); +var_export( + \DDTools\Tools\Objects::unfold([ + 'object' => [ + 'name' => 'Elon Musk', + 'parents' => [ + 'mother' => 'Maye Musk', + 'father' => 'Errol Musk', + ], + ], + 'keySeparator' => '_', + ]) +); ``` Returns: @@ -1848,7 +1865,7 @@ Returns: stdClass::__set_state(array ( 'name' => 'Elon Musk', 'parents_mother' => 'Maye Musk', - 'parents_father' => 'Errol Musk' + 'parents_father' => 'Errol Musk', )) ``` @@ -1862,14 +1879,14 @@ $data = [ 'bin1' => [ 'plastic' => 'plastic bottles', 'paper' => 'newspapers', - 'glass' => 'glass bottles' + 'glass' => 'glass bottles', ], //Object 'bin2' => (object) [ 'organic' => 'food waste', 'paper' => 'cardboard boxes', - 'metal' => 'aluminum cans' - ] + 'metal' => 'aluminum cans', + ], ]; ``` @@ -1930,25 +1947,29 @@ Checks if the object, class or array has a property / element using the same syn You can pass an object: ```php -var_export(\DDTools\Tools\Objects::isPropExists([ - 'object' => (object) [ - 'firstName' => 'John', - 'lastName' => 'Lennon' - ], - 'propName' => 'firstName' -])); +var_export( + \DDTools\Tools\Objects::isPropExists([ + 'object' => (object) [ + 'firstName' => 'John', + 'lastName' => 'Lennon', + ], + 'propName' => 'firstName', + ]) +); ``` Or an array: ```php -var_export(\DDTools\Tools\Objects::isPropExists([ - 'object' => [ - 'firstName' => 'Paul', - 'lastName' => 'McCartney' - ], - 'propName' => 'firstName' -])); +var_export( + \DDTools\Tools\Objects::isPropExists([ + 'object' => [ + 'firstName' => 'Paul', + 'lastName' => 'McCartney', + ], + 'propName' => 'firstName', + ]) +); ``` Both calls return `true`. @@ -1962,25 +1983,29 @@ Both calls return `true`. You can pass an object: ```php -var_export(\DDTools\Tools\Objects::getPropValue([ - 'object' => (object) [ - 'name' => 'Floyd', - 'weight' => 7 - ], - 'propName' => 'name' -])); +var_export( + \DDTools\Tools\Objects::getPropValue([ + 'object' => (object) [ + 'name' => 'Floyd', + 'weight' => 7, + ], + 'propName' => 'name', + ]) +); ``` Or an array: ```php -var_export(\DDTools\Tools\Objects::getPropValue([ - 'object' => [ - 'name' => 'Floyd', - 'weight' => 7 - ], - 'propName' => 'name' -])); +var_export( + \DDTools\Tools\Objects::getPropValue([ + 'object' => [ + 'name' => 'Floyd', + 'weight' => 7, + ], + 'propName' => 'name', + ]) +); ``` Both calls return `'Floyd'`. @@ -1998,26 +2023,26 @@ $sourceObject = (object) [ //Let the third level be an associative array [ 'name' => 'Syd Barrett', - 'role' => 'lead and rhythm guitars, vocals' + 'role' => 'lead and rhythm guitars, vocals', ], [ 'name' => 'David Gilmour', - 'role' => 'lead and rhythm guitars, vocals, bass, keyboards, synthesisers' + 'role' => 'lead and rhythm guitars, vocals, bass, keyboards, synthesisers', ], //Let Roger be a little bit special ;) (object) [ 'name' => 'Roger Waters', - 'role' => 'bass, vocals, rhythm guitar, synthesisers' + 'role' => 'bass, vocals, rhythm guitar, synthesisers', ], [ 'name' => 'Richard Wright', - 'role' => 'keyboards, piano, organ, synthesisers, vocals' + 'role' => 'keyboards, piano, organ, synthesisers, vocals', ], [ 'name' => 'Nick Mason', - 'role' => 'drums, percussion' - ] - ] + 'role' => 'drums, percussion', + ], + ], ]; ``` @@ -2027,10 +2052,12 @@ $sourceObject = (object) [ There's nothing special, just look at this example for the full picture. ```php -var_export(\DDTools\Tools\Objects::getPropValue([ - 'object' => $sourceObject, - 'propName' => 'PinkFloyd' -])); +var_export( + \DDTools\Tools\Objects::getPropValue([ + 'object' => $sourceObject, + 'propName' => 'PinkFloyd', + ]) +); ``` Returns: @@ -2066,10 +2093,12 @@ array ( Let's make it a little more interesting: let's get the 4th element of the second-level indexed array. ```php -var_export(\DDTools\Tools\Objects::getPropValue([ - 'object' => $sourceObject, - 'propName' => 'PinkFloyd.4' -])); +var_export( + \DDTools\Tools\Objects::getPropValue([ + 'object' => $sourceObject, + 'propName' => 'PinkFloyd.4', + ]) +); ``` Returns: @@ -2090,10 +2119,12 @@ No matter what type of element is used in any nesting level, the method will wor So let's get Roger's name. As you remember, he is stdClass as opposed to the other members who are associative arrays. ```php -var_export(\DDTools\Tools\Objects::getPropValue([ - 'object' => $sourceObject, - 'propName' => 'PinkFloyd.2.name' -])); +var_export( + \DDTools\Tools\Objects::getPropValue([ + 'object' => $sourceObject, + 'propName' => 'PinkFloyd.2.name', + ]) +); ``` Returns: @@ -2106,13 +2137,15 @@ Returns: ###### Of course, it works fine with single-level objects that contain `'.'` in their property names ```php -var_export(\DDTools\Tools\Objects::getPropValue([ - 'object' => [ - '1973.03.01' => 'The Dark Side of the Moon', - '1975.09.12' => 'Wish You Were Here' - ], - 'propName' => '1975.09.12' -])); +var_export( + \DDTools\Tools\Objects::getPropValue([ + 'object' => [ + '1973.03.01' => 'The Dark Side of the Moon', + '1975.09.12' => 'Wish You Were Here', + ], + 'propName' => '1975.09.12', + ]) +); ``` Returns: @@ -2135,27 +2168,27 @@ $collection = new \DDTools\ObjectCollection([ 'isHuman' => 1, 'gender' => 'female', 'nobelPeacePrize' => 1, - 'religion' => 'Catholicism' + 'religion' => 'Catholicism', ], [ 'name' => 'Mahatma Gandhi', 'isHuman' => 1, 'gender' => 'male', - 'nobelPeacePrize' => 0 + 'nobelPeacePrize' => 0, ], [ 'name' => 'Tenzin Gyatso', 'isHuman' => 1, 'gender' => 'male', 'nobelPeacePrize' => 1, - 'religion' => 'Tibetan Buddhism' + 'religion' => 'Tibetan Buddhism', ], [ 'name' => 'ICAN', 'isHuman' => 0, - 'nobelPeacePrize' => 1 - ] - ] + 'nobelPeacePrize' => 1, + ], + ], ]); ``` @@ -2205,7 +2238,7 @@ $collection->setItems([ ```php $collection->getItems([ - 'filter' => 'religion' + 'filter' => 'religion', ]); ``` @@ -2218,15 +2251,15 @@ array( 'isHuman' => 1, 'gender' => 'female', 'nobelPeacePrize' => 1, - 'religion' => 'Catholicism' + 'religion' => 'Catholicism', ), 1 => array( 'name' => 'Tenzin Gyatso', 'isHuman' => 1, 'gender' => 'male', 'nobelPeacePrize' => 1, - 'religion' => 'Tibetan Buddhism' - ) + 'religion' => 'Tibetan Buddhism', + ), ) ``` @@ -2235,7 +2268,7 @@ array( ```php $collection->getItems([ - 'filter' => 'gender==male' + 'filter' => 'gender==male', ]); ``` @@ -2247,15 +2280,15 @@ array( 'name' => 'Mahatma Gandhi', 'isHuman' => 1, 'gender' => 'male', - 'nobelPeacePrize' => 0 + 'nobelPeacePrize' => 0, ), 1 => array( 'name' => 'Tenzin Gyatso', 'isHuman' => 1, 'gender' => 'male', 'nobelPeacePrize' => 1, - 'religion' => 'Tibetan Buddhism' - ) + 'religion' => 'Tibetan Buddhism', + ), ) ``` @@ -2266,8 +2299,8 @@ array( $collection->getItems([ //Spaces, tabs and line breaks are also allowed and do not matter 'filter' => ' - gender == female || - nobelPeacePrize == 1 && isHuman == 0 + gender == female + || nobelPeacePrize == 1 && isHuman == 0 ' ]); ``` @@ -2282,13 +2315,13 @@ array( 'isHuman' => 1, 'gender' => 'female', 'nobelPeacePrize' => 1, - 'religion' => 'Catholicism' + 'religion' => 'Catholicism', ), //nobelPeacePrize == 1 && isHuman == 0 1 => array( 'name' => 'ICAN', 'isHuman' => 0, - 'nobelPeacePrize' => 1 + 'nobelPeacePrize' => 1, ), ) ``` @@ -2298,7 +2331,7 @@ array( ```php $collection->getItems([ - 'propAsResultKey' => 'name' + 'propAsResultKey' => 'name', ]); ``` @@ -2311,26 +2344,26 @@ array( 'isHuman' => 1, 'gender' => 'female', 'nobelPeacePrize' => 1, - 'religion' => 'Catholicism' + 'religion' => 'Catholicism', ), 'Mahatma Gandhi' => array( 'name' => 'Mahatma Gandhi', 'isHuman' => 1, 'gender' => 'male', - 'nobelPeacePrize' => 0 + 'nobelPeacePrize' => 0, ), 'Tenzin Gyatso' => array( 'name' => 'Tenzin Gyatso', 'isHuman' => 1, 'gender' => 'male', 'nobelPeacePrize' => 1, - 'religion' => 'Tibetan Buddhism' + 'religion' => 'Tibetan Buddhism', ), 'ICAN' => array( 'name' => 'ICAN', 'isHuman' => 0, - 'nobelPeacePrize' => 1 - ) + 'nobelPeacePrize' => 1, + ), ) ``` @@ -2340,7 +2373,7 @@ array( ```php $collection->getItems([ 'propAsResultKey' => 'name', - 'propAsResultValue' => 'isHuman' + 'propAsResultValue' => 'isHuman', ]); ``` @@ -2351,7 +2384,7 @@ array( 'Mary Teresa' => 1, 'Mahatma Gandhi' => 1, 'Tenzin Gyatso' => 1, - 'ICAN' => 0 + 'ICAN' => 0, ) ``` @@ -2360,7 +2393,7 @@ array( ```php $collection->getOneItem([ - 'filter' => 'name == Mahatma Gandhi' + 'filter' => 'name == Mahatma Gandhi', ]); ``` @@ -2371,7 +2404,7 @@ array( 'name' => 'Mahatma Gandhi', 'isHuman' => 1, 'gender' => 'male', - 'nobelPeacePrize' => 0 + 'nobelPeacePrize' => 0, ) ``` @@ -2382,10 +2415,10 @@ array( ```php $collection->getOneItem([ 'filter' => 'name == European Union', - notFoundResult' => [ + 'notFoundResult' => [ 'name' => 'Default item', - 'nobelPeacePrize' => 0 - ] + 'nobelPeacePrize' => 0, + ], ]); ``` @@ -2394,7 +2427,7 @@ Returns: ```php array( 'name' => 'Default item', - 'nobelPeacePrize' => 0 + 'nobelPeacePrize' => 0, ) ``` @@ -2404,7 +2437,7 @@ array( ```php $collection->convertItemsType([ 'filter' => 'gender==male', - 'itemType' => 'objectStdClass' + 'itemType' => 'objectStdClass', ]); $collection->getItems(); @@ -2419,26 +2452,26 @@ array( 'isHuman' => 1, 'gender' => 'female', 'nobelPeacePrize' => 1, - 'religion' => 'Catholicism' + 'religion' => 'Catholicism', ), 1 => stdClass::__set_state(array( 'name' => 'Mahatma Gandhi', 'isHuman' => 1, 'gender' => 'male', - 'nobelPeacePrize' => 0 + 'nobelPeacePrize' => 0, )), 2 => stdClass::__set_state(array( 'name' => 'Tenzin Gyatso', 'isHuman' => 1, 'gender' => 'male', 'nobelPeacePrize' => 1, - 'religion' => 'Tibetan Buddhism' + 'religion' => 'Tibetan Buddhism', )), 3 => array( 'name' => 'ICAN', 'isHuman' => 0, - 'nobelPeacePrize' => 1 - ) + 'nobelPeacePrize' => 1, + ), ) ``` @@ -2450,12 +2483,12 @@ $collection->updateItems([ 'filter' => 'name==Mahatma Gandhi', 'data' => [ 'nobelPeacePrize' => 1, - 'birthday' => '2 October 1869' + 'birthday' => '2 October 1869', ] ]); $collection->getItems( - 'filter' => 'name==Mahatma Gandhi' + 'filter' => 'name==Mahatma Gandhi', ); ``` @@ -2471,7 +2504,7 @@ array( //Given property values have overwritten the existing ones 'nobelPeacePrize' => 1, //Non-existing properties have been created - 'birthday' => '2 October 1869' + 'birthday' => '2 October 1869', )) ) ``` @@ -2482,7 +2515,7 @@ array( ```php $collection->updateItems([ 'filter' => 'isHuman==1', - 'limit' => 2 + 'limit' => 2, ]); $collection->getItems(); @@ -2498,13 +2531,13 @@ array( 'isHuman' => 1, 'gender' => 'male', 'nobelPeacePrize' => 1, - 'religion' => 'Tibetan Buddhism' + 'religion' => 'Tibetan Buddhism', )), 1 => array( 'name' => 'ICAN', 'isHuman' => 0, - 'nobelPeacePrize' => 1 - ) + 'nobelPeacePrize' => 1, + ), ) ``` From fa2398e5180e90fa0733631f22b8a79a1107bc78 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Fri, 2 Aug 2024 18:05:40 +0400 Subject: [PATCH 10/12] =?UTF-8?q?+=20Composer.json=20=E2=86=92=20`support`?= =?UTF-8?q?.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- composer.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/composer.json b/composer.json index a57299f..6955cf6 100644 --- a/composer.json +++ b/composer.json @@ -10,6 +10,9 @@ "ddtools" ], "homepage": "https://code.divandesign.ru/modx/ddtools", + "support": { + "chat": "https://t.me/dd_code" + }, "authors": [ { "name": "Ilyas Ronef", From 0d0f34885968becaf125daa71e1be08e1f9ea066 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Fri, 2 Aug 2024 18:08:11 +0400 Subject: [PATCH 11/12] * Minor changes. --- composer.json | 3 +-- modx.ddtools.class.php | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index 6955cf6..f9ab475 100644 --- a/composer.json +++ b/composer.json @@ -16,8 +16,7 @@ "authors": [ { "name": "Ilyas Ronef", - "email": "ilyas@DivanDesign.ru", - "homepage": "https://ronef.ru", + "homepage": "https://ronef.me", "role": "Owner" }, { diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index fd47677..de1443f 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -5,7 +5,7 @@ * * @see README.md * - * @copyright 2012–2024 Ronef {@link https://Ronef.ru } + * @copyright 2012–2024 https://Ronef.me */ global $modx; From ea722e8df1224c3aebfbed07f89e596fbf0e14cb Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Fri, 2 Aug 2024 18:23:00 +0400 Subject: [PATCH 12/12] Prerelease --- CHANGELOG.md | 7 +++++++ CHANGELOG_ru.md | 7 +++++++ composer.json | 2 +- modx.ddtools.class.php | 2 +- 4 files changed, 16 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c937bf1..3b470dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ # (MODX)EvolutionCMS.libraries.ddTools changelog +## Version 0.63 (2024-08-02) + +* \+ `\DDTools\Tools\Cache`: The new class. Allows you to cache some data (e. g. a snippet result) to a file in the `assets/cache/ddCache` folder (see README). +* \* `\DDTools\Tools\Objects`: The class has been renamed from `\DDTools\ObjectTools` (with backward compatibility). +* \* `\DDTools\Tools\Files`: The class has been renamed from `\DDTools\FilesTools` (with backward compatibility). + + ## Version 0.62.1 (2024-06-17) * \* `\ddTools::parseText` → Parameters → `$params->isCompletelyParsingEnabled`: Broken support for deprecated name `$params->mergeAll` has been fixed. diff --git a/CHANGELOG_ru.md b/CHANGELOG_ru.md index 0420c10..3c9e449 100644 --- a/CHANGELOG_ru.md +++ b/CHANGELOG_ru.md @@ -1,6 +1,13 @@ # (MODX)EvolutionCMS.libraries.ddTools changelog +## Версия 0.63 (2024-08-02) + +* \+ `\DDTools\Tools\Cache`: Новый класс. Позволяет кэшировать какие-то данные (например, результаты сниппетов) в файл в папке `assets/cache/ddCache` (см. README). +* \* `\DDTools\Tools\Objects`: Класс переименован из `\DDTools\ObjectTools` (с обратной совместимостью). +* \* `\DDTools\Tools\Files`: Класс переименован из `\DDTools\FilesTools` (с обратной совместимостью). + + ## Версия 0.62.1 (2024-06-17) * \* `\ddTools::parseText` → Parameters → `$params->isCompletelyParsingEnabled`: Неработающая поддержка устаревшего названия `$params->mergeAll` исправлена. diff --git a/composer.json b/composer.json index f9ab475..b47e654 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "dd/evolutioncms-libraries-ddtools", "type": "modxevo-library-ddtools", - "version": "0.62.1", + "version": "0.63.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 de1443f..f4043ef 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -1,7 +1,7 @@