From c4c8da944f51c0e7de30a284d4a011fc7e681818 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Thu, 31 Oct 2019 17:11:54 +0300 Subject: [PATCH 01/10] * Minor changes. --- ddIf_snippet.php | 96 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 76 insertions(+), 20 deletions(-) diff --git a/ddIf_snippet.php b/ddIf_snippet.php index 56cd841..6201d8f 100644 --- a/ddIf_snippet.php +++ b/ddIf_snippet.php @@ -22,18 +22,19 @@ * @copyright 2012–2018 DivanDesign {@link http://www.DivanDesign.biz } */ -$result = ''; +//Include (MODX)EvolutionCMS.libraries.ddTools +require_once($modx->getConfig('base_path') . 'assets/libs/ddTools/modx.ddtools.class.php'); -require_once $modx->getConfig('base_path').'assets/libs/ddTools/modx.ddtools.class.php'; +$result = ''; //Если для отладки нужно вывести то что пришло в сниппет выводим if(isset($debugTitle)){ ddTools::logEvent([ - 'message' => '

Snippet parameters:

'.var_export(
+		'message' => '

Snippet parameters:

' . var_export(
 			$params,
 			true
-		).'
', - 'source' => 'ddIf: '.$debugTitle + ) . '
', + 'source' => 'ddIf: ' . $debugTitle ]); } @@ -49,8 +50,16 @@ } //Если передали, с чем сравнивать, хорошо, если нет — будем с пустой строкой - $operand2 = isset($operand2) ? $operand2 : ''; - $operator = isset($operator) ? mb_strtolower($operator) : '=='; + $operand2 = + isset($operand2) ? + $operand2 : + '' + ; + $operator = + isset($operator) ? + mb_strtolower($operator) : + '==' + ; //Булевое значение истинности сравнения $boolOut = ''; @@ -59,31 +68,55 @@ case '!=': //Backward compatibility case '!r': - $boolOut = ($operand1 != $operand2) ? true : false; + $boolOut = + ($operand1 != $operand2) ? + true : + false + ; break; case '>': case 'b': - $boolOut = ($operand1 > $operand2) ? true : false; + $boolOut = + ($operand1 > $operand2) ? + true : + false + ; break; case '<': case 'm': - $boolOut = ($operand1 < $operand2) ? true : false; + $boolOut = + ($operand1 < $operand2) ? + true : + false + ; break; case '>=': case 'br': - $boolOut = ($operand1 >= $operand2) ? true : false; + $boolOut = + ($operand1 >= $operand2) ? + true : + false + ; break; case '<=': case 'mr': - $boolOut = ($operand1 <= $operand2) ? true : false; + $boolOut = + ($operand1 <= $operand2) ? + true : + false + ; break; case 'bool': - $boolOut = ($operand1) ? true : false; + $boolOut = + ($operand1) ? + true : + false + ; break; case 'inarray': @@ -91,10 +124,14 @@ ',', $operand2 ); - $boolOut = in_array( - $operand1, - $operand2Array - ) ? true : false; + $boolOut = + in_array( + $operand1, + $operand2Array + ) ? + true : + false + ; break; case 'isnumeric': @@ -104,7 +141,11 @@ case '==': case 'r': default: - $boolOut = ($operand1 == $operand2) ? true : false; + $boolOut = + ($operand1 == $operand2) ? + true : + false + ; } //Если есть дополнительные данные @@ -129,10 +170,25 @@ } //Select output chunk - $resultChunk = $boolOut ? (isset($trueChunk) ? $trueChunk : '') : (isset($falseChunk) ? $falseChunk : ''); + $resultChunk = + $boolOut ? + ( + isset($trueChunk) ? + $trueChunk : + '' + ) : + ( + isset($falseChunk) ? + $falseChunk : + '' + ); //$modx->getTpl('@CODE:') returns '@CODE:' O_o - $resultChunk = $modx->getTpl($resultChunk != '@CODE:' ? $resultChunk : ''); + $resultChunk = $modx->getTpl( + $resultChunk != '@CODE:' ? + $resultChunk : + '' + ); $result = $modx->parseText( $resultChunk, From ab1759b52b9f230ce66f0fb2b337e8071546ad50 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Tue, 10 Mar 2020 17:55:07 +0300 Subject: [PATCH 02/10] * Minor changes. --- README.md | 1 + ddIf_snippet.php | 38 ++++++++++++++++++++++++++++---------- 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 4b332b0..cc2e147 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ # (MODX)EvolutionCMS.snippets.ddIf + This snippet compares 2 values and returns required chunk or string. ___ Visit the following [link](http://code.divandesign.biz/modx/ddif) to read the documentation, instructions & changelog. \ No newline at end of file diff --git a/ddIf_snippet.php b/ddIf_snippet.php index 6201d8f..a9b17c4 100644 --- a/ddIf_snippet.php +++ b/ddIf_snippet.php @@ -23,17 +23,24 @@ */ //Include (MODX)EvolutionCMS.libraries.ddTools -require_once($modx->getConfig('base_path') . 'assets/libs/ddTools/modx.ddtools.class.php'); +require_once( + $modx->getConfig('base_path') . + 'assets/libs/ddTools/modx.ddtools.class.php' +); $result = ''; //Если для отладки нужно вывести то что пришло в сниппет выводим if(isset($debugTitle)){ - ddTools::logEvent([ - 'message' => '

