Skip to content

Instantly share code, notes, and snippets.

@msbrime
Created July 25, 2017 16:14
Show Gist options
  • Save msbrime/336a788c7cced2137bdc7896c1241239 to your computer and use it in GitHub Desktop.
Save msbrime/336a788c7cced2137bdc7896c1241239 to your computer and use it in GitHub Desktop.
A form request that trims the parameters that are sent to it
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
/**
* Description of AjaxValidatableFormRequest
*
* @author msalisu
*/
class TrimmedFormRequest extends FormRequest
{
/**
* Never trim these attributes on any request
*
* @var array
*/
private $dontTrim = ['_token','validate_only'];
/**
* Fields on request that should not be trimmed
* nested fields can be indicated with dot notation
* @example [ 'field1','field2.subfield' ]
*
* @var array
*/
protected $untrimmable = [];
/**
* @see Illuminate\Validation\ValidatesWhenResolvedTrait
*/
protected function prepareForValidation()
{
return $this->replace($this->trimData($this->all()));
}
/**
* Get data to be validated from the request.
*
* @return array
*/
protected function validationData()
{
return $this->all();
}
/**
* Trims data in request fields
*
* @param array $data
* @param string $keyPrefix indicates the current depth of the array
*/
protected function trimData($data,$keyPrefix = '')
{
$trimmedFields = array_map(function($value,$field) use ($keyPrefix){
// if the value is an array handle it as
// a request array and send along the prefix
if(is_array($value)){
return $this->trimData($value,$this->dotIndex($keyPrefix,$field));
}
// if the field is not in the specified fields to be
// left untrimmed
if(
!in_array($this->dotIndex($keyPrefix,$field),$this->dontTrim) &&
!in_array($this->dotIndex($keyPrefix,$field), $this->untrimmable)
) {
return trim((string) $value);
}
return $value;
}, $data,array_keys($data));
return array_combine(array_keys($data),$trimmedFields);
}
/**
* Resolves a dot index for an array value
* using a prefix and key to append
*
* @param string $prefix the prefix
* @param string $append the key to append
* @return string
*/
private function dotIndex($prefix,$append){
if(trim($prefix) == ''){
return trim($append);
}
return trim($prefix).'.'.trim($append);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment