Upgrading to Symfony 2.1 broke WebTestCase functional test sessions - symfony

in 2.0 the code below worked correctly, since upgrading to 2.1 the session var is going MIA.
public function __construct()
{
$this->client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'unittest#test.com',
'PHP_AUTH_PW' => 'test',
));
//set the session
$this->container = $this->client->getContainer();
$this->client->getCookieJar()->set(new \Symfony\Component\BrowserKit\Cookie(session_name(), true));
$this->session = $this->container->get('session');
$this->session->set('company_id', '9999');
$this->session->save();
}
public function testGetClientsAction()
{
$this->client->request(
'GET',
'/clients',
array(),
array(),
array('HTTP_X-Requested-With' => 'XMLHttpRequest', 'HTTP_accept' => 'application/json')
);
$content = $this->client->getResponse()->getContent();
$status = $this->client->getResponse()->getStatusCode();
$this->assertNotEmpty($content);
$this->assertEquals(200, $status);
}

Related

auto-responder with login details in Symfony

Here is the funcion im using
public function sendCredentialsEmailMessage(UserInterface $user)
{
$template = 'Emails/afterRegister.html.twig';
$rendered = $this->templating->render($template, array(
'user' => $user,
));
$this->sendEmailMessage($rendered,
$this->parameters['from_email']['confirmation'], $user->getEmail());
}
Basically I want the auto-mailer to send my template along with the login name. When i create a new user nothing is being sent. My email template is located in app>resources>views>emails>
and this controller file is located in src>myname>userbundle>mailer>
protected function sendEmailMessage($renderedTemplate, $fromEmail, $toEmail)
{
// Render the email, use the first line as the subject, and the rest as the body
$renderedLines = explode("\n", trim($renderedTemplate));
$subject = array_shift($renderedLines);
$body = implode("\n", $renderedLines);
$message = (new \Swift_Message())
->setSubject($subject)
->setFrom($fromEmail)
->setTo($toEmail)
->setBody($body);
$this->mailer->send($message);
}
Also this works for sure:
public function sendResettingEmailMessage(UserInterface $user)
{
$template = $this->parameters['resetting.template'];
$url = $this->router->generate('fos_user_resetting_reset', array('token' => $user->getConfirmationToken()),
UrlGeneratorInterface::ABSOLUTE_URL);
$rendered = $this->templating->render($template, array(
'user' => $user,
'confirmationUrl' => $url,
));
$this->sendEmailMessageCustom($rendered, $this->from, (string)$user->getEmail(),'Password resseting');
}

You have requested a non-existent service "knp_snappy.pdf"

I followed the tutorial on https://github.com/KnpLabs/KnpSnappyBundle and https://ourcodeworld.com/articles/read/250/how-to-create-a-pdf-from-html-using-knpsnappybundle-wkhtmltopdf-in-symfony-3.
app/config/config.yml
knp_snappy:`enter code here`
pdf:
enabled: true
binary: /usr/local/bin/wkhtmltopdf
options: []
image:
enabled: true
binary: /usr/local/bin/wkhtmltoimage
options: []
app/AppKernel
new Knp\Bundle\SnappyBundle\KnpSnappyBundle(),
MyController
use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
public function pdfAction(string $offerId)
{
$html = $this->renderView('#App/Offer/offer_pdf.html.twig', array(
'offerId' => $offerId
));
return new PdfResponse(
$this->get('knp_snappy.pdf')->getOutputFromHtml($html),
'file.pdf'
);
}
I try and this:
public function offerToPDFAction(string $offerId)
{
$snappy = $this->container->get('knp_snappy.pdf');
$html = '<h1>Hello</h1>';
$filename = 'myFirstSnappyPDF';
return new Response(
$snappy->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="'.$filename.'.pdf"'
)
);
The same problem:
You have requested a non-existent service "knp_snappy.pdf".
/**
* #Route("/{id}/pdf", name="sandbox_pdf", methods={"GET"})
*/
public function pdfAction(\Knp\Snappy\Pdf $snappy, Product $product): Response
{
$html = $this->renderView('pdf/index.html.twig', [
'product' => $product,
]);
$filename = 'product';
return new Response(
$snappy->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'.pdf"'
)
);
}
use Knp\Snappy\Pdf;
use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
/**
* #Route("/show/pdf/{token}", name="admin_invoice_show_pdf", methods={"GET"})
*/
public function showPdf(Command $command, Pdf $pdf)
{
$html = $this->renderView('admin/invoice/showPdf.html.twig',array('command' $command));
return new PdfResponse($pdf->getOutputFromHtml($html), 'invoice.pdf');
}

Functional Testing in Symfony

I am new in testing.I want to test my function.I have successfully installed phpUnit. I check many tutorials on internet.But I could not get the proper information regarding testing. Here is the my function code:
public function loginAction(Request $request)
{
$session = $this->getRequest()->getSession();
if( $session->get('userId') && $session->get('userId') != '' && $session->get('type') == '2')
{
//if user is login then it will be redirect to login page
return $this->redirect($this->generateUrl('registrarGeneral_dashboard'));
}
$em = $this->getDoctrine()->getEntityManager();
$repository = $em->getRepository('DRPAdminBundle:User');
if ($request->getMethod() == 'POST')
{
$session->clear();
$userName = $request->get('username');
$password = md5($request->get('password'));
//find email, password type and status of User
$user = $repository->findOneBy(array('username' => $userName, 'password' => $password,'type'=>2,'status'=>1 ));
$userEmail = $repository->findOneBy(array('email' => $userName, 'password' => $password,'type'=>2,'status'=>1 ));
if ($user)
{
//set session of User login
$session->set('userId', $user->getId());
$session->set('type', 2);
$session->set('nameRegistrar', $user->getFirstName());
$session->set('pictureRegistrar', $user->getPicture());
//echo "<pre>";print_r($session->get('picture'));die;
return $this->redirect($this->generateUrl('registrarGeneral_dashboard'));
}
if ($userEmail)
{
$session->set('type', 2);
$session->set('userId', $userEmail->getId());
$session->set('nameRegistrar', $userEmail->getFirstName());
$session->set('pictureRegistrar', $userEmail->getPicture());
//echo "<pre>";print_r($session->get('picture'));die;
return $this->redirect($this->generateUrl('registrarGeneral_dashboard'));
}
else
{
return $this->render('DRPRegistrarGeneralBundle:Pages:login.html.twig', array('name' => 'Invalid Email/Password'));
}
}
return $this->render('DRPRegistrarGeneralBundle:Pages:login.html.twig');
}
how to test this function? Please help
I don't know what you want to test but here is an exemple of what you can do to test user fonctionnalities :
public function testUserPageDown()
{
$client = static::createClient();
$client->request('GET', '/user/login');
$this->assertTrue($client->getResponse()->isSuccessful());
$client->request('GET', '/user/register');
$this->assertTrue($client->getResponse()->isSuccessful());
}
public function testUserFirewall()
{
$client = static::createClient();
//Trying go to user routes without being logged
$client->request('GET', '/user/profile');
$this->assertTrue($client->getResponse()->isRedirect());
$client->request('GET', '/user/profile/edit');
$this->assertTrue($client->getResponse()->isRedirect());
$client->request('GET', '/user/profile/editpassword');
$this->assertTrue($client->getResponse()->isRedirect());
}
public function testUserFormRegister()
{
$client = static::createClient();
$crawler = $client->request('GET', '/user/register');
$buttonCrawlerNode = $crawler->selectButton('submit_user_register');
$form = $buttonCrawlerNode->form();
$testForm = array(
'wineot_databundle_user[username]' => 'test',
'wineot_databundle_user[firstname]' => 'test',
'wineot_databundle_user[lastname]' => 'test',
'wineot_databundle_user[mail]' => 'test#mail.fr',
'wineot_databundle_user[plain_password][first]' => 'blabla321',
'wineot_databundle_user[plain_password][second]' => 'blabla321'
);
$response = $client->getResponse();
$client->submit($form, $testForm);
//If the submit is true that mean that the register is ok
$this->assertTrue($response->isSuccessful());
}
I hope that will help you do undestand how to test.

JMSPaymentPaypalBundle blank order summary

