Define associative array key

1

Consider this array:

protected $filter = [
    'preco' => 'required;double(1,4)',
    'email' => 'required;email'
];

Step by foreach:

protected function bootFilterPost() {

    foreach ($this->filter as $key => $value):
        $this->postRules[$key] = preg_split('/(;)/', $value);
    endforeach;

    var_dump($this->postRules);
}

and I have this output:

array(2) {
  ["preco"]=>
  array(2) {
    [0]=>
    string(8) "required"
    [1]=>
    string(11) "double(1,4)"
  }
  ["email"]=>
  array(2) {
    [0]=>
    string(8) "required"
    [1]=>
    string(5) "email"
  }
}

But it would need to come out this way:

array(2) {
  ["preco"]=>
  array(2) {
    ["required"]=>
    string(8) "true"
    ["double"]=>
    string(11) "1,4"
  }
  ["email"]=>
  array(2) {
    ["required"]=>
    string(8) "true"
    ["email"]=>
    string(5) "true"
  }
}

that is, I need the values to be entered as braces, and the braces must be in string ("true") or boolean (true);

    
asked by anonymous 05.10.2017 / 12:37

1 answer

1

Although you have not set all the rules that mattered, since the Laravel validations are quite comprehensive and allow for many other things you did not mention, such as unique , min , max , digits , etc ... I present you a possible solution.

This uses an auxiliary array of value mappings:

private $regras = [
    "required"=>true, 
    "email"=>true
];

If the value to be considered is in this array the mapping is applied directly, otherwise it tries to see if the value has some separation by (

double(1,4)

Or separation by :

digits:3

Doing their interpretation and application.

Example:

protected function bootFilterPost() {

    foreach ($this->filter as $key => $value):
        $arr = preg_split('/(;)/', $value);

        foreach ($arr as $a): //ver cada regra de validação do campo

            //ver se é um que faz parte do array de regras 
            if (array_key_exists ($a, $this->regras)): 
                $this->postRules[$key][$a] = $this->regras[$a];

            elseif (strpos($a, "(") !== false): //ver se tem (
                $split = explode("(", $a); //dividir pelo (
                $this->postRules[$key][$split[0]] = "(" . $split[1];

            elseif (strpos($a, ":") !== false): //ver se tem :
                $split = explode(":", $a); //dividir pelo :
                $this->postRules[$key][$split[0]] = $split[1]; 

            endif;


        endforeach;
    endforeach;

    var_dump($this->postRules);
}

Example on Ideone

    
05.10.2017 / 18:36