jsonResponse = $jsonResponse; $this->jsonResponseData = $jsonResponseData; $this->webinarFactory = $webinarFactory; $this->repository = $repository; $this->request = $request; } protected function validate(){ $validateData = ['name', 'email', 'mobile', 'company']; $errors = []; foreach ($validateData as $item) { $this->request->setParam($item, trim($this->request->getParam($item))); if (!ValidatorChain::is($this->request->getParam($item), NotEmpty::class)) { $errors[] = $item.' 是必填项'; } } // if (!preg_match('/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/', $this->request->getParam('email'))) { // $errors[] = '请输入有效的邮箱'; // } return $errors; } /** * Execute view action * * @return ResultInterface */ public function execute() { $jsonResponse = $this->jsonResponse->create(); $errors = $this->validate(); if (!empty($errors)) { return $jsonResponse->setData($this->jsonResponseData->setErrors(true)->setData($errors)); } $message = null; try { try { $webinar = $this->repository->get($this->request->getParam('email'), 'email'); $id = $webinar->getId(); $webinar = $webinar->setData($this->request->getParams())->setId($id); } catch (NoSuchEntityException $exception) { $webinar = $this->webinarFactory->create()->setData($this->request->getParams()); } $this->repository->save($webinar); $error = false; } catch (LocalizedException $exception) { $error = true; $message = $exception->getMessage(); } return $jsonResponse->setData($this->jsonResponseData ->setErrors($error) ->setMessages([$message]) ); } public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException { $phrase = new Phrase('Invalid Form Key. Please refresh the page.'); $responseData = $this->jsonResponseData->setErrors(true)->setMessages([ $phrase->getText() ]); return new InvalidRequestException( $this->jsonResponse->create()->setData($responseData) ); } public function validateForCsrf(RequestInterface $request): ?bool { return true; } }