Skip to content

feat: [Validation] add method to get the validated data #7420

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions system/Validation/DotArrayFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
<?php

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Validation;

final class DotArrayFilter
{
/**
* Creates a new array with only the elements specified in dot array syntax.
*
* This code comes from the dot_array_search() function.
*
* @param array $indexes The dot array syntax pattern to use for filtering.
* @param array $array The array to filter.
*
* @return array The filtered array.
*/
public static function run(array $indexes, array $array): array
{
$result = [];

foreach ($indexes as $index) {
// See https://regex101.com/r/44Ipql/1
$segments = preg_split(
'/(?<!\\\\)\./',
rtrim($index, '* '),
0,
PREG_SPLIT_NO_EMPTY
);

$segments = array_map(
static fn ($key) => str_replace('\.', '.', $key),
$segments
);

$result = array_merge_recursive($result, self::filter($segments, $array));
}

return $result;
}

/**
* Used by `run()` to recursively filter the array with wildcards.
*
* @param array $indexes The dot array syntax pattern to use for filtering.
* @param array $array The array to filter.
*
* @return array The filtered array.
*/
private static function filter(array $indexes, array $array): array
{
// If index is empty, returns empty array.
if ($indexes === []) {
return [];
}

// Grab the current index.
$currentIndex = array_shift($indexes);

if (! isset($array[$currentIndex]) && $currentIndex !== '*') {
return [];
}

// Handle Wildcard (*)
if ($currentIndex === '*') {
$answer = [];

foreach ($array as $key => $value) {
if (! is_array($value)) {
continue;
}

$result = self::filter($indexes, $value);

if ($result !== []) {
$answer[$key] = $result;
}
}

return $answer;
}

// If this is the last index, make sure to return it now,
// and not try to recurse through things.
if (empty($indexes)) {
return [$currentIndex => $array[$currentIndex]];
}

// Do we need to recursively filter this value?
if (is_array($array[$currentIndex]) && $array[$currentIndex] !== []) {
$result = self::filter($indexes, $array[$currentIndex]);

if ($result !== []) {
return [$currentIndex => $result];
}
}

// Otherwise, not found.
return [];
}
}
35 changes: 33 additions & 2 deletions system/Validation/Validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,13 @@ class Validation implements ValidationInterface
*/
protected $data = [];

/**
* The data that was actually validated.
*
* @var array
*/
protected $validated = [];

/**
* Any generated errors during validation.
* 'key' is the alias, 'value' is the message.
Expand Down Expand Up @@ -109,7 +116,12 @@ public function __construct($config, RendererInterface $view)
*/
public function run(?array $data = null, ?string $group = null, ?string $dbGroup = null): bool
{
$data ??= $this->data;
if ($data === null) {
$data = $this->data;
} else {
// Store data to validate.
$this->data = $data;
}

// i.e. is_unique
$data['DBGroup'] = $dbGroup;
Expand Down Expand Up @@ -171,7 +183,17 @@ public function run(?array $data = null, ?string $group = null, ?string $dbGroup
}
}

return $this->getErrors() === [];
if ($this->getErrors() === []) {
// Store data that was actually validated.
$this->validated = DotArrayFilter::run(
array_keys($this->rules),
$this->data
);

return true;
}

return false;
}

/**
Expand All @@ -188,6 +210,14 @@ public function check($value, string $rule, array $errors = []): bool
return $this->setRule('check', null, $rule, $errors)->run(['check' => $value]);
}

/**
* Returns actually validated data.
*/
public function getValidated(): array
{
return $this->validated;
}

/**
* Runs all of $rules against $field, until one fails, or
* all of them have been processed. If one fails, it adds
Expand Down Expand Up @@ -827,6 +857,7 @@ protected function splitRules(string $rules): array
public function reset(): ValidationInterface
{
$this->data = [];
$this->validated = [];
$this->rules = [];
$this->errors = [];
$this->customErrors = [];
Expand Down
183 changes: 183 additions & 0 deletions tests/system/Validation/DotArrayFilterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
<?php

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Validation;

use CodeIgniter\Test\CIUnitTestCase;

/**
* @internal
*
* @group Others
*/
final class DotArrayFilterTest extends CIUnitTestCase
{
public function testRunReturnEmptyArray()
{
$data = [];

$result = DotArrayFilter::run(['foo.bar'], $data);

$this->assertSame([], $result);
}

public function testRunReturnEmptyArrayMissingValue()
{
$data = [
'foo' => [
'bar' => 23,
],
];

$result = DotArrayFilter::run(['foo.baz'], $data);

$this->assertSame([], $result);
}

public function testRunReturnEmptyArrayEmptyIndex()
{
$data = [
'foo' => [
'bar' => 23,
],
];

$result = DotArrayFilter::run([''], $data);

$this->assertSame([], $result);
}

public function testRunEarlyIndex()
{
$data = [
'foo' => [
'bar' => 23,
],
];

$result = DotArrayFilter::run(['foo'], $data);

$this->assertSame($data, $result);
}

public function testRunWildcard()
{
$data = [
'foo' => [
'bar' => [
'baz' => 23,
],
],
];

$result = DotArrayFilter::run(['foo.*.baz'], $data);

$this->assertSame($data, $result);
}

public function testRunWildcardWithMultipleChoices()
{
$data = [
'foo' => [
'buzz' => [
'fizz' => 11,
],
'bar' => [
'baz' => 23,
],
],
];

$result = DotArrayFilter::run(['foo.*.fizz', 'foo.*.baz'], $data);

$this->assertSame($data, $result);
}

public function testRunNestedNotFound()
{
$data = [
'foo' => [
'buzz' => [
'fizz' => 11,
],
'bar' => [
'baz' => 23,
],
],
];

$result = DotArrayFilter::run(['foo.*.notthere'], $data);

$this->assertSame([], $result);
}

public function testRunIgnoresLastWildcard()
{
$data = [
'foo' => [
'bar' => [
'baz' => 23,
],
],
];

$result = DotArrayFilter::run(['foo.bar.*'], $data);

$this->assertSame($data, $result);
}

public function testRunNestedArray()
{
$array = [
'user' => [
'name' => 'John',
'age' => 30,
'email' => 'john@example.com',
'preferences' => [
'theme' => 'dark',
'language' => 'en',
'notifications' => [
'email' => true,
'push' => false,
],
],
],
'product' => [
'name' => 'Acme Product',
'description' => 'This is a great product!',
'price' => 19.99,
],
];

$result = DotArrayFilter::run([
'user.name',
'user.preferences.language',
'user.preferences.notifications.email',
'product.name',
], $array);

$expected = [
'user' => [
'name' => 'John',
'preferences' => [
'language' => 'en',
'notifications' => [
'email' => true,
],
],
],
'product' => [
'name' => 'Acme Product',
],
];
$this->assertSame($expected, $result);
}
}
Loading