Upgrade to Pro — share decks privately, control downloads, hide ads and more …

TDD視点から見る、Laravel・Requestクラスの依存性

stwile
February 22, 2021

 TDD視点から見る、Laravel・Requestクラスの依存性

stwile

February 22, 2021
Tweet

More Decks by stwile

Other Decks in Programming

Transcript

  1. όϦσʔγϣϯͷྫɿ class HogeRequest extends FormRequest { public function authorize(): bool

    { return true; } public function rules(): array { return [ 'name' => 'required|string|max:128', 'content' => 'required|string|max:500', ]; } public function attributes(): array { return ['name' => '໊લ','content' => '಺༰']; } protected function failedValidation(Validator $validator) { $errors = []; $validateErrors = $validator->errors()->toArray(); foreach ($validateErrors as $e) { $errors[] = $e[0]; } throw new HttpResponseException( response()->json($errors, 422) ); } } FormRequestΛܧঝ Α͋͘ΔFormRequestͷ֦ு • ೝূ • όϦσʔγϣϯϧʔϧͷఆٛ • όϦσʔγϣϯͰམͪͨͱ͖ͷ ڞ௨ॲཧ
  2. class HogeRequest extends FormRequest { public function authorize(): bool {

    return true; } public function rules(): array { return [ 'name' => 'required|string|max:128', 'content' => 'required|string|max:500', ]; } public function attributes(): array { return ['name' => '໊લ','content' => '಺༰']; } protected function failedValidation(Validator $validator) { $errors = []; $validateErrors = $validator->errors()->toArray(); foreach ($validateErrors as $e) { $errors[] = $e[0]; } throw new HttpResponseException( response()->json($errors, 422) ); } } ιʔείʔυͱςετίʔυͷྫ class HogeRequestTest extends TestCase { /** * @dataProvider dataProvider */ public function test(array $param, array, $expected): void { $request = new Request(); $actual = Validator::make( $params, $request->rules(), $request->messages() ) ->errors() ->all(); parent::assertSame($expected, $actual); } public function dataProvider(): array { return [ 'ඞਢܥ NG' => [ [], ['໊લ͕ඞਢͰ͢ɻ','಺༰͕ඞਢͰ͢ɻ'], ], ] } } ᶃ ᶄ ᶅ
  3. public function authorize(): bool { return true; } ιʔείʔυͱςετίʔυͷྫ ᶃ

    ੹຿ͷॏෳ ೝূͷ੹຿ͱόϦσʔγϣϯͷ੹຿͕ ڞଘ͍ͯ͠Δ ςετΫϥεͷจ຺͕ϒϨΔ → υΩϡϝϯτ📄ͱͯ͠ಡΈͮΒ͍😂 → ॻ͍͍ͯͯҧ࿨ײ͕ग़Δ
  4. ιʔείʔυͱςετίʔυͷྫ class HogeRequestTest extends TestCase { /** * @dataProvider dataProvider

    */ public function test(array $param, array, $expected): void { $request = new HogeRequest(); $actual = Validator::make( $params, $request->rules(), $request->messages() ) ->errors() ->all(); parent::assertSame($expected, $actual); } public function dataProvider(): array { return [ 'ඞਢܥ NG' => [ [], ['໊લ͕ඞਢͰ͢ɻ','಺༰͕ඞਢͰ͢ɻ'], ], ] } } ᶄ ෆཁͳґଘ ϧʔϧɾϝοηʔδͱ ࣮ߦͷॴࡏ͕ผΕ͍ͯΔ όϦσʔγϣϯ͚͍ͩͨ͠ͷʹɺ RequestΫϥεΛ ΠϯελϯεԽ͠ͳ͚Ε͹ͳΒͳ͍ → ΩϞνϫϧΠ🤮
  5. class HogeRequest extends FormRequest { protected function failedValidation( Validator $validator

    ) { $errors = []; $validateErrors = $validator->errors() ->toArray(); foreach ($validateErrors as $e) { $errors[] = $e[0]; } throw new HttpResponseException( response()->json($errors, 422) ); } } ιʔείʔυͱςετίʔυͷྫ ᶅ ϑϨʔϜϫʔΫґଘͷڧ͞ ϝοηʔδΛՃ޻͢ΔͨΊʹɺ ܧঝݩͷ࣮૷Λؾʹ͢Δ ϑϨʔϜϫʔΫ΁ͷଥڠ → ࣮૷ͷࣗ༝౓͕Լ͕Δ protected ͷϝιουͷςετ͸ॻ͖ͮΒ͍😇