Snippet parameters:

' . var_export(
-			$params,
-			true
-		) . '
', + \ddTools::logEvent([ + 'message' => + '

Snippet parameters:

' .
+			var_export(
+				$params,
+				true
+			) .
+			'
' + , 'source' => 'ddIf: ' . $debugTitle ]); } @@ -151,7 +158,7 @@ //Если есть дополнительные данные if (isset($placeholders)){ //Разбиваем их - $placeholders = ddTools::encodedStringToArray($placeholders); + $placeholders = \ddTools::encodedStringToArray($placeholders); }else{ $placeholders = []; } @@ -161,12 +168,23 @@ isset($trueString) || isset($falseString) ){ - ddTools::logEvent([ + \ddTools::logEvent([ 'message' => '

The “trueString” and “falseString” parameters are deprecated. Please use instead “trueChunk” and “falseChunk” with the “@CODE:” prefix.

' ]); - if (isset($trueString)){$trueChunk = '@CODE:'.$trueString;} - if (isset($falseString)){$falseChunk = '@CODE:'.$falseString;} + if (isset($trueString)){ + $trueChunk = + '@CODE:' . + $trueString + ; + } + + if (isset($falseString)){ + $falseChunk = + '@CODE:' . + $falseString + ; + } } //Select output chunk From 59354fef9b6f794117f25926ceb9e3b4129be787 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Tue, 10 Mar 2020 17:58:57 +0300 Subject: [PATCH 03/10] * Small refactoring. --- ddIf_snippet.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ddIf_snippet.php b/ddIf_snippet.php index a9b17c4..7bf1953 100644 --- a/ddIf_snippet.php +++ b/ddIf_snippet.php @@ -28,7 +28,8 @@ 'assets/libs/ddTools/modx.ddtools.class.php' ); -$result = ''; +//The snippet must return an empty string even if result is absent +$snippetResult = ''; //Если для отладки нужно вывести то что пришло в сниппет выводим if(isset($debugTitle)){ @@ -208,7 +209,7 @@ '' ); - $result = $modx->parseText( + $snippetResult = $modx->parseText( $resultChunk, array_merge( [ @@ -221,5 +222,5 @@ ); } -return $result; +return $snippetResult; ?> \ No newline at end of file From dc90f43112ec1ad288f9f71bad49c64e1e2fddc9 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Thu, 21 May 2020 23:42:35 +0300 Subject: [PATCH 04/10] * Minor changes. --- ddIf_snippet.php | 41 +++++++++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/ddIf_snippet.php b/ddIf_snippet.php index 7bf1953..a5015e4 100644 --- a/ddIf_snippet.php +++ b/ddIf_snippet.php @@ -17,11 +17,13 @@ * @param $placeholders {string_json|string_queryFormated} — Additional data which is required to transfer to chunk. JSON or query-formated string, e. g.: '{"width": 800, "height": 600}' or 'width=800&height=600'. Default: ''. * @param $debugTitle {string} — The title for the System Event log if debugging is needed. Just set it and watch the System Event log. Default: —. * - * @link http://code.divandesign.biz/modx/ddif/1.6 + * @link https://code.divandesign.biz/modx/ddif * - * @copyright 2012–2018 DivanDesign {@link http://www.DivanDesign.biz } + * @copyright 2012–2018 DD Group {@link https://DivanDesign.biz } */ +global $modx; + //Include (MODX)EvolutionCMS.libraries.ddTools require_once( $modx->getConfig('base_path') . @@ -42,18 +44,22 @@ ) . '' , - 'source' => 'ddIf: ' . $debugTitle + 'source' => + 'ddIf: ' . + $debugTitle ]); } //Если передано, что сравнивать if (isset($operand1)){ //Если это сырой плейсхолдер, то скорее всего он пустой, и его не обработал парсер, приравняем тогда параметр к пустоте - if(mb_substr( - $operand1, - 0, - 2 - ) == '[+'){ + if( + mb_substr( + $operand1, + 0, + 2 + ) == '[+' + ){ $operand1 = ''; } @@ -71,13 +77,14 @@ //Булевое значение истинности сравнения $boolOut = ''; + //Выбираем сравнение в зависимости от оператора switch ($operator){ case '!=': //Backward compatibility case '!r': $boolOut = - ($operand1 != $operand2) ? + $operand1 != $operand2 ? true : false ; @@ -86,7 +93,7 @@ case '>': case 'b': $boolOut = - ($operand1 > $operand2) ? + $operand1 > $operand2 ? true : false ; @@ -95,7 +102,7 @@ case '<': case 'm': $boolOut = - ($operand1 < $operand2) ? + $operand1 < $operand2 ? true : false ; @@ -104,7 +111,7 @@ case '>=': case 'br': $boolOut = - ($operand1 >= $operand2) ? + $operand1 >= $operand2 ? true : false ; @@ -113,7 +120,7 @@ case '<=': case 'mr': $boolOut = - ($operand1 <= $operand2) ? + $operand1 <= $operand2 ? true : false ; @@ -121,7 +128,7 @@ case 'bool': $boolOut = - ($operand1) ? + $operand1 ? true : false ; @@ -132,6 +139,7 @@ ',', $operand2 ); + $boolOut = in_array( $operand1, @@ -150,7 +158,7 @@ case 'r': default: $boolOut = - ($operand1 == $operand2) ? + $operand1 == $operand2 ? true : false ; @@ -200,7 +208,8 @@ isset($falseChunk) ? $falseChunk : '' - ); + ) + ; //$modx->getTpl('@CODE:') returns '@CODE:' O_o $resultChunk = $modx->getTpl( From 1a7b3e82a905d05869c45d3033e4a8f42a077134 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Thu, 17 Sep 2020 13:28:22 +0300 Subject: [PATCH 05/10] =?UTF-8?q?+=20Parameters=20=E2=86=92=20`placeholder?= =?UTF-8?q?s`:=20Nested=20arrays=20are=20supported=20too.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ddIf_snippet.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ddIf_snippet.php b/ddIf_snippet.php index a5015e4..a03e910 100644 --- a/ddIf_snippet.php +++ b/ddIf_snippet.php @@ -14,7 +14,7 @@ * @param $operator {'=='|'!='|'>'|'<'|'<='|'>='|'bool'|'inarray'|'isnumeric'} — Comparing operator. Default: '=='. * @param $trueChunk {string_chunkName|string} — This value is returning if result is true (chunk name or code via “@CODE:” prefix). Available placeholders: [+ddIf_operand1+], [+ddIf_operand2+], [+ddIf_operator+], [+anyPlaceholdersFromPlaceholdersParam+]. Default: ''. * @param $falseChunk {string_chunkName|string} — This value is returning if result is false (chunk name or code via “@CODE:” prefix). Available placeholders: [+ddIf_operand1+], [+ddIf_operand2+], [+ddIf_operator+], [+anyPlaceholdersFromPlaceholdersParam+]. Default: ''. - * @param $placeholders {string_json|string_queryFormated} — Additional data which is required to transfer to chunk. JSON or query-formated string, e. g.: '{"width": 800, "height": 600}' or 'width=800&height=600'. Default: ''. + * @param $placeholders {string_json|string_queryFormated} — Additional data which is required to transfer to chunk. JSON or query-formated string, e. g.: '{"width": 800, "height": 600}' or 'width=800&height=600'. Nested arrays are supported too. Default: ''. * @param $debugTitle {string} — The title for the System Event log if debugging is needed. Just set it and watch the System Event log. Default: —. * * @link https://code.divandesign.biz/modx/ddif @@ -218,9 +218,9 @@ '' ); - $snippetResult = $modx->parseText( - $resultChunk, - array_merge( + $snippetResult = \ddTools::parseText([ + 'text' => $resultChunk, + 'data' => array_merge( [ 'ddIf_operand1' => $operand1, 'ddIf_operand2' => $operand2, @@ -228,7 +228,7 @@ ], $placeholders ) - ); + ]); } return $snippetResult; From 42c7aeffb4c720dcc609b2310cc2264ff1c07785 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Thu, 17 Sep 2020 13:30:11 +0300 Subject: [PATCH 06/10] * Minor changes. --- ddIf_snippet.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ddIf_snippet.php b/ddIf_snippet.php index a03e910..197dc06 100644 --- a/ddIf_snippet.php +++ b/ddIf_snippet.php @@ -5,16 +5,16 @@ * * @desc This snippet compares 2 values and returns required chunk or string. * - * @uses PHP >= 5.4. - * @uses (MODX)EvolutionCMS >= 1.1. - * @uses (MODX)EvolutionCMS.libraries.ddTools >= 0.18. + * @uses PHP >= 5.4 + * @uses (MODX)EvolutionCMS >= 1.1 + * @uses (MODX)EvolutionCMS.libraries.ddTools >= 0.18 * * @param $operand1 {string} — The first operand for comparing. @required * @param $operand2 {string} — The second operand for comparing. Default: ''. * @param $operator {'=='|'!='|'>'|'<'|'<='|'>='|'bool'|'inarray'|'isnumeric'} — Comparing operator. Default: '=='. - * @param $trueChunk {string_chunkName|string} — This value is returning if result is true (chunk name or code via “@CODE:” prefix). Available placeholders: [+ddIf_operand1+], [+ddIf_operand2+], [+ddIf_operator+], [+anyPlaceholdersFromPlaceholdersParam+]. Default: ''. - * @param $falseChunk {string_chunkName|string} — This value is returning if result is false (chunk name or code via “@CODE:” prefix). Available placeholders: [+ddIf_operand1+], [+ddIf_operand2+], [+ddIf_operator+], [+anyPlaceholdersFromPlaceholdersParam+]. Default: ''. - * @param $placeholders {string_json|string_queryFormated} — Additional data which is required to transfer to chunk. JSON or query-formated string, e. g.: '{"width": 800, "height": 600}' or 'width=800&height=600'. Nested arrays are supported too. Default: ''. + * @param $trueChunk {stringChunkName|string} — This value is returning if result is true (chunk name or code via “@CODE:” prefix). Available placeholders: [+ddIf_operand1+], [+ddIf_operand2+], [+ddIf_operator+], [+anyPlaceholdersFromPlaceholdersParam+]. Default: ''. + * @param $falseChunk {stringChunkName|string} — This value is returning if result is false (chunk name or code via “@CODE:” prefix). Available placeholders: [+ddIf_operand1+], [+ddIf_operand2+], [+ddIf_operator+], [+anyPlaceholdersFromPlaceholdersParam+]. Default: ''. + * @param $placeholders {stringJson|stringQueryFormated} — Additional data which is required to transfer to chunk. JSON or query-formated string, e. g.: '{"width": 800, "height": 600}' or 'width=800&height=600'. Nested arrays are supported too. Default: ''. * @param $debugTitle {string} — The title for the System Event log if debugging is needed. Just set it and watch the System Event log. Default: —. * * @link https://code.divandesign.biz/modx/ddif From 7210f33c26757baa6fbc4ea81fa354990eb98f6a Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Thu, 17 Sep 2020 14:38:23 +0300 Subject: [PATCH 07/10] + Composer.json. --- composer.json | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 composer.json diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..63fae3b --- /dev/null +++ b/composer.json @@ -0,0 +1,48 @@ +{ + "name": "dd/evolutioncms-snippets-ddif", + "type": "modxevo-snippet", + "version": "1.6", + "description": "This snippet compares 2 values and returns required chunk or string.", + "keywords": [ + "modx", + "modx evo", + "modx evolution", + "evo", + "evo cms", + "evolutioncms", + "evolution cms", + "dd group", + "dd studio", + "divandesign", + "ddif", + "if", + "compare" + ], + "homepage": "https://code.divandesign.biz/modx/ddif", + "authors": [ + { + "name": "DD Group", + "email": "code@DivanDesign.biz", + "homepage": "https://code.divandesign.biz", + "role": "Owner" + }, + { + "name": "Ilyas Ronef", + "email": "ilyas@DivanDesign.ru", + "homepage": "https://ronef.ru", + "role": "Developer" + }, + { + "name": "Vladislav Lavrov", + "role": "Developer" + }, + { + "name": "Andrey Demchenko", + "role": "Developer" + } + ], + "require": { + "php": ">=5.4.0", + "dd/evolutioncms-libraries-ddtools": ">=0.18.0" + } +} \ No newline at end of file From 3186351c1973f24f325199838fa7237d9fb95afb Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Mon, 28 Sep 2020 12:37:08 +0300 Subject: [PATCH 08/10] + README. + README_ru. --- README.md | 210 ++++++++++++++++++++++++++++++++++++++++++++++- README_ru.md | 210 +++++++++++++++++++++++++++++++++++++++++++++++ ddIf_snippet.php | 14 +--- 3 files changed, 418 insertions(+), 16 deletions(-) create mode 100644 README_ru.md diff --git a/README.md b/README.md index cc2e147..78f1ee9 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,210 @@ # (MODX)EvolutionCMS.snippets.ddIf +This snippet compares different values and returns required chunk or string. -This snippet compares 2 values and returns required chunk or string. -___ -Visit the following [link](http://code.divandesign.biz/modx/ddif) to read the documentation, instructions & changelog. \ No newline at end of file + +## Requires + +* PHP >= 5.4 +* [(MODX)EvolutionCMS](https://github.com/evolution-cms/evolution) >= 1.1 +* [(MODX)EvolutionCMS.libraries.ddTools](https://code.divandesign.biz/modx/ddtools) >= 0.18 + + +## Documentation + + +### Installation + +Elements → Snippets: Create a new snippet with the following data: + +1. Snippet name: `ddIf`. +2. Description: `1.6 This snippet compares different values and returns required chunk or string.`. +3. Category: `Core`. +4. Parse DocBlock: `no`. +5. Snippet code (php): Insert content of the `ddIf_snippet.php` file from the archive. + + +### Parameters description + +* `operand1` + * Desctription: The first operand for comparing. + * Valid values: `string` + * **Required** + +* `operand2` + * Desctription: The second operand for comparing. + * Valid values: `string` + * Default value: `''` + +* `operator` + * Desctription: Comparing operator. + * Valid values: + * `'=='` + * `'!='` + * `'>'` + * `'<'` + * `'<='` + * `'>='` + * `'bool'` + * `'inarray'` + * `'isnumeric'` + * Default value: `'=='` + +* `trueChunk` + * Desctription: This value is returning if result is true. + Available placeholders: + * `[+ddIf_operand1+]` — contains `operand1` value. + * `[+ddIf_operand2+]` — contains `operand2` value. + * `[+ddIf_operator+]` — contains `operator` value. + * `[+`any placeholders from the `placeholders` parameter`+]` + * Valid values: + * `stringChunkName` + * `string` — use inline templates starting with `@CODE:` + * Default value: `''` + +* `falseChunk` + * Desctription: This value is returning if result is false. + Available placeholders: + * `[+ddIf_operand1+]` — contains `operand1` value. + * `[+ddIf_operand2+]` — contains `operand2` value. + * `[+ddIf_operator+]` — contains `operator` value. + * `[+`any placeholders from the `placeholders` parameter`+]` + * Valid values: + * `stringChunkName` + * `string` — use inline templates starting with `@CODE:` + * Default value: `''` + +* `placeholders` + * Desctription: + Additional data has to be passed into the `trueChunk` and `falseChunk`. + Nested objects and arrays are supported too: + * `{"someOne": "1", "someTwo": "test" }` => `[+someOne+], [+someTwo+]`. + * `{"some": {"a": "one", "b": "two"} }` => `[+some.a+]`, `[+some.b+]`. + * `{"some": ["one", "two"] }` => `[+some.0+]`, `[+some.1+]`. + * Valid values: + * `stringJsonObject` — as [JSON](https://en.wikipedia.org/wiki/JSON) + * `stringQueryFormated` — as [Query string](https://en.wikipedia.org/wiki/Query_string) + * It can also be set as a PHP object or array (e. g. for calls through `$modx->runSnippet`). + * `arrayAssociative` + * `object` + * Default value: — + +* `debugTitle` + * Desctription: The title for the System Event log if debugging is needed. + Just set it and watch the System Event log. + * Valid values: `string` + * Default value: — + + +### Examples + + +#### String comparison + +``` +[[ddIf? + &operand1=`Test string 1` + &operator=`==` + &operand2=`Test string 2` + &trueChunk=`@CODE:The strings are equal.` + &falseChunk=`@CODE:The strings are not equal.` +]] +``` + +Returns: + +``` +The strings are not equal. +``` + + +#### Checks if a value exists in an array + +``` +[[ddIf? + &operand1=`Apple` + &operator=`inarray` + &operand2=`Pear,Banana,Apple,Orange` + &trueChunk=`@CODE:Exists.` + &falseChunk=`@CODE:Not exists.` +]] +``` + +Returns: + +``` +Exists. +``` + + +#### Checks if a `operand1` value is number or not + +``` +[[ddIf? + &operand1=`123` + &operator=`isnumeric` + &trueChunk=`@CODE:Number.` + &falseChunk=`@CODE:Not number.` +]] +``` + +Returns: + +``` +Number. +``` + + +#### Number comparison and pass additional data to chunks + +``` +[[ddIf? + &operand1=`[*general_price*]` + &operator=`<` + &operand2=`500` + &trueChunk=`general_goodInexpensive` + &falseChunk=`general_good` + &placeholders=`{ + "title": "[*pagetitle*]", + "image": "[*general_image*]", + "somethingText": "All we need is love!" + }` +]] +``` + +Code of the `general_good` chunk: + +```html +
+

[+title+], $[+ddIf_operand1+]

+ [+title+] +
+``` + +Code of the `general_goodInexpensive` chunk: + +```html +
+

[+title+], $[+ddIf_operand1+]

+ [+title+] +

[+somethingText+]

+
+``` + +Let `[*general_price*]` be equal to `120`, then the snippet returns: + +```html +
+

Some inexpensive good, $120

+ Some inexpensive good +
+``` + + +## Links + +* [Home page](https://code.divandesign.biz/modx/ddif) +* [Telegram chat](https://t.me/dd_code) + + + \ No newline at end of file diff --git a/README_ru.md b/README_ru.md new file mode 100644 index 0000000..19b2d1f --- /dev/null +++ b/README_ru.md @@ -0,0 +1,210 @@ +# (MODX)EvolutionCMS.snippets.ddIf + +Сравнивает значения и выводит необходимый чанк или строку. + + +## Использует + +* PHP >= 5.4 +* [(MODX)EvolutionCMS](https://github.com/evolution-cms/evolution) >= 1.1 +* [(MODX)EvolutionCMS.libraries.ddTools](https://code.divandesign.biz/modx/ddtools) >= 0.18 + + +## Документация + + +### Установка + +Элементы → Сниппеты: Создайте новый сниппет со следующими параметрами: + +1. Название сниппета: `ddIf`. +2. Описание: `1.6 Сравнивает значения и выводит необходимый чанк или строку.`. +3. Категория: `Core`. +4. Анализировать DocBlock: `no`. +5. Код сниппета (php): Вставьте содержимое файла `ddIf_snippet.php` из архива. + + +### Описание параметров + +* `operand1` + * Описание: Первое значение для сравнения. + * Допустимые значения: `string` + * **Обязателен** + +* `operand2` + * Описание: Второе значение для сравнения. + * Допустимые значения: `string` + * Значение по умолчанию: `''` + +* `operator` + * Описание: Оператор сравнения. + * Допустимые значения: + * `'=='` + * `'!='` + * `'>'` + * `'<'` + * `'<='` + * `'>='` + * `'bool'` + * `'inarray'` + * `'isnumeric'` + * Значение по умолчанию: `'=='` + +* `trueChunk` + * Описание: Значение, возвращаемое при истинном условии. + Доступные плейсхолдеры: + * `[+ddIf_operand1+]` — содержит значение `operand1`. + * `[+ddIf_operand2+]` — содержит значение `operand2`. + * `[+ddIf_operator+]` — содержит значение `operator`. + * `[+`любой плейсхолдер из параметра `placeholders` `+]` + * Допустимые значения: + * `stringChunkName` + * `string` — передавать код напрямую без чанка можно начиная значение с `@CODE:` + * Значение по умолчанию: `''` + +* `falseChunk` + * Описание: Значение, возвращаемое при ложном условии. + Доступные плейсхолдеры: + * `[+ddIf_operand1+]` — содержит значение `operand1`. + * `[+ddIf_operand2+]` — содержит значение `operand2`. + * `[+ddIf_operator+]` — содержит значение `operator`. + * `[+`любой плейсхолдер из параметра `placeholders` `+]` + * Допустимые значения: + * `stringChunkName` + * `string` — передавать код напрямую без чанка можно начиная значение с `@CODE:` + * Значение по умолчанию: `''` + +* `placeholders` + * Описание: + Дополнительные данные, которые будут переданы в шаблоны `trueChunk` и `falseChunk`. + Вложенные объекты и массивы также поддерживаются: + * `{"someOne": "1", "someTwo": "test" }` => `[+someOne+], [+someTwo+]`. + * `{"some": {"a": "one", "b": "two"} }` => `[+some.a+]`, `[+some.b+]`. + * `{"some": ["one", "two"] }` => `[+some.0+]`, `[+some.1+]`. + * Допустимые значения: + * `stringJsonObject` — в виде [JSON](https://ru.wikipedia.org/wiki/JSON) + * `stringQueryFormated` — в виде [Query string](https://en.wikipedia.org/wiki/Query_string) + * Также может быть задан, как нативный PHP объект или массив (например, для вызовов через `$modx->runSnippet`). + * `arrayAssociative` + * `object` + * Значение по умолчанию: — + +* `debugTitle` + * Описание: Заголовок для Протокола событий CMS. + Если нужно подебажить — задайте его и смотрите Протокол событий CMS. + * Допустимые значения: `string` + * Значение по умолчанию: — + + +### Примеры + + +#### Сравнение двух строк + +``` +[[ddIf? + &operand1=`Тестовая строка 1` + &operator=`==` + &operand2=`Тестовая строка 2` + &trueChunk=`@CODE:Строки равны.` + &falseChunk=`@CODE:Строки не равны.` +]] +``` + +Вернёт: + +``` +Строки не равны. +``` + + +#### Присутствует ли значение в массиве + +``` +[[ddIf? + &operand1=`Яблоки` + &operator=`inarray` + &operand2=`Груши,Бананы,Яблоки,Апельсины` + &trueChunk=`@CODE:Присутствует.` + &falseChunk=`@CODE:Отсутствует.` +]] +``` + +Вернёт: + +``` +Присутствует. +``` + + +#### Является ли `operand1` числом + +``` +[[ddIf? + &operand1=`123` + &operator=`isnumeric` + &trueChunk=`@CODE:Число.` + &falseChunk=`@CODE:Не число.` +]] +``` + +Вернёт: + +``` +Число. +``` + + +#### Сравнение двух чисел и передача дополнительных данных в чанки + +``` +[[ddIf? + &operand1=`[*general_price*]` + &operator=`<` + &operand2=`500` + &trueChunk=`general_goodInexpensive` + &falseChunk=`general_good` + &placeholders=`{ + "title": "[*pagetitle*]", + "image": "[*general_image*]", + "somethingText": "Любовь — всё, что нам нужно!" + }` +]] +``` + +Код чанка `general_good`: + +```html +
+

[+title+], $[+ddIf_operand1+]

+ [+title+] +
+``` + +Код чанка `general_goodInexpensive`: + +```html +
+

[+title+], $[+ddIf_operand1+]

+ [+title+] +

[+somethingText+]

+
+``` + +Пусть `[*general_price*]` равно `120`, тогда сниппет вернёт: + +```html +
+

Один из недорогих товаров, $120

+ Один из недорогих товаров +
+``` + + +## Ссылки + +* [Home page](https://code.divandesign.ru/modx/ddif) +* [Telegram chat](https://t.me/dd_code) + + + \ No newline at end of file diff --git a/ddIf_snippet.php b/ddIf_snippet.php index 197dc06..8628571 100644 --- a/ddIf_snippet.php +++ b/ddIf_snippet.php @@ -3,19 +3,7 @@ * ddIf * @version 1.6 (2018-12-05) * - * @desc This snippet compares 2 values and returns required chunk or string. - * - * @uses PHP >= 5.4 - * @uses (MODX)EvolutionCMS >= 1.1 - * @uses (MODX)EvolutionCMS.libraries.ddTools >= 0.18 - * - * @param $operand1 {string} — The first operand for comparing. @required - * @param $operand2 {string} — The second operand for comparing. Default: ''. - * @param $operator {'=='|'!='|'>'|'<'|'<='|'>='|'bool'|'inarray'|'isnumeric'} — Comparing operator. Default: '=='. - * @param $trueChunk {stringChunkName|string} — This value is returning if result is true (chunk name or code via “@CODE:” prefix). Available placeholders: [+ddIf_operand1+], [+ddIf_operand2+], [+ddIf_operator+], [+anyPlaceholdersFromPlaceholdersParam+]. Default: ''. - * @param $falseChunk {stringChunkName|string} — This value is returning if result is false (chunk name or code via “@CODE:” prefix). Available placeholders: [+ddIf_operand1+], [+ddIf_operand2+], [+ddIf_operator+], [+anyPlaceholdersFromPlaceholdersParam+]. Default: ''. - * @param $placeholders {stringJson|stringQueryFormated} — Additional data which is required to transfer to chunk. JSON or query-formated string, e. g.: '{"width": 800, "height": 600}' or 'width=800&height=600'. Nested arrays are supported too. Default: ''. - * @param $debugTitle {string} — The title for the System Event log if debugging is needed. Just set it and watch the System Event log. Default: —. + * @see README.md * * @link https://code.divandesign.biz/modx/ddif * From 0d87b8f60e60b5bc6b48655a82aef1a29dd8dd33 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Mon, 28 Sep 2020 13:07:36 +0300 Subject: [PATCH 09/10] + CHANGELOG. + CHANGELOG_ru. --- CHANGELOG.md | 52 +++++++++++++++++++++++++++++++++++++++++++++++++ CHANGELOG_ru.md | 52 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 CHANGELOG.md create mode 100644 CHANGELOG_ru.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..73e859c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,52 @@ +# (MODX)EvolutionCMS.snippets.ddIf changelog + + +## Version 1.6 (2018-12-05) +* \+ Parameters → `trueChunk`, `falseChunk`: Added few placeholders: + * \+ `[+ddIf_operand1+]` — contains `operand1` value. + * \+ `[+ddIf_operand2+]` — contains `operand2` value. + * \+ `[+ddIf_operator+]` — contains `operator` value. + + +## Version 1.5 (2018-10-31) +* \+ Parameters → `debugTitle`: The new parameter. If you need to debug just set it and watch the System Event log. +* \+ Parameters → `operand1`: If is equal to something like `[+somePlaceholder+]` the snippet interpretate it as `''`. It's convenient when placeholders were not parsed for any reason. + + +## Version 1.4 (2017-02-10) +* \* Attention! PHP >= 5.4 is required. +* \* Attention! (MODX)Evolution >= 1.1 is required. +* \* Attention! (MODX)Evolution.libraries.ddTools >= 0.18 is required. +* \+ Parameters → `placeholders`: Added JSON and Query string support. The old format is still supported but deprecated. +* \+ Parameters → `trueChunk`, `falseChunk`: Added support of the `@CODE:` keyword prefix. +* \- Parameters → `trueString`, `falseString`: Are deprecated (use `@CODE:` prefix instead). Backward compatibility is preserved with message to the CMS Event log. +* \* Small optimization and other changes. + + +## Version 1.3 (2016-07-14) +* \+ Parameter → `operator`: + * \+ Now can be equal to `isnumeric` — check the `operand1` is number or not. + * \+ Is not case sensitive. + + +## Version 1.2 (2015-02-22) +* \* Attention! (MODX)Evolution >= 1.0.13 is required. +* \+ Parameters → `operator`: Now can gets a simple operator value instead of it’s letter alias (of course, with backward compatibility). +* \+ Additional data (from the `placeholders` parameter) are processed in the `trueString` and `falseString` parameters too. +* \* Refactoring: + * \* The `$result` variable has not been used for placeholders array anymore, the `$placeholder` variable instead. + * \* One `return` instead of several, `return` in any case. + + +## Version 1.1 (2012-04-05) +* \* Attention! Backward compatibility is broken. Actually the version should be named as 2.0 because of backward compatibility absence but renaming hasn’t been done on account of minor changes. +* \* Attention! (MODX)Evolution.libraries.ddTools >= 0.2 is required. +* \* Parameters: + * \* `operand1`: Has been renamed from `subject`. + * \* `operand2`: Has been renamed from `operand`. + * \* `trueChunk`: Has been renamed from `trueChank`. + * \* `falseChunk`: Has been renamed from `falseChank`. + + + + \ No newline at end of file diff --git a/CHANGELOG_ru.md b/CHANGELOG_ru.md new file mode 100644 index 0000000..3087180 --- /dev/null +++ b/CHANGELOG_ru.md @@ -0,0 +1,52 @@ +# (MODX)EvolutionCMS.snippets.ddIf changelog + + +## Версия 1.6 (2018-12-05) +* \+ Параметры → `trueChunk`, `falseChunk`: Добавлено несколько плейсхолдеров: + * \+ `[+ddIf_operand1+]` — содержит значение `operand1`. + * \+ `[+ddIf_operand2+]` — содержит значение `operand2`. + * \+ `[+ddIf_operator+]` — содержит значение `operator`. + + +## Версия 1.5 (2018-10-31) +* \+ Параметры → `debugTitle`: Новый параметр. Если нужно подебажить, задайте его и смотрите Протокол событий CMS. +* \+ Параметры → `operand1`: Если равен чему-то вроде `[+somePlaceholder+]`, сниппет интерпретирует это как `''`. Это удобно, когда какие-то плейсхолдеры не отпарсились по каким-либо причинам. + + +## Версия 1.4 (2017-02-10) +* \* Внимание! Требуется PHP >= 5.4. +* \* Внимание! Требуется (MODX)Evolution >= 1.1. +* \* Внимание! Требуется (MODX)Evolution.libraries.ddTools >= 0.18. +* \+ Параметры → `placeholders`: Добавлена поддержка форматов JSON and Query string. Старый формат по прежнему поддерживается, но считается устаревшим. +* \+ Параметры → `trueChunk`, `falseChunk`: Добавлена поддержка указания шаблонов через префикс `@CODE:`. +* \- Параметры → `trueString`, `falseString`: больше не используются (вместо них используйте префикс `@CODE:`). Обратная совместимость сохранена с уведомлением в лог событий CMS. +* \* Небольшая оптимизация и прочие изменения. + + +## Версия 1.3 (2016-07-14) +* \+ Parameter → `operator`: + * \+ Теперь может принимать значение `isnumeric` — является ли `operand1` числом или нет. + * \+ Теперь не чувствителен к регистру. + + +## Версия 1.2 (2015-02-22) +* \* Внимание! Требуется (MODX)Evolution >= 1.0.13. +* \+ Параметры → `operator`: Поддерживает простое указание оператора, вместо буквенных псевдонимов (те тоже работают для обратной совместимости). +* \+ Дополнительные данные (из параметра `placeholders`) также передаются в `trueString` и `falseString`. +* \* Рефакторинг: + * \* Переменная `$result` как массив плэйсхолдеров больше не используется, переменная `$placeholders` используется вместо неё повторно. + * \* Один `return` вместо нескольких, в любом случае `return`. + + +## Версия 1.1 (2012-04-05) +* \* Внимание, нарушена обратная совместимость! Вообще говоря, версию надо бы назвать 2.0 из-за отсутствия обратной совместимости, но изменения настолько незначительные, что рука не поднимается. +* \* Внимание! Требуется (MODX)Evolution.libraries.ddTools >= 0.2. +* \* Параметры: + * \* `operand1`: Переименован из `subject`. + * \* `operand2`: Переименован из `operand`. + * \* `trueChunk`: Переименован из `trueChank`. + * \* `falseChunk`: Переименован из `falseChank`. + + + + \ No newline at end of file From 4895e9bcb99897718afdeb25c6dfb661a4d4fa84 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Mon, 28 Sep 2020 16:24:52 +0300 Subject: [PATCH 10/10] Prerelease --- CHANGELOG.md | 10 ++++++++++ CHANGELOG_ru.md | 10 ++++++++++ README.md | 4 ++-- README_ru.md | 2 +- composer.json | 6 +++--- ddIf_snippet.php | 4 ++-- 6 files changed, 28 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 73e859c..8796200 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,16 @@ # (MODX)EvolutionCMS.snippets.ddIf changelog +## Version 1.7 (2020-09-28) +* \* Attention! (MODX)Evolution.libraries.ddTools >= 0.40.1 is required (not tested with older versions). +* \+ Parameters → `placeholders`: Nested arrays are supported too. +* \+ README. +* \+ README_ru. +* \+ CHANGELOG. +* \+ CHANGELOG_ru. +* \+ Composer.json. + + ## Version 1.6 (2018-12-05) * \+ Parameters → `trueChunk`, `falseChunk`: Added few placeholders: * \+ `[+ddIf_operand1+]` — contains `operand1` value. diff --git a/CHANGELOG_ru.md b/CHANGELOG_ru.md index 3087180..7612cfc 100644 --- a/CHANGELOG_ru.md +++ b/CHANGELOG_ru.md @@ -1,6 +1,16 @@ # (MODX)EvolutionCMS.snippets.ddIf changelog +## Версия 1.7 (2020-09-28) +* \* Внимание! Требуется (MODX)Evolution.libraries.ddTools >= 0.40.1 (не тестировался с более старыми версиями). +* \+ Parameters → `placeholders`: Вложенные массивы также поддерживаются. +* \+ README. +* \+ README_ru. +* \+ CHANGELOG. +* \+ CHANGELOG_ru. +* \+ Composer.json. + + ## Версия 1.6 (2018-12-05) * \+ Параметры → `trueChunk`, `falseChunk`: Добавлено несколько плейсхолдеров: * \+ `[+ddIf_operand1+]` — содержит значение `operand1`. diff --git a/README.md b/README.md index 78f1ee9..e936c65 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ This snippet compares different values and returns required chunk or string. * PHP >= 5.4 * [(MODX)EvolutionCMS](https://github.com/evolution-cms/evolution) >= 1.1 -* [(MODX)EvolutionCMS.libraries.ddTools](https://code.divandesign.biz/modx/ddtools) >= 0.18 +* [(MODX)EvolutionCMS.libraries.ddTools](https://code.divandesign.biz/modx/ddtools) >= 0.40.1 (not tested with older versions) ## Documentation @@ -18,7 +18,7 @@ This snippet compares different values and returns required chunk or string. Elements → Snippets: Create a new snippet with the following data: 1. Snippet name: `ddIf`. -2. Description: `1.6 This snippet compares different values and returns required chunk or string.`. +2. Description: `1.7 This snippet compares different values and returns required chunk or string.`. 3. Category: `Core`. 4. Parse DocBlock: `no`. 5. Snippet code (php): Insert content of the `ddIf_snippet.php` file from the archive. diff --git a/README_ru.md b/README_ru.md index 19b2d1f..adba9f0 100644 --- a/README_ru.md +++ b/README_ru.md @@ -7,7 +7,7 @@ * PHP >= 5.4 * [(MODX)EvolutionCMS](https://github.com/evolution-cms/evolution) >= 1.1 -* [(MODX)EvolutionCMS.libraries.ddTools](https://code.divandesign.biz/modx/ddtools) >= 0.18 +* [(MODX)EvolutionCMS.libraries.ddTools](https://code.divandesign.biz/modx/ddtools) >= 0.40.1 (не тестировался с более старыми версиями) ## Документация diff --git a/composer.json b/composer.json index 63fae3b..c7b2089 100644 --- a/composer.json +++ b/composer.json @@ -1,8 +1,8 @@ { "name": "dd/evolutioncms-snippets-ddif", "type": "modxevo-snippet", - "version": "1.6", - "description": "This snippet compares 2 values and returns required chunk or string.", + "version": "1.7", + "description": "This snippet compares different values and returns required chunk or string.", "keywords": [ "modx", "modx evo", @@ -43,6 +43,6 @@ ], "require": { "php": ">=5.4.0", - "dd/evolutioncms-libraries-ddtools": ">=0.18.0" + "dd/evolutioncms-libraries-ddtools": ">=0.40.1" } } \ No newline at end of file diff --git a/ddIf_snippet.php b/ddIf_snippet.php index 8628571..75611ae 100644 --- a/ddIf_snippet.php +++ b/ddIf_snippet.php @@ -1,13 +1,13 @@