Created
July 16, 2018 14:17
-
-
Save sasin91/7dc2fdcb50af0afdbc1e75c8c796093d to your computer and use it in GitHub Desktop.
Strip invalid nested values from data validated in a form request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Requests; | |
use function array_dot; | |
use function fnmatch; | |
use Illuminate\Support\Arr; | |
use Illuminate\Support\Collection; | |
use Illuminate\Support\Str; | |
trait RemovesInvalidNestedValues | |
{ | |
/** | |
* Get the validated data from the request. | |
* | |
* @return array | |
*/ | |
public function validated() | |
{ | |
$validated = parent::validated(); | |
return $this->removeInvalidNestedValues($validated); | |
} | |
/** | |
* Remove invalid nested values from the validated. | |
* | |
* @see https://stackoverflow.com/a/46006808 | |
* @param array $validated | |
* @return array | |
*/ | |
private function removeInvalidNestedValues(array $validated) | |
{ | |
$original = array_dot($validated); | |
Collection::make($this->rules()) | |
->keys() | |
->filter(function ($rule) { | |
return Str::contains($rule, '.'); | |
})->each(function ($rule) use ($original, &$filtered) { | |
foreach ($original as $dotIndex => $element) { | |
//fnmatch respects wildcard asterisks | |
if (fnmatch($rule, $dotIndex)) { | |
//array_set respects dot-notation, building out a normal array | |
Arr::set($filtered, $dotIndex, $element); | |
} | |
} | |
}); | |
return $filtered; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment