Skip to content

Commit

Permalink
Merge pull request #8959 from kenjis/fix-if_exist-with-array
Browse files Browse the repository at this point in the history
fix: [Validation] `if_exist` does not work with array data
  • Loading branch information
kenjis authored Jun 19, 2024
2 parents ad73071 + cdec7d0 commit 2fae945
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
4 changes: 3 additions & 1 deletion system/Validation/Validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -399,8 +399,10 @@ private function processIfExist(string $field, array $rules, array $data)
break;
}
}
} else {
} elseif (str_contains($field, '.')) {
$dataIsExisting = array_key_exists($ifExistField, $flattenedData);
} else {
$dataIsExisting = array_key_exists($ifExistField, $data);
}

if (! $dataIsExisting) {
Expand Down
14 changes: 14 additions & 0 deletions tests/system/Validation/RulesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use CodeIgniter\Test\CIUnitTestCase;
use Config\Services;
use ErrorException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use stdClass;
Expand Down Expand Up @@ -126,6 +127,19 @@ public static function provideIfExist(): iterable
];
}

public function testIfExistArray(): void
{
$this->expectException(ErrorException::class);
$this->expectExceptionMessage('Array to string conversion');

$rules = ['foo' => 'if_exist|alpha'];
// Invalid array input
$data = ['foo' => ['bar' => '12345']];

$this->validation->setRules($rules);
$this->validation->run($data);
}

#[DataProvider('providePermitEmpty')]
public function testPermitEmpty(array $rules, array $data, bool $expected): void
{
Expand Down
10 changes: 10 additions & 0 deletions tests/system/Validation/StrictRules/RulesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -244,4 +244,14 @@ public static function provideDiffers(): iterable
'foo bar bool match' => [['foo' => true, 'bar' => true], false],
];
}

public function testIfExistArray(): void
{
$rules = ['foo' => 'if_exist|alpha'];
// Invalid array input
$data = ['foo' => ['bar' => '12345']];

$this->validation->setRules($rules);
$this->assertFalse($this->validation->run($data));
}
}

0 comments on commit 2fae945

Please sign in to comment.