/** * @param EmailTemplate $value * @param Constraint|EmailTemplateSyntax $constraint */ public function validate($value, Constraint $constraint) { // prepare templates to be validated $itemsToValidate = [['field' => 'subject', 'locale' => null, 'template' => $value->getSubject()], ['field' => 'content', 'locale' => null, 'template' => $value->getContent()]]; $translations = $value->getTranslations(); foreach ($translations as $trans) { if (in_array($trans->getField(), ['subject', 'content'])) { $itemsToValidate[] = ['field' => $trans->getField(), 'locale' => $trans->getLocale(), 'template' => $trans->getContent()]; } } /** @var \Twig_Extension_Sandbox $sandbox */ $sandbox = $this->twig->getExtension('sandbox'); $sandbox->enableSandbox(); // validate templates' syntax $errors = []; foreach ($itemsToValidate as &$item) { try { $this->twig->parse($this->twig->tokenize($item['template'])); } catch (\Twig_Error_Syntax $e) { $errors[] = ['field' => $item['field'], 'locale' => $item['locale'], 'error' => $e->getMessage()]; } } $sandbox->disableSandbox(); // add violations for found errors if (!empty($errors)) { foreach ($errors as $error) { $this->context->addViolation($constraint->message, ['{{ field }}' => $this->getFieldLabel(ClassUtils::getClass($value), $error['field']), '{{ locale }}' => $this->getLocaleName($error['locale']), '{{ error }}' => $error['error']]); } } }
/** * @param EmailModel $emailModel * @param EmailTemplate $template * @param Email $email */ protected function applyTemplate(EmailModel $emailModel, EmailTemplate $template, Email $email) { $locales = array_merge($email->getAcceptedLocales(), [$this->defaultLocale]); $flippedLocales = array_flip($locales); $translatedSubjects = []; $translatedContents = []; foreach ($template->getTranslations() as $translation) { switch ($translation->getField()) { case 'content': $translatedContents[$translation->getLocale()] = $translation->getContent(); break; case 'subject': $translatedSubjects[$translation->getLocale()] = $translation->getContent(); break; } } $comparator = ArrayUtil::createOrderedComparator($flippedLocales); uksort($translatedSubjects, $comparator); uksort($translatedContents, $comparator); $validContents = array_intersect_key($translatedContents, $flippedLocales); $validsubjects = array_intersect_key($translatedSubjects, $flippedLocales); $content = reset($validContents); $subject = reset($validsubjects); $emailModel->setSubject($subject === false ? $template->getSubject() : $subject)->setBody($content === false ? $template->getContent() : $content)->setType($template->getType()); }