serverBackup = $_SERVER; $this->getBackup = $_GET; $this->postBackup = $_POST; $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REQUEST_URI'] = '/test'; $_SERVER['DOCUMENT_ROOT'] = '/nonexistent-docroot'; unset($_SERVER['CONTENT_TYPE'], $_SERVER['HTTP_ACCEPT']); $_GET = []; $_POST = []; } protected function tearDown(): void { $_SERVER = $this->serverBackup; $_GET = $this->getBackup; $_POST = $this->postBackup; } #[Test] public function failedValidationThrowsWithHttp422Code(): void { $_SERVER['REQUEST_METHOD'] = 'POST'; $_POST = ['age' => '5']; $this->expectException(Exception::class); $this->expectExceptionMessage('The age must be at least 18.'); $this->expectExceptionCode(422); new class extends Request { public function rules(): array { return ['age' => 'required|min:18']; } }; } #[Test] public function messagesOverrideWinsForFailedRule(): void { $_SERVER['REQUEST_METHOD'] = 'POST'; $_POST = ['age' => '5']; $this->expectException(Exception::class); $this->expectExceptionMessage('Way too short'); new class extends Request { public function rules(): array { return ['age' => 'required|min:18']; } public function messages(): array { return ['age.min' => 'Way too short']; } }; } #[Test] public function attributesRenameTheFieldInDefaultMessage(): void { $_SERVER['REQUEST_METHOD'] = 'POST'; $_POST = ['age' => '5']; $this->expectException(Exception::class); $this->expectExceptionMessage('The applicant age must be at least 18.'); new class extends Request { public function rules(): array { return ['age' => 'required|min:18']; } public function attributes(): array { return ['age' => 'applicant age']; } }; } #[Test] public function getRulesFailureThrowsToo(): void { $this->expectException(Exception::class); $this->expectExceptionMessage('The q field is required.'); new class extends Request { public function getRules(): array { return ['q' => 'required']; } }; } #[Test] public function validDataDoesNotThrow(): void { $_SERVER['REQUEST_METHOD'] = 'POST'; $_POST = ['age' => '20']; $request = new class extends Request { public function rules(): array { return ['age' => 'required|min:18']; } }; $this->assertSame('20', $request->post->age); $this->assertSame('/test', $request->path); } }