hi i was wondering on how to show order summary in paypal with JMSPaymentPaypalBundle ?!
ay tips will be greatly appreciated ..
here is my paypalController code in case needed
<?php
namespace Splurgin\EventsBundle\Controller;
use JMS\DiExtraBundle\Annotation as DI;
use JMS\Payment\CoreBundle\Entity\Payment;
use JMS\Payment\CoreBundle\PluginController\Result;
use JMS\Payment\CoreBundle\Plugin\Exception\ActionRequiredException;
use JMS\Payment\CoreBundle\Plugin\Exception\Action\VisitUrl;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\RedirectResponse;
class PaymentController
{
/** #DI\Inject */
private $request;
/** #DI\Inject */
private $router;
/** #DI\Inject("doctrine.orm.entity_manager") */
private $em;
/** #DI\Inject("payment.plugin_controller") */
private $ppc;
/**
* #DI\Inject("service_container")
*
*/
private $container;
/**
* #Template
*/
public function detailsAction($package)
{
// note this ticket at this point in inactive ...
$order = $this->container->get('ticket')->generateTicket($package);
$order = $this->em->getRepository('SplurginEventsBundle:SplurginEventTickets')->find($order);
$packageId = $order->getPackageId();
$package = $this->em->getRepository('SplurginEventsBundle:SplurginEventPackages')->find($package);
$price = $package->getPrice();
var_dump($price);
if($price == null){
throw new \RuntimeException('Package was not found: '.$result->getReasonCode());
}
$form = $this->getFormFactory()->create('jms_choose_payment_method', null, array(
'amount' => $price,
'currency' => 'USD',
'default_method' => 'payment_paypal', // Optional
'predefined_data' => array(
'paypal_express_checkout' => array(
'return_url' => $this->router->generate('payment_complete', array(
'order' => $order->getId(),
), true),
'cancel_url' => $this->router->generate('payment_cancel', array(
'order' => $order->getId(),
), true)
),
),
));
if ('POST' === $this->request->getMethod()) {
$form->bindRequest($this->request);
if ($form->isValid()) {
$this->ppc->createPaymentInstruction($instruction = $form->getData());
$order->setPaymentInstruction($instruction);
$this->em->persist($order);
$this->em->flush($order);
return new RedirectResponse($this->router->generate('payment_complete', array(
'order' => $order->getId(),
)));
}
}
return array(
'form' => $form->createView(),
'order'=>$order->getId(),
);
}
/** #DI\LookupMethod("form.factory") */
protected function getFormFactory() { }
/**
*/
public function completeAction($order)
{
$order = $this->em->getRepository('SplurginEventsBundle:SplurginEventTickets')->find($order);
$instruction = $order->getPaymentInstruction();
if (null === $pendingTransaction = $instruction->getPendingTransaction()) {
$payment = $this->ppc->createPayment($instruction->getId(), $instruction->getAmount() - $instruction->getDepositedAmount());
} else {
$payment = $pendingTransaction->getPayment();
}
$result = $this->ppc->approveAndDeposit($payment->getId(), $payment->getTargetAmount());
if (Result::STATUS_PENDING === $result->getStatus()) {
$ex = $result->getPluginException();
if ($ex instanceof ActionRequiredException) {
$action = $ex->getAction();
if ($action instanceof VisitUrl) {
return new RedirectResponse($action->getUrl());
}
throw $ex;
}
} else if (Result::STATUS_SUCCESS !== $result->getStatus()) {
throw new \RuntimeException('Transaction was not successful: '.$result->getReasonCode());
}
}
public function cancelAction($order)
{
die('cancel the payment');
}
}
i really dont know why this is not a part of the docs , but the bundle is capable of setting checkout parameters out of the box ...
here is how i have done it
$form = $this->getFormFactory()->create('jms_choose_payment_method', null, array(
'amount' => $price,
'currency' => 'USD',
'default_method' => 'payment_paypal', // Optional
'predefined_data' => array(
'paypal_express_checkout' => array(
'return_url' => $this->router->generate('payment_complete', array(
'order' => $order->getId(),
), true),
'cancel_url' => $this->router->generate('payment_cancel', array(
'order' => $order->getId(),
), true),
'checkout_params' => array(
'L_PAYMENTREQUEST_0_NAME0' => 'event',
'L_PAYMENTREQUEST_0_DESC0' => 'some event that the user is trying to buy',
'L_PAYMENTREQUEST_0_AMT0'=> 6.00, // if you get 10413 , then visit the api errors documentation , this number should be the total amount (usually the same as the price )
// 'L_PAYMENTREQUEST_0_ITEMCATEGORY0'=> 'Digital',
),
),
),
));
error code can be found here
SetExpressCheckout Request Fields here
i will provide a pull request to the documentation as soon as i can .. :)

symfony 2 , pagination

I'm just started working with Symfony2 and I have some problems with Pagination.
I have this code in my Account class:
public function indexAction($page)
{
$session = $this->get('session');
if ($session->get('valid')=='true') {
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ProjectCRMBundle:Account')->findAll();
$user = new Account();
$form = $this->container->get('form.factory')->create(new AccountType());
$total = $this->getDoctrine()->getRepository('ProjectCRMBundle:Account')->createQueryBuilder('p')->getQuery()->getResult();
/* total of résultat */
$total_users = count($total);
$users_per_page = 1;
$last_page = ceil($total_users / $users_per_page);
$previous_page = $page > 1 ? $page - 1 : 1;
$next_page = $page < $last_page ? $page + 1 : $last_page;
/* résultat à afficher*/
$entities = $this->getDoctrine()->getRepository('ProjectCRMBundle:Account')->createQueryBuilder('p')->setFirstResult(($page * $users_per_page) - $users_per_page)->setMaxResults(1)->getQuery()->getResult();
return $this->render('ProjectCRMBundle:Account:index.html.twig', array(
'entities' => $entities,
'last_page' => $last_page,
'previous_page' => $previous_page,
'current_page' => $page,
'next_page' => $next_page,
'total_users' => $total_users,
'form' => $form->createView(),
'user' => $user,
));
return $this->render('ProjectCRMBundle:Account:index.html.twig');
} else {
return $this->redirect($this->generateUrl('user_login'));
}
}
/**
* Creates a new Account entity.
*
*/
public function createAction(Request $request)
{
$entity = new Account();
$form = $this->createForm(new AccountType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('account_show', array('id' => $entity->getId())));
}
return $this->render('ProjectCRMBundle:Account:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
without forgetting the path on account.yml
account:
pattern: /{page}
defaults: { _controller: "ProjectCRMBundle:Account:index" , page: 1 }
At first look, it seems to work, but after trying to add a new account, I got this message:
LIMIT argument offset=-1 is not valid
Can anyone solve my problem?

Resources