Skip to content

Commit 928d453

Browse files
2.7
1 parent 46f85bf commit 928d453

File tree

6 files changed

+181
-19
lines changed

6 files changed

+181
-19
lines changed

README.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,51 @@ $validation->alwaysTrim(true,",."); // always trim , and .
610610
$validation->alwaysTrim(false); // we disable the always trim.
611611
```
612612

613+
### isArray()
614+
615+
If we want to fetch an array, then we could use the next method
616+
617+
```php
618+
$array=$validation->isArray()->request('id');
619+
```
620+
It also validates every value. However, it stores the messages in a single container.
621+
622+
If we want to store every message separately, then we could use:
623+
```php
624+
$array=$validation->isArray(true)->request('id');
625+
```
626+
627+
#### Example of array
628+
629+
```html
630+
<form>
631+
<input type='text' name='field[col1][0]' value="cocacola" />
632+
<input type='text' name='field[col2][0]' value="123" /><br>
633+
<input type='text' name='field[col1][1]' value="fanta" />
634+
<input type='text' name='field[col2][1]' value="123" /><br>
635+
<input type="submit"><br>
636+
</form>
637+
```
638+
639+
>Note: You could also define the fields as 'field\[0]\[col1]' so you won't need to invert the array
640+
641+
```php
642+
$values=getVal()->isArray(true)->request('field'); // ['col1'=>['cocacola','fanta'],'col2'=>[123,123]]
643+
ValidationOne::invertArray($values); // // [['col1'=>'cocacola','col2'=>123],['col1'=>'fanta','col2'=>123]]
644+
```
645+
646+
### invertArray()
647+
648+
If the value is an array but the indexes of the columns are inverted with the columns, then you can invert the order<br>
649+
**example:**
650+
651+
```php
652+
$arr=['col1'=>['cocacola','fanta'],'col2'=>[1,2]];
653+
ValidationOne::invertArray($arr); // [['col1'=>'cocacola','col2'=>1],['col1'=>'fanta','col2'=>2]]
654+
'''
655+
656+
657+
613658

614659

615660
### convert()
@@ -663,6 +708,9 @@ $validation->convert('htmldecode')->set(....);
663708

664709

665710
## Version list
711+
* 2023-02-26 2.7
712+
* added a new argument for isArray()
713+
* added the static method invertArray()
666714
* 2023-01-26 2.6
667715
* Some small cleanups.
668716
* 2022-08-27 2.5

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"require": {
1515
"php": ">=7.2.5",
1616
"ext-ctype": "*",
17-
"eftec/messagecontainer": "^2.6",
17+
"eftec/messagecontainer": "^2.8",
1818
"ext-json": "*",
1919
"ext-fileinfo": "*"
2020
},

examples/examplearrayget3.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<form method="post">
2+
<input type='text' name='field[0][col1]' value="cocacola" />
3+
<input type='text' name='field[0][col2]' value="123" /><br>
4+
<input type='text' name='field[1][col1]' value="fanta" />
5+
<input type='text' name='field[1][col2]' value="123" /><br>
6+
<input type="submit"><br>
7+
</form>
8+
<?php
9+
10+
use eftec\ValidationOne;
11+
12+
include "common.php";
13+
$values=getVal('')->type('integer')->ifFailThenOrigin()->isArray(true)->request('field');
14+
echo "<h1>The validation</h1>";
15+
var_dump(getVal('')->getMessageId('field')->allError());
16+
//var_dump(getVal('')->getMessage());
17+
echo "<h1>The values</h1>";
18+
echo "<pre>";
19+
var_dump($values);
20+
echo "</pre>";
21+
echo "<h1>The values inverted</h1>";
22+
echo "<pre>";
23+
var_dump(ValidationOne::invertArray($values));
24+
echo "</pre>";
25+

examples/examplearrayget3inv.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<form method="post">
2+
<input type='text' name='field[col1][0]' value="cocacola" />
3+
<input type='text' name='field[col2][0]' value="123" /><br>
4+
<input type='text' name='field[col1][1]' value="fanta" />
5+
<input type='text' name='field[col2][1]' value="123" /><br>
6+
<input type="submit"><br>
7+
</form>
8+
<?php
9+
10+
use eftec\ValidationOne;
11+
12+
include "common.php";
13+
14+
$values=getVal('')->type('integer')->ifFailThenOrigin()->isArray(true)->request('field');
15+
echo "<h1>The validation</h1>";
16+
var_dump(getVal('')->getMessageId('field')->allError());
17+
//var_dump(getVal('')->getMessage());
18+
echo "<h1>The values</h1>";
19+
echo "<pre>";
20+
var_dump($values);
21+
echo "</pre>";
22+
echo "<h1>The values inverted</h1>";
23+
echo "<pre>";
24+
var_dump(ValidationOne::invertArray($values));
25+
echo "</pre>";
26+

lib/ValidationOne.php

Lines changed: 54 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,13 @@
1717
*
1818
* @package eftec
1919
* @author Jorge Castro Castillo
20-
* @version 2.6 2023-01-26
20+
* @version 2.7 2023-02-26
2121
* @copyright (c) Jorge Castro C. LGLPV2 License https://github.com/EFTEC/ValidationOne
2222
* @see https://github.com/EFTEC/ValidationOne
2323
*/
2424
class ValidationOne
2525
{
26+
public const VERSION='2.7';
2627
/** @var string It is the (expected) input format for date (short) */
2728
public $dateShort = 'd/m/Y';
2829
/** @var string It is the (expected) input format (with date and time) */
@@ -69,6 +70,13 @@ class ValidationOne
6970
private $isColumn = false;
7071
/** @var bool if true then the errors from id[0],id[1] ared stored in "idx" */
7172
private $isArrayFlat = false;
73+
/**
74+
* @var bool If the value is an array but the indexes of the columns are inverted with the columns, then you can
75+
* invert the order<br>
76+
* <b>(false, no conversion)</b>: ['col1'=>['cocacola','fanta'],'col2'=>[1,2]]<br>
77+
* <b>(true)</b>: [['col1'=>'cocacola','col2'=>1],['col1'=>'fanta','col2'=>2]]<br>
78+
*/
79+
private $invertIndexRow = false;
7280
/** @var bool TODO */
7381
private $hasMessage = false;
7482
/** @var bool if the validation fails then it returns the default value */
@@ -364,6 +372,9 @@ private function afterFetch($input, $fieldId, ?string $msg)
364372
if ($this->missingSet !== null && ($input === null || $input === '')) {
365373
$input = $this->missingSet;
366374
}
375+
if($this->isArray && $this->invertIndexRow) {
376+
$input = self::invertArray($input);
377+
}
367378
//if (!$this->isMissing) {
368379
if ($this->ifFailThenOrigin) {
369380
$this->default = $input;
@@ -391,8 +402,9 @@ private function afterFetch($input, $fieldId, ?string $msg)
391402
foreach ($input as $key => &$items) {
392403
$currentField = ($this->isArrayFlat) ? $fieldId : $fieldId . "[" . $key . "]";
393404
$this->runConditions($items, $currentField, $key);
405+
394406
if ($this->ifFailThenDefault && $this->messageList->get($currentField)->countError()) {
395-
$items = (is_array($this->default)) ? $this->default[$key] : $this->default;
407+
$items = (is_array($this->default)) ? ($this->default[$key]??null) : $this->default;
396408
}
397409
}
398410
unset($items);
@@ -443,6 +455,34 @@ private function afterFetch($input, $fieldId, ?string $msg)
443455
return $output;
444456
}
445457

458+
/**
459+
* If the value is an array but the indexes of the columns are inverted with the columns,
460+
* then you can invert the order<br>
461+
* <b>example:</b><br>
462+
* <pre>
463+
* $arr=['col1'=>['cocacola','fanta'],'col2'=>[1,2]];
464+
* ValidationOne::invertArray($arr); // [['col1'=>'cocacola','col2'=>1],['col1'=>'fanta','col2'=>2]]
465+
* </pre>
466+
* @param array|null $input
467+
* @return array|null
468+
*/
469+
public static function invertArray(?array $input):?array {
470+
if($input===null) {
471+
return null;
472+
}
473+
$inputFinal = [];
474+
foreach ($input as $kcol => $vcol) {
475+
if (is_array($vcol)) {
476+
foreach ($vcol as $kid => $vidx) {
477+
$inputFinal[$kid][$kcol] = $vidx;
478+
}
479+
} else {
480+
$inputFinal[$kcol] = $vcol;
481+
}
482+
}
483+
return $inputFinal;
484+
}
485+
446486

447487
//<editor-fold desc="chain commands">
448488

@@ -570,7 +610,7 @@ private function addMessageInternal(?string $msg, ?string $msg2, string $fieldId
570610
}
571611
if (is_array($this->originalValue)) {
572612
$txt = str_replace(['%field', '%realfield', '%value', '%comp', '%first', '%second', '%key'], [
573-
$this->friendId ?? $fieldId,
613+
$this->friendId ?? $fieldId,
574614
$fieldId,
575615
is_array($value) ? "[]" : $value,
576616
$vcomp,
@@ -581,7 +621,7 @@ private function addMessageInternal(?string $msg, ?string $msg2, string $fieldId
581621
//$this->originalValue=$value;
582622
} else {
583623
$txt = str_replace(['%field', '%realfield', '%value', '%comp', '%first', '%second', '%key'], [
584-
$this->friendId ?? $fieldId,
624+
$this->friendId ?? $fieldId,
585625
$fieldId,
586626
$this->addMessageSer($this->originalValue),
587627
$this->addMessageSer($vcomp),
@@ -1760,13 +1800,17 @@ public function abortOnError(bool $abort = false): ValidationOne
17601800
* If $flat is true then the errors are returned as a flat array (idx instead of idx[0],idx[1])
17611801
*
17621802
* @param bool $flat
1803+
* @param bool $invertIndexRow If true, then it invert the order of the array<br>
1804+
* <b>(false, no conversion)</b>: ['col1'=>['cocacola','fanta'],'col2'=>[1,2]]<br>
1805+
* <b>(true)</b>: [['col1'=>'cocacola','col2'=>1],['col1'=>'fanta','col2'=>2]]<br>
17631806
*
17641807
* @return ValidationOne $this
17651808
*/
1766-
public function isArray(bool $flat = false): ValidationOne
1809+
public function isArray(bool $flat = false,bool $invertIndexRow = false): ValidationOne
17671810
{
17681811
$this->isArray = true;
17691812
$this->isArrayFlat = $flat;
1813+
$this->invertIndexRow = $invertIndexRow;
17701814
return $this;
17711815
}
17721816

@@ -2068,7 +2112,7 @@ public function required(bool $required = true, string $msg = ''): ValidationOne
20682112
}
20692113

20702114
/**
2071-
* @param FormOne $form
2115+
* @param FormOne|null $form
20722116
*
20732117
* @return ValidationOne
20742118
* @noinspection PhpUndefinedClassInspection
@@ -2176,8 +2220,12 @@ public function set($input, string $fieldId = "setfield", ?string $msg = "", boo
21762220
if (is_object($input)) {
21772221
$input = (array)$input;
21782222
}
2223+
if(is_array($input) && $this->invertIndexRow) {
2224+
$input = self::invertArray($input);
2225+
}
21792226
$this->countError = $this->messageList->errorCount;
21802227
if (is_array($input)) {
2228+
21812229
if (!$this->isMissingValid || !$this->isMissing) { // bypass if missing is valid (and the value is missing)
21822230
foreach ($input as $key => &$v) {
21832231
$this->originalValue = $v;

tests/ValidationOneTest.php

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use DateTime;
66
use eftec\MessageContainer;
7+
use eftec\ValidationOne;
78
use PHPUnit\Framework\TestCase;
89

910

@@ -23,16 +24,20 @@ public function test_db(): void
2324
getVal()->override(false);
2425
self::assertCount(2, getVal()->messageList->allErrorArray(), 'it must be 2 errors');
2526
}
27+
public function testVersion():void
28+
{
29+
$this->assertNotEmpty(ValidationOne::VERSION);
30+
}
2631

2732
public function testMessages(): void
2833
{
2934
$ml = MessageContainer::instance();
3035
$ml->resetAll();
31-
$ml->addItem('c1', 'message error c1-1', 'error');
32-
$ml->addItem('c1', 'message error c1-2', 'error');
36+
$ml->addItem('c1', 'message error c1-1');
37+
$ml->addItem('c1', 'message error c1-2');
3338

34-
$ml->addItem('c2', 'message error c2-1', 'error');
35-
$ml->addItem('c2', 'message error c2-2', 'error');
39+
$ml->addItem('c2', 'message error c2-1');
40+
$ml->addItem('c2', 'message error c2-2');
3641

3742
self::assertEquals(['message error c1-1', 'message error c1-2'], $ml->get('c1')->allErrorOrWarning());
3843
self::assertEquals(['message error c1-1', 'message error c1-2'], $ml->get('c1')->allErrorOrWarning());
@@ -45,6 +50,16 @@ public function testMessages(): void
4550
], $ml->allErrorOrWarningArray());
4651
}
4752
public function testArray(): void
53+
{
54+
getVal()->resetValidation(true);
55+
$r=getVal()->isArray(true,true)->set(['col1'=>['cocacola','fanta'],'col2'=>[1,2]],'id');
56+
self::assertEquals(
57+
[
58+
['col1'=>'cocacola','col2'=>1],
59+
['col1'=>'fanta','col2'=>2]
60+
], $r);
61+
}
62+
public function testArray2(): void
4863
{
4964
getVal()->resetValidation(true);
5065
getVal()->condition('gt','10')->isArray()->set([1,2,3],'id');
@@ -53,14 +68,14 @@ public function testArray(): void
5368

5469
public function test6(): void
5570
{
56-
getVal()->configChain(false, false);
71+
getVal()->configChain();
5772
getVal()->resetValidation(true);
5873
getVal()->useForm(null);
5974

6075
getVal()->notempty('this value must not be empty')->set('', 'id');
6176
self::assertEquals(1, getVal()->getMessageId('id')->countError());
6277
self::assertEquals('this value must not be empty', getVal()->messageList->firstErrorText());
63-
getVal()->configChain(false, false);
78+
getVal()->configChain();
6479
}
6580
public function testAlphaNumericUnder(): void
6681
{
@@ -114,7 +129,7 @@ public function testOther(): void
114129
getVal()->messageList->resetAll();
115130
unset($_POST['frm_FIELDREQ'], $_GET['frm_FIELDREQ'], $_FILES['frm_FIELDREQF']);
116131
$_POST['frm_FIELDREQ']='abc';
117-
$r=getVal()->type('integer')->def('noexist')->exist(true)->get('FIELDREQ');
132+
$r=getVal()->type('integer')->def('noexist')->exist()->get('FIELDREQ');
118133
self::assertEquals(false,getVal()->getHasMessage());
119134
}
120135
public function testPipeline(): void
@@ -123,7 +138,7 @@ public function testPipeline(): void
123138
getVal()->messageList->resetAll();
124139
unset($_POST['frm_FIELDREQ'], $_GET['frm_FIELDREQ'], $_FILES['frm_FIELDREQF']);
125140

126-
$r=getVal()->type('string')->def('noexist')->exist(true)->post('FIELDREQ');
141+
$r=getVal()->type('string')->def('noexist')->exist()->post('FIELDREQ');
127142
self::assertEquals(1,getVal()->messageList->errorCount);
128143
self::assertEquals("FIELDREQ does not exist",getVal()->getMessage());
129144
self::assertEquals('noexist',$r);
@@ -208,7 +223,7 @@ public function testMessageContainer(): void
208223
{
209224
getVal()->messageList->resetAll();
210225
self::assertEquals(0,getVal()->messageList->errorCount);
211-
getVal()->messageList->addItem('containere','errorm','error');
226+
getVal()->messageList->addItem('containere','errorm');
212227
getVal()->messageList->addItem('containeri','infom','info');
213228
getVal()->messageList->addItem('container1','warningm','warning');
214229
getVal()->messageList->addItem('containers','successm','success');
@@ -529,7 +544,7 @@ public function testFailCondition(): void
529544

530545
public function test7(): void
531546
{
532-
$r = getVal()->type('string')->isNullValid(true)->set(null, 'field');
547+
$r = getVal()->type('string')->isNullValid()->set(null, 'field');
533548
self::assertEquals(null, $r);
534549
}
535550

@@ -552,7 +567,7 @@ public function testExt(): void
552567
$this->assertEquals('image/jpeg',getVal()->getFileExtension('aaa.jpg',true));
553568
$this->assertEquals('application/javascript',getVal()->getFileExtension('aaa.js',true));
554569
$this->assertEquals('image/png',getVal()->getFileExtension('aaa.png',true));
555-
getVal()->addMessage('tmp','error','error');
570+
getVal()->addMessage('tmp','error');
556571
$this->assertEquals(1,getVal()->errorCount());
557572
$this->assertEquals('hello',getVal()->initial('hello')->get('XXXXX'));
558573
}
@@ -564,7 +579,7 @@ public function testDateEmptyOrMissing(): void
564579
self::assertEquals('', $r);
565580
$r = getVal()->type('datetimestring')->get('missingfield');
566581
self::assertEquals('', $r);
567-
$r = getVal()->type('datetimestring')->def(null)->ifFailThenDefault()->set(null);
582+
$r = getVal()->type('datetimestring')->def()->ifFailThenDefault()->set(null);
568583
self::assertEquals(null, $r);
569584
}
570585

0 commit comments

Comments
 (0)