DusanKasan / Knapsack

Collection pipeline library for PHP

Home Page:http://dusankasan.github.io/Knapsack/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Return composed string

roukmoute opened this issue · comments

I've tried to convert this:

$errors = '';
foreach ($validator->errors() as $field => $keyErrors) {
    $errors .= "Field \"$field\" must be follow theses rules:" . PHP_EOL;
    foreach ($keyErrors as $rule) {
        $error .= " $rule" . PHP_EOL;
    }
}

return $errors;

So I wrote this:

$errors = '';

(new Collection($this->validator->errors()))
    ->each(
        function (array $rules, string $field) use (&$errors) {
            $errors .= "Field \"$field\" must be follow theses rules:" . PHP_EOL;
            (new Collection($rules))
                ->each(
                    function (string $rule) use (&$errors) {
                        $errors .= " - $rule" . PHP_EOL;
                    }
                )
                ->toArray()
            ;
        }
    )
    ->toArray()
;

return $errors;

It works perfectly, but it is a little bit complicated, have you better idea?

I'm not by my computer, but something like this should work:

$errors = Collection::from($validator->errors())
	->map(function($keyErrors, $field) {
		return Collection:from($keyErrors)
			->prepend("Field \"$field\" must be follow theses rules:")
			->interpose(PHP_EOL)
			->toString()
	})
	->interpose(PHP_EOL)
	->toString()	

Thanks again !
What do you think about to do a tutorial?

Well I can put something together, maybe put some questions/answers from github issues together and add my own examples. Will think about it :) Thanks for the idea.