I have problems with paypal calling the notification function, i think i have everything set up correctly, however there is little documentation available about this
use Maxim\CMSBundle\Entity\NotificationDetails;
use Payum\Action\ActionInterface;
use Payum\Request\NotifyTokenizedDetailsRequest;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Maxim\CMSBundle\Entity\Visitor;
class StoreNotificationAction implements ActionInterface
{
protected $doctrine;
protected $logger;
public function __construct(RegistryInterface $doctrine, $logger) {
$this->doctrine = $doctrine;
$this->logger = $logger;
}
/**
* {#inheritDoc}
*/
public function execute($request)
{
/** #var NotifyTokenizedDetailsRequest $request */
$this->logger->err("hi");
$notification = new NotificationDetails;
$notification->setPaymentName($request->getTokenizedDetails()->getPaymentName());
$notification->setDetails($request->getNotification());
$notification->setCreatedAt(new \DateTime);
$this->doctrine->getManager()->persist($notification);
$this->doctrine->getManager()->flush();
}
/**
* {#inheritDoc}
*/
public function supports($request)
{
return $request instanceof NotifyTokenizedDetailsRequest;
}
}
which i am calling with a service defined in services.yml and also this is my configuration according to the git example:
payum:
contexts:
paypal_express_checkout_plus_doctrine:
paypal_express_checkout_nvp:
api:
options:
username: 'MYUSER'
password: 'MYPAS'
signature: 'MYSIGNATURE'
sandbox: true
actions:
- myname.action.store_notification
storages:
myname\mybundle\Entity\PaypalExpressPaymentDetails:
doctrine:
driver: orm
payment_extension: true
myname\mybundle\Entity\TokenizedDetails:
doctrine:
driver: orm
payment_extension: true
Please check you correctly setup NOTIFY_URL. For this you have to generate tokenForNotifyRoute and use its targetUrl as notify. See an example of prepareAction in the sandbox.
Related
it is going to be lengthy post, I encountering weird behavior where I see in profiler that one entity managers is said to map entity that it does not map. It looks like this:
Here is doctrine.yaml:
doctrine:
dbal:
default_connection: default
connections:
default:
driver: "pdo_mysql"
host: "127.0.0.1"
port: "3306"
dbname: "example"
user: "root"
password: ""
charset: utf8mb4
server_version: "mariadb-10.4.10"
logs:
driver: "pdo_mysql"
host: "127.0.0.1"
port: "3306"
dbname: "example_logs"
user: "root"
password: ""
charset: utf8mb4
server_version: "mariadb-10.4.10"
orm:
auto_generate_proxy_classes: true
default_entity_manager: default
entity_managers:
default:
query_cache_driver:
type: pool
pool: apcu.default.cache.pool
metadata_cache_driver:
type: pool
pool: apcu.default.cache.pool
result_cache_driver:
type: pool
pool: apcu.default.cache.pool
connection: default
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
mappings:
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity/Main'
prefix: 'App\Entity\Main'
alias: App
logs:
query_cache_driver:
type: pool
pool: apcu.default.cache.pool
metadata_cache_driver:
type: pool
pool: apcu.default.cache.pool
result_cache_driver:
type: pool
pool: apcu.default.cache.pool
connection: logs
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
mappings:
LogBundle:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity/Logs'
prefix: 'App\Entity\Logs'
alias: App
And here is framework.yaml with cache pool configuration:
framework:
secret: '%env(APP_SECRET)%'
session:
handler_id: null
cookie_secure: auto
cookie_samesite: lax
php_errors:
log: true
cache:
pools:
apcu.default.cache.pool:
adapter: cache.adapter.apcu
apcu.logs.cache.pool:
adapter: cache.adapter.apcu
If I remove metadata_cache_driver configuration from logs entity_manager configuration, or change it to use different cache pool (apcu.logs.cache.pool) than default entity manager then profiler reports correct mappings (Example entity in default em and logs em is empty).
The issue occurs only when entity is feed trough form and $form->handleRequest() handles it, creating or modifying entity without forms does not cause such issue. Here is my controller:
<?php
namespace App\Controller;
use App\Entity\Main\Example;
use App\Form\Type\ExampleType;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class ExampleController extends AbstractController {
/**
* #Route("/example1")
* #Template
*/
public function example1(EntityManagerInterface $em){
$example = new Example();
$example->setValue('example value');
try {
$em->persist($example);
$em->flush();
} catch(\Exception $e){
return new Response('An error has occurred. '.$e->getMessage());
}
return [];
}
/**
* #Route("/example2")
* #Template
*/
public function example2(EntityManagerInterface $em){
$example = $em->getRepository(Example::class)->find(1);
if(!$example){
return new Response('No example found.');
}
$example->setValue(mt_rand(0, mt_getrandmax()));
try {
$em->flush();
} catch(\Exception $e){
return new Response('An error has occurred. '.$e->getMessage());
}
return [];
}
/**
* #Route("/example3")
* #Template
*/
public function example3(Request $request, EntityManagerInterface $em){
$example = $em->getRepository(Example::class)->find(1);
if(!$example){
return new Response('No example found.');
}
$form = $this->createForm(ExampleType::class, $example);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$em->flush();
}
return ['form' => $form->createView()];
}
}
example1 and example2 routes DOES NOT cause issue, only example3 does and only when the form is submitted, so only when I enter example3 url, then click submit form only then when enter profiler for this request I can see the issue.
My minimal reproduction example was to create new symfony LTS project symfony new example-site --version=lts --full
Then these are files that I have changed since:
Databases are created by symfony console doctrine:database:create --connection=default and symfony console doctrine:database:create --connection=logs then tables are created by symfony console doctrine:migrations:diff --em=default and symfony console doctrine:migrations:migrate --em=default
Here is code for other files I haven't yet included in post:
<?php
//src/Entity/Main/Example.php
namespace App\Entity\Main;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class Example {
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $value;
public function getId(){
return $this->id;
}
public function getValue(){
return $this->value;
}
public function setValue(string $value){
$this->value = $value;
}
}
<?php
//src/Form/Type/ExampleType.php
namespace App\Form\Type;
use App\Entity\Main\Example;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ExampleType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options){
$builder->add('value', TextType::class);
$builder->add('submit', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver){
$resolver->setDefaults([
'data_class' => Example::class,
]);
}
}
<!-- template/s/example/example1.html.twig -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
Example1
</body>
</html>
<!-- template/s/example/example2.html.twig -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
Example2
</body>
</html>
<!-- template/s/example/example3.html.twig -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
{{ form(form) }}
</body>
</html>
Last thing I want to add is that in other project this issue is more visible, because when entity has reference to other entity an error is reported (on non-owning side in One-to-Many self-referencing association):
In this case Item entity is the one feed trough form.
For those who are curious here is Item.php:
But I don't know how would it matter as it is not managed by logs entity manager and should not appear under. default entity manager who is managing the entity is not reporting any issues with it.
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="App\Repository\ItemRepository")
* #ORM\Table(indexes={
* #ORM\Index(name="item_image", columns={"image"})
* })
*/
class Item {
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=32)
* #Assert\NotBlank()
* #Assert\Length(min=3, max=32)
*/
private $name;
/**
* #ORM\Column(type="string")
*/
private $description = '';
/**
* #ORM\Column(type="string", length=25, nullable=true)
*/
private $image;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Item", mappedBy="container")
*/
private $items;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Item", inversedBy="items")
* #ORM\JoinColumn(name="container", referencedColumnName="id")
* #var $container Item
*/
private $container;
/**
* #ORM\OneToMany(targetEntity="App\Entity\TagItem", mappedBy="item")
* #var $tags TagItem[]
*/
private $tags;
/**
* #Assert\Image(mimeTypes="image/jpeg")
* #var $imageFile null|UploadedFile
*/
private $imageFile;
public function __construct() {
$this->items = new \Doctrine\Common\Collections\ArrayCollection();
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getId(){
return $this->id;
}
public function getName(){
return $this->name;
}
public function setName(string $name){
$this->name = $name;
}
public function getDescription(){
return $this->description;
}
public function setDescription($description){
$this->description = $description;
}
public function hasImage(){
return isset($this->image);
}
public function getImage(){
return $this->image;
}
public function setImage($image){
$this->image = $image;
}
public function hasImageFile(){
return isset($this->imageFile);
}
public function getImageFile(){
return $this->imageFile;
}
public function setImageFile($imageFile){
$this->imageFile = $imageFile;
}
public function getItems(){
return $this->items;
}
public function hasContainer(){
return isset($this->container);
}
public function getContainer(){
return $this->container;
}
public function setContainer(?Item $container){
return $this->container = $container;
}
public function getTags(){
return $this->tags;
}
public function setTags($tags){
$this->tags = $tags;
}
}
PHP version is 7.3.12 and hosted with symfony serve
I got back on github in issue thread from fancyweb who said:
Status: reviewed
The bug is unrelated to the WebProfilerBundle. The reason is that you use the same cache salt for the 2 entity managers. At some places, we blindly call getClassMetadata() on both EM sequentially (ie: DoctrineLoader, DoctrineExtractor). The first call on the rightful EM populates the cache. The second call on the EM that should not know the class hits the cache and thus considers the class as loaded.
Using the same cache is fine, you just need to use different salts.
And when asked how if there is option in configuration to set salt for for entity manager I got answer from stof:
The clean way to achieve that is to use 2 separate cache pools, as FrameworkBundle takes the pool name into account for the seed to isolate keys from each pool when they share the same storage.
I've got two services, those get Doctrine injected via the constructor. When loading an entity in an EventListener and giving it ot service the entity is detached.
When im providing the DoctrineEntityManager from an EventListener to service, the entity is still managed.
class Listener implements EventSubscriberInterface
{
/** #var EntityManagerInterface */
private $em;
/** #var Service */
private $service;
/** #var EventDispatcherInterface */
private $eventDispatcher;
public function __construct(
EntityManagerInterface $em,
Service $service,
EventDispatcherInterface $eventDispatcher
) {
$this->em = $em;
$this->eventDispatcher = $eventDispatcher;
$this->service = $service;
}
public function listenerFunction(Event $event)
{
$user = $event->getEntity()->getUser();
var_dump($this->em->contains($user)); // true
$this->service->func($this->em, $user);
}
}
class Service
{
/** #var EventDispatcherInterface */
private $eventDispatcher;
public function __construct(EntityManagerInterface $em, EventDispatcherInterface $eventDispatcher)
{
$this->em = $em;
$this->eventDispatcher = $eventDispatcher;
}
public function func($em, $user)
{
var_dump($this->em->contains($user)); // false
var_dump($em->contains($user)); // true
}
}
the services yaml
services:
_defaults:
autowire: true
autoconfigure: true
public: true
App\Payment\Command\:
resource: "%kernel.project_dir%/src/Payment/Command/*"
tags:
- { name: console.command }
App\Payment\Service\:
resource: "%kernel.project_dir%/src/Payment/Service/*"
App\Payment\Controller\:
resource: "%kernel.project_dir%/src/Payment/Controller/*"
App\Payment\EventSubscriber\:
resource: "%kernel.project_dir%/src/Payment/EventSubscriber/*"
tags:
- { name: kernel.event_subscriber }
The EntityManager in the service should contain the $user entity. Im thinking symfony is creating a second instance of the entitymanagerinterface here, but the says there is only one instance of each item (https://symfony.com/doc/current/service_container/shared.html)
Fixed by updating all packages (composer update) yay ;D
I am trying to override the FosUserBundle Registry Controller, but the following error appears:
Cannot autowire service "App\Controller\RegistrationController": argument "$formFactory" of method
"FOS\UserBundle\Controller\RegistrationController::__construct()"
references interface "FOS\UserBundle\Form\Factory\FactoryInterface" but no such service exists.
You should maybe alias this interface to one of these existing services: "fos_user.profile.form.factory", "fos_user.registration.form.factory", "fos_user.change_password.form.factory",
"fos_user.resetting.form.factory". Did you create a class that implements this interface?
I'm using Symfony4 and this is my RegistrationController.php code.
I've tried multiple ways, but I can't find a way to make it work.
class RegistrationController extends BaseController
{
public function registerAction(Request $request)
{
$form = $this->get('fos_user.registration.form.factory');
$formHandler = $this->get('fos_user.registration.form.handler');
$confirmationEnabled = $this->getParameter('fos_user.registration.confirmation.enabled');
die("Hello");
$process = $formHandler->process($confirmationEnabled);
if ($process) {
$user = $form->getData();
if ($confirmationEnabled) {
$this->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
$route = 'fos_user_registration_check_email';
} else {
// $this->authenticateUser($user);
$route = 'users_edit';
}
$this->setFlash('fos_user_success', 'registration.flash.user_created');
$url = $this->get('router')->generate($route, array("id" => $user->id));
return new RedirectResponse($url);
}
return $this->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.twig', array(
'form' => $form->createView()
));
}
}
?>
I had the same problem , with SF4 and FOSUserBundle. After looking around for half a day I come with a solution. I use some material from #thibaut and adapt it to SF 4.2.
I inject the services needed by fos user registration controlleur and give FOS\UserBundle\Form\Factory\FactoryInterface an alias
config/services.yaml
app.controller.register:
class: App\Controller\bundles\FOSUserBundle\RegistrationController
arguments:
$eventDispatcher: '#event_dispatcher'
$formFactory: '#fos_user.registration.form.factory'
$userManager: '#fos_user.user_manager'
$tokenStorage: 'security.token_storage'
calls:
- method: setContainer
arguments:
- '#service_container'
public: true
FOS\UserBundle\Form\Factory\FactoryInterface:
alias: 'fos_user.registration.form.factory'
public: true
Then in my registration controller, I redeclare a constructor and save formfactory to be use in the controller
App\Controller\bundles\FOSUserBundle
protected $formFactory;
public function __construct(EventDispatcherInterface $eventDispatcher, FactoryInterface $formFactory, UserManagerInterface $userManager, TokenStorageInterface $tokenStorage, $serviceContainer=null)
{
$this->setContainer($serviceContainer);
$this->formFactory = $formFactory;
parent::__construct($eventDispatcher, $formFactory, $userManager, $tokenStorage);
}
use the declare $formfactory in my action
/**
* #Route("/register", name="registration")
*/
public function registerAction(Request $request)
{
/** #var $formFactory FactoryInterface */
$formFactory = $this->formFactory;
/** #var $userManager UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** #var $dispatcher EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
Hope it also help you guys
work in symfony 4.2
services.yaml
App\Controller\RegistrationController:
arguments:
$formFactory: '#fos_user.registration.form.factory'
and controller
use FOS\UserBundle\Controller\RegistrationController as Base;
class RegistrationController extends Base
{
private $eventDispatcher;
private $formFactory;
private $userManager;
private $tokenStorage;
public function __construct(EventDispatcherInterface $eventDispatcher, FactoryInterface $formFactory, UserManagerInterface $userManager, TokenStorageInterface $tokenStorage)
{
parent::__construct($eventDispatcher, $formFactory,$userManager, $tokenStorage);
$this->eventDispatcher = $eventDispatcher;
$this->formFactory = $formFactory;
$this->userManager = $userManager;
$this->tokenStorage = $tokenStorage;
}
I don't know which version of FOSUserBundle are you using but there is no official support for sf4 yet - see release notes. You can try dev-master version and follow this issue to make it work.
You should use hooks and avoid override controllers in FOSUserBundel v2.x
More information you can read on the page: http://symfony.com/doc/master/bundles/FOSUserBundle/controller_events.html
I had to use an alias for the FOS services that were refusing to autowire in my config/services.yaml
FOS\UserBundle\Form\Factory\FormFactory: '#fos_user.registration.form.factory'
As seen in vendor/friendsofsymfony/user-bundle/Resources/config/registration.xml
Hello i think i have found a way to handle this problem:
Define your service:
app.controller.register:
class: AppBundle\Controller\RegisterController
arguments: ['#service_container']
public: true
then your controller
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
/**
* #Route(service="app.controller.register")
*/
class RegisterController extends BaseController
{
public function __construct($serviceContainer=null)
{
$this->setContainer($serviceContainer);
$eventDispatcher=$this->container->get('event_dispatcher');
$formFactory=$this->container->get('fos_user.registration.form.factory');
$userManager=$this->container->get('fos_user.user_manager');
$tokenStorage=$this->container->get('security.token_storage');
parent::__construct($eventDispatcher, $formFactory, $userManager, $tokenStorage);
}
/**
* #Route("/register", name="register")
*/
public function registerAction(Request $request)
{
//do your stuff
}
}
hope this help (sorry for bad english)
To solve this issue in an override:
Do a full override of the FOSUserBundle RegistrationController i.e. copy its entire contents to AppBundle/Controller/RegistrationController.php
Then replace the __construct function with the below:
public function __construct() {
$this->eventDispatcher = $this->get('event_dispatcher');
$this->formFactory = $this->get('fos_user.registration.form.factory');
$this->userManager = $this->get('fos_user.user_manager');
$this->tokenStorage = $this->get('security.token_storage'); }
Voila! You are just calling these services in the constructor instead of passing them in as parameters in a registration controller service.
I did this now & it works for sf3.4.
I had the same problem , with SF4, FOSUserBundle (behind SonataAdmin).
I wanted listen an event : Registration confirmed, to send a message to the admininstrator.
my first try : override the FosUser controller. But the issues are many !
Thanks to #majne, I went to http://symfony.com/doc/master/bundles/FOSUserBundle/controller_events.html, and, even I am not in 'master', that works, hooking the event, from FOS\UserBundle\FOSUserEvents class.
I had some problems to cleary adapt the use statements...
With Symfony 4.2 the following should work.
Contrary to what is suggested in other answers, there was no need to extend the corresponding FOSUserBundle controller or modify the __construct method.
/config/services.yaml
FOS\UserBundle\Form\Factory\FactoryInterface: '#fos_user.registration.form.factory'
In my case I actually overrode both the RegistrationController and the ResettingController and in that case one needs to wire both forms - and also the MailerInterface - as so:
/config/services.yaml
FOS\UserBundle\Form\Factory\FactoryInterface: '#fos_user.resetting.form.factory'
FOS\UserBundle\Mailer\MailerInterface: '#fos_user.mailer.default'
App\Controller\RegistrationController:
autowire: true
arguments:
$formFactory: '#fos_user.registration.form.factory'
I had the same problem and I solve it by making "fos_user.resetting.form.factory" public
#fos_user.yaml
services:
new_service_name:
alias: fos_user.registration.form.factory
public: true
Then use the service with the new name
$form = $this->get('new_service_name');
I have a problem with Events in Symfony. I do not understand how way it works. This is my Listener:
class ClientVisitedListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return
[
KernelEvents::REQUEST => 'sprawdz',
];
}
My service.yml
anderos_invoice.invoice_club_listener:
class: Anderos\AcpPriceBundle\EventListener\InvoiceClubListener
arguments: [#service_container]
tags:
- { name: kernel.event_subscriber }
In all system, I have not any dispatcher. How does it work?
Where is the start of this procedure? Maybe in Kernel?
Could you help me to understand that procedure?
This is the key to understand what's happening here:
tags:
- { name: kernel.event_subscriber }
When the container is being compiled, it uses compiler passes. Compiler pass is an object which, at the time of compilation, gets ContainerBuilder as an argument and can do something with it. For example iterate over all services, check if they have a tag (kernel.event_subscriber in this case) and if so, do something with it.
In this case there is such compiler pass which takes all services having kernel.event_subscriber tag and adds them into EventDispatcher, which already exists in Symfony core (so yes, you have an event dispatcher, although you may not know about it).
That's how it knows which services need to be called when an event occurs - when it happens, the EventDispatcher instance already has registered all listeners/subscribers and simply call them.
When an event happens, then listener that is subscribed to this event will execute some code. Here is how I implemented it.
my service.yml:
app.listener.bot.logger:
class: AppBundle\Listener\BotLoggerListener
arguments: ['#logger']
tags:
- { name: monolog.logger, channel: bot }
- { name: kernel.event_listener, event: bot.log.message, method: 'onBotMessage' }
in my controller:
$event = new BotLogMessage('Request finish ');
$this->get('event_dispatcher')->dispatch($event::NAME, $event);
the listener:
namespace AppBundle\Listener;
use AppBundle\Event\BotLogRequestEvent;
use AppBundle\Event\BotLogResponseEvent;
use AppBundle\Event\BotLogMessage;
use Psr\Log\LoggerInterface;
class BotLoggerListener
{
private $logger;
/**
* BotLoggerListener constructor.
* #param LoggerInterface $logger
*/
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* #param BotLogMessage $event
*/
public function onBotMessage(BotLogMessage $event)
{
$this->logger->info('[Log Message] : ' . $event->getMessage());
}
}
the event class:
namespace AppBundle\Event;
use AppBundle\Model\BotRequest\BotRequestInterface;
use Symfony\Component\EventDispatcher\Event;
class BotLogMessage extends Event
{
const NAME = 'bot.log.message';
/**
* #var string
*/
private $message;
/**
* #param string $message
*/
public function __construct($message)
{
$this->message = $message;
}
/**
* #return string
*/
public function getMessage() : string
{
return $this->message;
}
}
I have done some custom exception listener, so in database in table I have got old url which is now 404 error and another url to which user should be redirected when it will get to the old url. The problem is that everything is working fine on DEV environment but I have got problem to get it working on PROD environment (it is throwing 503 Service Unavailable Error).
Does anyone may know what can be wrong?
services.yml:
services:
coupons.exception.action_listener:
class: Coupons\WebBundle\EventListener\ExceptionListener
arguments: [#service_container, #templating]
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
ExecptionListener:
namespace Coupons\WebBundle\EventListener;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Bundle\TwigBundle\TwigEngine;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class ExceptionListener
{
/**
* #var ContainerInterface
*/
protected $container;
/**
* #var TwigEngine
*/
protected $templating;
/**
* #param ContainerInterface $container
*/
public function __construct(ContainerInterface $container, TwigEngine $templating){
// assign value(s)
$this->container = $container;
$this->templating = $templating;
}
/**
*
* #param GetResponseForExceptionEvent $event
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
// get exception
$exception = $event->getException();
// get path
$path = $event->getRequest()->getPathInfo();
$url = $event->getRequest()->getUri();
$repository = $this->container->get('doctrine')->getRepository('CouponsWebBundle:SeoNotFound');
$seonotfound = $repository->createQueryBuilder('s')
->where('s.urlFrom LIKE :url')
->andWhere('s.status = 1')
->setParameter('url', $url.'%')
->getQuery()
->getOneOrNullResult();
if($seonotfound != NULL){
$event->setResponse(new RedirectResponse($seonotfound->getUrlTo(),$seonotfound->getRedirectType()));
}
}
}
Probably you're getting another exception in your exception listener, check symfony's log file.