protected function initializeRequestAttributes(Request $request, $master) { if ($master) { // set the context even if the parsing does not need to be done // to have correct link generation $context = new RequestContext($request->getBaseUrl(), $request->getMethod(), $request->getHost(), $request->getScheme(), $request->isSecure() ? $this->httpPort : $request->getPort(), $request->isSecure() ? $request->getPort() : $this->httpsPort); if ($session = $request->getSession()) { $context->setParameter('_locale', $session->getLocale()); } $this->router->setContext($context); } if ($request->attributes->has('_controller')) { // routing is already done return; } // add attributes based on the path info (routing) try { $parameters = $this->router->match($request->getPathInfo()); if (null !== $this->logger) { $this->logger->info(sprintf('Matched route "%s" (parameters: %s)', $parameters['_route'], $this->parametersToString($parameters))); } $request->attributes->add($parameters); } catch (ResourceNotFoundException $e) { $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo()); if (null !== $this->logger) { $this->logger->err($message); } throw new NotFoundHttpException($message, $e); } catch (MethodNotAllowedException $e) { $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod(), $request->getPathInfo(), strtoupper(implode(', ', $e->getAllowedMethods()))); if (null !== $this->logger) { $this->logger->err($message); } throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e); } if ($master && ($locale = $request->attributes->get('_locale'))) { $request->getSession()->setLocale($locale); $context->setParameter('_locale', $locale); } }
public function testUrlWithGlobalParameter() { $routes = $this->getRoutes('test', new Route('/testing/{foo}')); $generator = $this->getGenerator($routes); $context = new RequestContext('/app.php'); $context->setParameter('foo', 'bar'); $generator->setContext($context); $url = $generator->generate('test', array()); $this->assertEquals('/app.php/testing/bar', $url); }
public function testGlobalParameterHasHigherPriorityThanDefault() { $routes = $this->getRoutes('test', new Route('/{_locale}', array('_locale' => 'en'))); $generator = $this->getGenerator($routes); $context = new RequestContext('/app.php'); $context->setParameter('_locale', 'de'); $generator->setContext($context); $url = $generator->generate('test', array()); $this->assertSame('/app.php/de', $url); }
public function testSetParameter() { $requestContext = new RequestContext(); $requestContext->setParameter('foo', 'bar'); $this->assertEquals('bar', $requestContext->getParameter('foo')); }
/** * @dataProvider getGenerateThrowsExceptionFixtures * @expectedException Symfony\Component\Routing\Exception\RouteNotFoundException */ public function testGenerateThrowsException($locale, $host, $route) { $router = $this->getNonRedirectingHostMapRouter(); $context = new RequestContext(); $context->setParameter('_locale', $locale); $context->setHost($host); $router->setContext($context); $router->generate($route); }
public function testSendTestEmailAction() { if (null !== static::$kernel) { static::$kernel->shutdown(); } try { static::$kernel = static::createKernel(array()); } catch (\RuntimeException $ex) { $this->markTestSkipped("There does not seem to be a full application available (e.g. running tests on travis.org). So this test is skipped."); return; } static::$kernel->boot(); $container = static::$kernel->getContainer(); $spoolDir = $container->getParameter('swiftmailer.spool.defaultMailer.file.path'); // delete all spooled mails from other tests array_map('unlink', glob($spoolDir . "/*.messag*")); array_map('unlink', glob($spoolDir . "/.*.messag*")); $context = new RequestContext('/app.php'); $context->setParameter('_locale', 'en'); $router = $container->get('router'); $router->setContext($context); $to = md5(time() . "to") . '@email.non-existent.to.mail.domain.com'; $uri = $router->generate("azine_email_send_test_email", array('template' => AzineTemplateProvider::NEWSLETTER_TEMPLATE, 'email' => $to)); $container->set('request', Request::create($uri, "GET")); // "login" a user $token = new UsernamePasswordToken("username", "password", "main"); $recipientProvider = $container->get('azine_email_recipient_provider'); $users = $recipientProvider->getNewsletterRecipientIDs(); $token->setUser($recipientProvider->getRecipient($users[0])); $container->get('security.context')->setToken($token); // instantiate the controller and try to send the email $controller = new AzineEmailTemplateController(); $controller->setContainer($container); $response = $controller->sendTestEmailAction(AzineTemplateProvider::NEWSLETTER_TEMPLATE, $to); $this->assertEquals(302, $response->getStatusCode(), "Status-Code 302 expected."); $uri = $router->generate("azine_email_template_index"); $this->assertContains("Redirecting to {$uri}", $response->getContent(), "Redirect expected."); $findInFile = new FindInFileUtil(); $findInFile->excludeMode = false; $findInFile->formats = array(".message"); $this->assertEquals(1, sizeof($findInFile->find($spoolDir, "This is just the default content-block."))); $this->assertEquals(1, sizeof($findInFile->find($spoolDir, "Add some html content here"))); }
/** * (non-PHPdoc) * @see Azine\EmailBundle\Services.TemplateTwigSwiftMailerInterface::sendEmail() * @param array $failedRecipients * @param string $subject * @param String $from * @param String $fromName * @param array|String $to * @param String $toName * @param array|String $cc * @param String $ccName * @param array|String $bcc * @param String $bccName * @param $replyTo * @param $replyToName * @param array $params * @param $template * @param array $attachments * @param null $emailLocale * @param \Swift_Message $message * @return int */ public function sendEmail(&$failedRecipients, $subject, $from, $fromName, $to, $toName, $cc, $ccName, $bcc, $bccName, $replyTo, $replyToName, array $params, $template, $attachments = array(), $emailLocale = null, \Swift_Message &$message = null) { // create the message if ($message == null) { $message = \Swift_Message::newInstance(); } $message->setSubject($subject); // set the from-Name & -Emali to the default ones if not given if ($from == null) { $from = $this->noReplyEmail; } if ($fromName == null) { $fromName = $this->noReplyName; } // add the from-email for the footer-text if (!array_key_exists('fromEmail', $params)) { $params['sendMailAccountName'] = $this->noReplyName; $params['sendMailAccountAddress'] = $this->noReplyEmail; } // get the baseTemplate. => templateId without the ending. $templateBaseId = substr($template, 0, strrpos($template, ".", -6)); // check if this email should be stored for web-view if ($this->templateProvider->saveWebViewFor($templateBaseId)) { // keep a copy of the vars for the web-view $webViewParams = $params; // add the web-view token $params[$this->templateProvider->getWebViewTokenId()] = SentEmail::getNewToken(); } else { $webViewParams = array(); } // recursively add all template-variables for the wrapper-templates and contentItems $params = $this->templateProvider->addTemplateVariablesFor($templateBaseId, $params); // recursively attach all messages in the array $this->embedImages($message, $params); // change the locale for the email-recipients if ($emailLocale !== null && strlen($emailLocale) > 0) { $currentUserLocale = $this->translator->getLocale(); // change the router-context locale $this->routerContext->setParameter("_locale", $emailLocale); // change the translator locale $this->translator->setLocale($emailLocale); } else { $emailLocale = $this->translator->getLocale(); } // recursively add snippets for the wrapper-templates and contentItems $params = $this->templateProvider->addTemplateSnippetsWithImagesFor($templateBaseId, $params, $emailLocale); // add the emailLocale (used for web-view) $params['emailLocale'] = $emailLocale; // render the email parts $twigTemplate = $this->loadTemplate($template); $textBody = $twigTemplate->renderBlock('body_text', $params); $message->addPart($textBody, 'text/plain'); $htmlBody = $twigTemplate->renderBlock('body_html', $params); $campaignParams = $this->templateProvider->getCampaignParamsFor($templateBaseId, $params); if (sizeof($campaignParams) > 0) { $htmlBody = $this->emailTwigExtension->addCampaignParamsToAllUrls($htmlBody, $campaignParams); } // if email-tracking is enabled if ($this->emailOpenTrackingCodeBuilder) { // add an image at the end of the html tag with the tracking-params to track email-opens $imgTrackingCode = $this->emailOpenTrackingCodeBuilder->getTrackingImgCode($templateBaseId, $campaignParams, $params, $message->getId(), $to, $cc, $bcc); if ($imgTrackingCode && strlen($imgTrackingCode) > 0) { $htmlCloseTagPosition = strpos($htmlBody, "</body>"); $htmlBody = substr_replace($htmlBody, $imgTrackingCode, $htmlCloseTagPosition, 0); } } $message->setBody($htmlBody, 'text/html'); // remove unused/unreferenced embeded items from the message $message = $this->removeUnreferecedEmbededItemsFromMessage($message, $params, $htmlBody); // change the locale back to the users locale if (isset($currentUserLocale) && $currentUserLocale != null) { $this->routerContext->setParameter("_locale", $currentUserLocale); $this->translator->setLocale($currentUserLocale); } // add attachments foreach ($attachments as $fileName => $file) { // add attachment from existing file if (is_string($file)) { // check that the file really exists! if (file_exists($file)) { $attachment = \Swift_Attachment::fromPath($file); if (strlen($fileName) >= 5) { $attachment->setFilename($fileName); } } else { throw new FileException("File not found: " . $file); } // add attachment from generated data } else { $attachment = \Swift_Attachment::newInstance($file, $fileName); } $message->attach($attachment); } // set the addresses if ($from) { $message->setFrom($from, $fromName); } if ($replyTo) { $message->setReplyTo($replyTo, $replyToName); } elseif ($from) { $message->setReplyTo($from, $fromName); } if ($to) { $message->setTo($to, $toName); } if ($cc) { $message->setCc($cc, $ccName); } if ($bcc) { $message->setBcc($bcc, $bccName); } // add custom headers $this->templateProvider->addCustomHeaders($templateBaseId, $message, $params); // send the message $mailer = $this->getMailer($params); $messagesSent = $mailer->send($message, $failedRecipients); // if the message was successfully sent, // and it should be made available in web-view if ($messagesSent && array_key_exists($this->templateProvider->getWebViewTokenId(), $params)) { // store the email $sentEmail = new SentEmail(); $sentEmail->setToken($params[$this->templateProvider->getWebViewTokenId()]); $sentEmail->setTemplate($templateBaseId); $sentEmail->setSent(new \DateTime()); // recursively add all template-variables for the wrapper-templates and contentItems $webViewParams = $this->templateProvider->addTemplateVariablesFor($template, $webViewParams); // replace absolute image-paths with relative ones. $webViewParams = $this->templateProvider->makeImagePathsWebRelative($webViewParams, $emailLocale); // recursively add snippets for the wrapper-templates and contentItems $webViewParams = $this->templateProvider->addTemplateSnippetsWithImagesFor($template, $webViewParams, $emailLocale, true); $sentEmail->setVariables($webViewParams); // save only successfull recipients if (!is_array($to)) { $to = array($to); } $successfulRecipients = array_diff($to, $failedRecipients); $sentEmail->setRecipients($successfulRecipients); // write to db $em = $this->managerRegistry->getManager(); $em->persist($sentEmail); $em->flush($sentEmail); $em->clear(); gc_collect_cycles(); } return $messagesSent; }
public function testMatch() { $router = $this->getRouter(); $router->setHostMap(array('en' => 'en.test', 'de' => 'de.test', 'fr' => 'fr.test')); $this->assertEquals(array('_controller' => 'foo', '_route' => 'welcome'), $router->match('/welcome')); $context = new RequestContext('', 'GET', 'en.test'); $context->setParameter('_locale', 'en'); $router->setContext($context); $this->assertEquals(array('_controller' => 'foo', '_locale' => 'en', '_route' => 'welcome'), $router->match('/welcome-on-our-website')); $this->assertEquals(array('_controller' => 'JMS\\I18nRoutingBundle\\Controller\\RedirectController::redirectAction', 'path' => '/willkommen-auf-unserer-webseite', 'host' => 'de.test', 'permanent' => true, 'scheme' => 'http', 'httpPort' => 80, 'httpsPort' => 443, '_route' => 'welcome'), $router->match('/willkommen-auf-unserer-webseite')); }