/** * @param ObjectManager $manager */ public function load(ObjectManager $manager) { $owner = $this->getReference('simple_user'); $calendar = $manager->getRepository('Oro\\Bundle\\CalendarBundle\\Entity\\Calendar')->findOneBy([]); $event = new CalendarEvent(); $event->setTitle('test_title')->setCalendar($calendar)->setAllDay(true)->setStart(new \DateTime('now -2 days', new \DateTimeZone('UTC')))->setEnd(new \DateTime('now', new \DateTimeZone('UTC'))); $emailTemplate1 = new EmailTemplate('no_entity_name', 'test {{ system.appFullName }} etc'); $emailTemplate1->setOrganization($owner->getOrganization()); $emailTemplate2 = new EmailTemplate('test_template', 'test {{ system.appFullName }} etc'); $emailTemplate2->setEntityName('Oro\\Bundle\\CalendarBundle\\Entity\\CalendarEvent'); $emailTemplate2->setOrganization($owner->getOrganization()); $emailTemplate3 = new EmailTemplate('no_system', 'test {{ system.appFullName }} etc'); $emailTemplate3->setIsSystem(false); $emailTemplate3->setEntityName('Entity\\Name'); $emailTemplate3->setOrganization($owner->getOrganization()); $emailTemplate4 = new EmailTemplate('system', 'test {{ system.appFullName }} etc'); $emailTemplate4->setIsSystem(true); $emailTemplate4->setEntityName('Entity\\Name'); $emailTemplate4->setOrganization($owner->getOrganization()); $emailTemplate5 = new EmailTemplate('no_system_no_entity', 'test {{ system.appFullName }} etc'); $emailTemplate5->setIsSystem(false); $emailTemplate5->setOrganization($owner->getOrganization()); $manager->persist($event); $manager->persist($emailTemplate1); $manager->persist($emailTemplate2); $manager->persist($emailTemplate3); $manager->persist($emailTemplate4); $manager->persist($emailTemplate5); $manager->flush(); $this->setReference('emailTemplate1', $emailTemplate1); $this->setReference('emailTemplate2', $emailTemplate2); $this->setReference('emailTemplate3', $emailTemplate3); $this->setReference('emailTemplate4', $emailTemplate4); $this->setReference('emailTemplate5', $emailTemplate5); }
/** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('entityName', 'hidden', ['attr' => ['data-default-value' => Email::ENTITY_CLASS], 'constraints' => [new Assert\Choice(['choices' => ['', Email::ENTITY_CLASS]])]])->add('type', 'choice', ['label' => 'oro.email.emailtemplate.type.label', 'multiple' => false, 'expanded' => true, 'choices' => ['html' => 'oro.email.datagrid.emailtemplate.filter.type.html', 'txt' => 'oro.email.datagrid.emailtemplate.filter.type.txt'], 'required' => true])->add('translations', 'oro_email_emailtemplate_translatation', ['label' => 'oro.email.emailtemplate.translations.label', 'locales' => $this->getLanguages(), 'labels' => $this->getLocaleLabels(), 'content_options' => ['constraints' => [new Assert\NotBlank()], 'attr' => ['data-default-value' => $this->cm->get('oro_email.signature', '')]], 'subject_options' => ['constraints' => [new Assert\NotBlank()]]])->add('visible', 'checkbox', ['label' => 'oro.email.autoresponserule.form.template.visible.label', 'required' => false]); $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { $form = $event->getForm(); if ($form->has('owner')) { $form->remove('owner'); } if (!$event->getData()) { $emailTemplate = new EmailTemplate(); $emailTemplate->setContent($this->cm->get('oro_email.signature', '')); $emailTemplate->setEntityName(Email::ENTITY_CLASS); $event->setData($emailTemplate); } }); $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) { $template = $event->getData(); if (!$template || $template->getName()) { return; } $proposedName = $template->getSubject(); while ($this->templateExists($proposedName)) { $proposedName .= rand(0, 10); } $template->setName($proposedName); }); }
/** * Process form * * @param EmailTemplate $entity * * @return bool True on successful processing, false otherwise */ public function process(EmailTemplate $entity) { // always use default locale during template edit in order to allow update of default locale $entity->setLocale($this->defaultLocale); if ($entity->getId()) { // refresh translations $this->manager->refresh($entity); } $this->form->setData($entity); if (in_array($this->request->getMethod(), array('POST', 'PUT'))) { // deny to modify system templates if ($entity->getIsSystem() && !$entity->getIsEditable()) { $this->form->addError(new FormError($this->translator->trans('oro.email.handler.attempt_save_system_template'))); return false; } $this->form->submit($this->request); if ($this->form->isValid()) { // mark an email template creating by an user as editable if (!$entity->getId()) { $entity->setIsEditable(true); } $this->manager->persist($entity); $this->manager->flush(); return true; } } return false; }
/** * @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 EmailTemplate $template * * @return Closure */ protected function createExistingEntityQueryBuilder(EmailTemplate $template) { return function (EmailTemplateRepository $repository) use($template) { $qb = $repository->createQueryBuilder('e'); return $qb->orderBy('e.name', 'ASC')->andWhere('e.entityName = :entityName OR e.entityName IS NULL')->andWhere("e.organization = :organization")->andWhere($qb->expr()->orX($qb->expr()->eq('e.visible', ':visible'), $qb->expr()->eq('e.id', ':id')))->setParameter('entityName', Email::ENTITY_CLASS)->setParameter('organization', $this->securityFacade->getOrganization())->setParameter('id', $template->getId())->setParameter('visible', true); }; }
/** * @return EmailTemplate */ protected function createTemplate() { $template = new EmailTemplate(); $translation = new EmailTemplateTranslation(); $translation->setLocale(self::LOCALE)->setField('type'); $translations = new ArrayCollection([$translation]); $template->setTranslations($translations); return $template; }
public function testAddingErrorToNonEditableSystemEntity() { $this->entity->setIsSystem(true); $this->entity->setIsEditable(false); $this->form->expects($this->once())->method('setData')->with($this->entity); $this->form->expects($this->once())->method('addError'); $this->request->setMethod('POST'); $this->translator->expects($this->once())->method('trans'); $this->assertFalse($this->handler->process($this->entity)); }
public function testValidateErrors() { $trans = new EmailTemplateTranslation(); $trans->setField('subject')->setContent(self::TEST_TRANS_SUBJECT); $this->template->setContent(self::TEST_CONTENT)->setSubject(self::TEST_SUBJECT)->getTranslations()->add($trans); $this->twig->expects($this->at(0))->method('render')->with(self::TEST_SUBJECT); $this->twig->expects($this->at(1))->method('render')->with(self::TEST_CONTENT); $this->twig->expects($this->at(2))->method('render')->with(self::TEST_TRANS_SUBJECT)->will($this->throwException(new \Exception())); $this->context->expects($this->once())->method('addViolation')->with($this->variablesConstraint->message); $this->validator->validate($this->template, $this->variablesConstraint); }
public function testCloneForSystemNonEditableTemplate() { $emailTemplate = new EmailTemplate(); $emailTemplate->setIsSystem(true); $emailTemplate->setIsEditable(false); $this->assertTrue($emailTemplate->getIsSystem()); $this->assertFalse($emailTemplate->getIsEditable()); $clone = clone $emailTemplate; $this->assertFalse($clone->getIsSystem()); $this->assertTrue($clone->getIsEditable()); }
/** * @param string $className * @return EmailTemplateSyntaxValidator */ protected function getValidator($className) { $this->template->setContent(self::TEST_CONTENT)->setSubject(self::TEST_SUBJECT)->setEntityName($className); $sandbox = $this->getMockBuilder('\\Twig_Extension_Sandbox')->disableOriginalConstructor()->getMock(); $sandbox->expects($this->once())->method('enableSandbox'); $sandbox->expects($this->once())->method('disableSandbox'); $this->twig->expects($this->once())->method('getExtension')->with($this->equalTo('sandbox'))->will($this->returnValue($sandbox)); $translator = $this->getMockBuilder('Symfony\\Component\\Translation\\Translator')->disableOriginalConstructor()->getMock(); $translator->expects($this->any())->method('trans')->will($this->returnArgument(0)); $validator = new EmailTemplateSyntaxValidator($this->twig, $this->localeSettings, $this->userConfig, $this->entityConfigProvider, $translator); $validator->initialize($this->context); return $validator; }
/** * @param ObjectManager $manager */ public function load(ObjectManager $manager) { $calendar = $manager->getRepository('Oro\\Bundle\\CalendarBundle\\Entity\\Calendar')->findOneBy([]); $event = new CalendarEvent(); $event->setTitle('test_title')->setCalendar($calendar)->setAllDay(true)->setStart(new \DateTime('now -2 days', new \DateTimeZone('UTC')))->setEnd(new \DateTime('now', new \DateTimeZone('UTC'))); $emailTemplate1 = new EmailTemplate('no_entity_name', 'test {{ system.appFullName }} etc'); $emailTemplate2 = new EmailTemplate('test_template', 'test {{ system.appFullName }} etc'); $emailTemplate2->setEntityName('Oro\\Bundle\\CalendarBundle\\Entity\\CalendarEvent'); $manager->persist($event); $manager->persist($emailTemplate1); $manager->persist($emailTemplate2); $manager->flush(); }
/** * {@inheritDoc} */ public function load(ObjectManager $manager) { $adminUser = $this->getAdminUser($manager); $organization = $this->getOrganization($manager); $emailTemplates = $this->getEmailTemplatesList($this->getEmailsDir()); foreach ($emailTemplates as $fileName => $file) { $template = file_get_contents($file['path']); $emailTemplate = new EmailTemplate($fileName, $template, $file['format']); $emailTemplate->setOwner($adminUser); $emailTemplate->setOrganization($organization); $manager->persist($emailTemplate); } $manager->flush(); }
/** * @dataProvider localeDataProvider * * @param string|null $defaultLocale * @param int|null $id * @param bool $expectedRefresh */ public function testShouldPresetDefaultLocale($defaultLocale, $id, $expectedRefresh) { $this->form->expects($this->once())->method('setData')->with($this->entity); $this->manager->expects($expectedRefresh ? $this->once() : $this->never())->method('refresh')->with($this->entity); $this->setEntityId($id); $this->handler->setDefaultLocale($defaultLocale); $this->handler->process($this->entity); $this->assertSame($defaultLocale, $this->entity->getLocale()); }
/** * REST GET email template * * @param EmailTemplate $emailTemplate comes from request parameter {id} * that transformed to entity by param converter * @param int $entityId entity id of class defined by $emailTemplate->getEntityName() * * @ApiDoc( * description="Get email template subject, type and content", * resource=true * ) * @AclAncestor("oro_email_emailtemplate_view") * @Get("/emailtemplates/compiled/{id}/{entityId}", * requirements={"id"="\d+", "entityId"="\d*"}, * name="oro_api_get_emailtemplate_compiled" * ) * @ParamConverter("emailTemplate", class="OroEmailBundle:EmailTemplate") * * @return Response */ public function getCompiledAction(EmailTemplate $emailTemplate, $entityId = null) { $templateParams = []; if ($entityId && $emailTemplate->getEntityName()) { $entity = $this->getDoctrine()->getRepository($emailTemplate->getEntityName())->find($entityId); if ($entity) { $templateParams['entity'] = $entity; } } // no entity found, but entity name defined for template if ($emailTemplate->getEntityName() && !isset($templateParams['entity'])) { return $this->handleView($this->view(['message' => sprintf('entity %s with id=%d not found', $emailTemplate->getEntityName(), $entityId)], Codes::HTTP_NOT_FOUND)); } list($subject, $body) = $this->get('oro_email.email_renderer')->compileMessage($emailTemplate, $templateParams); $data = ['subject' => $subject, 'body' => $body, 'type' => $emailTemplate->getType()]; return $this->handleView($this->view($data, Codes::HTTP_OK)); }
/** * Compile preview content * * @param EmailTemplate $entity * @param null|string $locale * * @return string */ public function compilePreview(EmailTemplate $entity, $locale = null) { $content = $entity->getContent(); if ($locale) { foreach ($entity->getTranslations() as $translation) { /** @var EmailTemplateTranslation $translation */ if ($translation->getLocale() === $locale && $translation->getField() === 'content') { $content = $translation->getContent(); } } } return $this->render('{% verbatim %}' . $content . '{% endverbatim %}', []); }
/** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Sender email and name is empty */ public function testFromEmpty() { $entity = new \stdClass(); $this->helper->expects($this->once())->method('getSingleEntityIdentifier')->will($this->returnValue(1)); $marketingList = new MarketingList(); $marketingList->setEntity($entity); $template = new EmailTemplate(); $template->setType('html'); $settings = new InternalTransportSettings(); $settings->setTemplate($template); $campaign = new EmailCampaign(); $campaign->setMarketingList($marketingList)->setTransportSettings($settings); $this->transport->send($campaign, $entity, [], []); }
/** * Compile preview content * * @param EmailTemplate $entity * * @return string */ public function compilePreview(EmailTemplate $entity) { // ensure we have no html tags in txt template $content = $entity->getContent(); $content = $entity->getType() == 'txt' ? strip_tags($content) : $content; $templateParams['user'] = $this->user; $templateRendered = $this->render('{% verbatim %}' . $content . '{% endverbatim %}', $templateParams); return $templateRendered; }
/** * @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()); }
/** * @return EmailTemplate */ protected function createEmailTemplate() { $template = new EmailTemplate(); $template->setName('test_name')->setSubject('Test Subject')->setContent('Test Body'); return $template; }
/** * Compile preview content * * @param EmailTemplate $entity * * @return string */ public function compilePreview(EmailTemplate $entity) { return $this->render('{% verbatim %}' . $entity->getContent() . '{% endverbatim %}', []); }