Skip to content

Commit 2fae945

Browse files
authored
Merge pull request #8959 from kenjis/fix-if_exist-with-array
fix: [Validation] `if_exist` does not work with array data
2 parents ad73071 + cdec7d0 commit 2fae945

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

system/Validation/Validation.php

+3-1
Original file line numberDiff line numberDiff line change
@@ -399,8 +399,10 @@ private function processIfExist(string $field, array $rules, array $data)
399399
break;
400400
}
401401
}
402-
} else {
402+
} elseif (str_contains($field, '.')) {
403403
$dataIsExisting = array_key_exists($ifExistField, $flattenedData);
404+
} else {
405+
$dataIsExisting = array_key_exists($ifExistField, $data);
404406
}
405407

406408
if (! $dataIsExisting) {

tests/system/Validation/RulesTest.php

+14
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use CodeIgniter\Test\CIUnitTestCase;
1717
use Config\Services;
18+
use ErrorException;
1819
use PHPUnit\Framework\Attributes\DataProvider;
1920
use PHPUnit\Framework\Attributes\Group;
2021
use stdClass;
@@ -126,6 +127,19 @@ public static function provideIfExist(): iterable
126127
];
127128
}
128129

130+
public function testIfExistArray(): void
131+
{
132+
$this->expectException(ErrorException::class);
133+
$this->expectExceptionMessage('Array to string conversion');
134+
135+
$rules = ['foo' => 'if_exist|alpha'];
136+
// Invalid array input
137+
$data = ['foo' => ['bar' => '12345']];
138+
139+
$this->validation->setRules($rules);
140+
$this->validation->run($data);
141+
}
142+
129143
#[DataProvider('providePermitEmpty')]
130144
public function testPermitEmpty(array $rules, array $data, bool $expected): void
131145
{

tests/system/Validation/StrictRules/RulesTest.php

+10
Original file line numberDiff line numberDiff line change
@@ -244,4 +244,14 @@ public static function provideDiffers(): iterable
244244
'foo bar bool match' => [['foo' => true, 'bar' => true], false],
245245
];
246246
}
247+
248+
public function testIfExistArray(): void
249+
{
250+
$rules = ['foo' => 'if_exist|alpha'];
251+
// Invalid array input
252+
$data = ['foo' => ['bar' => '12345']];
253+
254+
$this->validation->setRules($rules);
255+
$this->assertFalse($this->validation->run($data));
256+
}
247257
}

0 commit comments

Comments
 (0)