xtremer360
6 months ago
99
10
Laravel

Checking Keys for an Associate Array Form Request

Posted 6 months ago by xtremer360

What I'm trying to do is check that all the keys that get passed inside of the competitors array are valid keys. What should be accepted is wrestlers for now but I know that will change later on. Does anyone have a better way to write that check what is valid?

The rules that I am wanting to account for is the following.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreMatchesRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'matches' => ['required', 'array'],
            'matches.*' => ['required', 'array'],
            'matches.*.competitors' => ['required', 'array'],
            'matches.*.competitors.*' => ['required', 'array'],
        ];

        return $rules;
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            foreach ($this->matches as $key => $match) {
                $type = MatchType::find($match['match_type_id']);

                if ($type === null) {
                    continue;
                }

                if ($match['competitors'] === null || !is_array($match['competitors'])) {
                    continue;
                }

                foreach ($match['competitors'] as $side => $competitorType) {
                    if (array_intersect(array_keys($competitorType), ['wrestlers']) !== array_keys($competitorType)) {
                        $validator->errors()->add("matches.{$key}.competitors.*", 'Something is wrong with this field!');
                    }
                }

                if (!$this->matchHasCorrectSidesCount($match, $type)) {
                    $validator->errors()->add("matches.{$key}.competitors", 'Something is wrong with this field!');
                }

                if (!$this->matchHasCorrectCompetitorCount) {
                    $validator->errors()->add("matches.{$key}.competitors", 'Something is wrong with this field!');
                }
            }
        });
    }
}
return array_replace([
    'matches' => [
        [
            'match_type_id' => $matchType->getKey(),
            'competitors' => [
                [
                    'wrestlers' => [$wrestlers[0]->getKey()],
                ],
                [
                    'wrestlers' => [$wrestlers[1]->getKey()],
                ],
           ],
            'preview' => 'This is an example match preview.',
        ],
    ]
], $overrides);

Please sign in or create an account to participate in this conversation.