I need to get some data in my db and the current user, so I use the entity manager and security.context in my service
I have this error :
Fatal error: Call to a member function getRepository() on a non-object
in path/to/file on line 84
service.yml :
services:
ns_messagerie.letterboxcore:
class: ns\MessagerieBundle\LetterBoxCore\LetterBoxCore
arguments: [#security.context, #doctrine.orm.entity_manager]
Dependency injection :
class nsMessagerieExtension extends Extension
{
/**
* {#inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
}
And my service :
class LetterBoxCore {
protected $securityContext;
protected $em;
public function __construct( $securityContext, $entityManager) {
$this->securityContext = $securityContext;
$this->em = $entityManager;
}
public function countNbNotRead(Utilisateur $user = null, Discussion $discussions) {
//...
}
public function getAllDiscussion(Utilisateur $user = null, $all = null) {
// line 84:
$list = $em->getRepository('nsMessagerieBundle:ParticipantMessagerie')
->findBy(array('participant' => $user,
'supprimer' => $all
)
);
}
public function getBAL(Utilisateur $user = null) {
// Call the method countNbNotRead and GetAllDiscussion
}
Related
I've created an event subscriber that sends an email with Swiftmailer every time certain entity is updated but the event is triggered twice so i'm receiving email two times.
I've followed this guide and this one. The event is: easy_admin.pre_update
EasyAdminBundle version: 1.17.9
services.yml
app.easy_admin.aprobar_publicacion:
class: AppBundle\EventListener\AprobarPublicacionSubscriber
arguments: ['#mailer','#service_container','#twig']
tags:
- { name: kernel.event_subscriber, event: easy_admin.pre_update, method: preUpdate }
AprobarPublicacionSubscriber.php
<?php
namespace AppBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use AppBundle\Entity\VestidoDeNovia;
use AppBundle\Entity\PlantillaEmail;
class AprobarPublicacionSubscriber implements EventSubscriberInterface {
protected $mailer;
protected $container;
protected $twig;
public static function getSubscribedEvents() {
return array(
'easy_admin.pre_update' => array('preUpdate'),
);
}
public function __construct(\Swift_Mailer $mailer, \Symfony\Component\DependencyInjection\ContainerInterface $container, \Twig_Environment $twig) {
$this->mailer = $mailer;
$this->container = $container;
$this->twig = $twig;
}
public function preUpdate(GenericEvent $event) {
$entity = $event->getSubject();
if (!($entity instanceof VestidoDeNovia)) {
return;
}
$uow = $event->getArgument('em')->getUnitOfWork();
$uow->computeChangeSets();
$changeset = $uow->getEntityChangeSet($entity);
if (array_key_exists('estado', $changeset)) {
$estadoActual = $changeset['estado'][0]->getId();
if ($estadoActual != 2 and $entity->getEstado()->getId() == 2) {
$plantillaEmail = new PlantillaEmail();
$plantillaEmail = $event->getArgument('em')->getRepository(PlantillaEmail::class)->find(6);
$message = (new \Swift_Message($plantillaEmail->getAsunto()))
->setFrom($this->container->getParameter('direccion_mail_sistema'))
->setTo($entity->getUsuario()->getEmail())
->setBody(
$this->twig->render(
'AppBundle::Emails/publicacion_exitosa.html.twig', array(
'titulo' => $plantillaEmail->getAsunto(),
'mensaje' => $plantillaEmail->getMensaje(),
)
), 'text/html'
)
;
$this->mailer->send($message);
}
}
}
}
What am i missing?
I'm running phpunit tests on some classes and I get this error
Call to a member function getRepository() on null in
src/MyApp/MyBundle/CopyList.php on line 429
At that line is
$list = $this->em->getRepository('MyAppMyBundle:CopyList')->findByName($task);
from
namespace MyApp\MyBundle\Classes\Action;
use Symfony\Component\HttpFoundation\Session;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ParameterBag;
use MyApp\MyBundle\Entity\CopyVirtualList;
use Doctrine\ORM\EntityManager;
class CopyList extends Action
{
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function __clone() {
$task = $this->getTask();
$this->__copy($task);
}
public function __copy($task)
{
$list = $this->em->getRepository('MyAppMyBundle:CopyList')->findByName($task);
if (!$list) {
$list = new CopyVirtualList();
$this->em->persist($list);
$this->em->flush();
}
}
}
which is being called from the line
$clone = clone $container;
in
namespace tests\src\MyApp\MyBundle\Classes;
use Symfony\Component\HttpFoundation\Request;
abstract class TaskContextContainerTestCase extends TestCase
{
public function testCloning()
{
$container = $this->createInstance();
$container->setImmutable(true);
$this->assertTrue($container->isImmutable());
$clone = clone $container;
$this->assertNotEquals($container, $clone);
$this->assertFalse($clone->isImmutable());
}
protected function createInstance()
{
$task = $this->getMockBuilder('MyApp\MyBundle\Model\TaskContext')
->disableOriginalConstructor()
->getMockForAbstractClass();
$container = $task->createElement(
$this->getContainerKind(),
$this->getContainerType()
);
$container->setContext($task);
return $container;
}
}
TestCase is
namespace tests\src\MyApp\MyBundle;
use MyApp\Environment as Env;
require_once dirname(__DIR__) . '/../../../../app/AppKernel.php';
class TestCase extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
try {
$kernel = new \AppKernel('test', true);
$kernel->boot();
new \MyApp\Environment(); // init single env-instance
Env::getInstance()->setContainer($kernel->getContainer());
} catch (\Exception $e) {
}
parent::setUp();
}
}
And
namespace MyApp\MyBundle\Tests\Units\Classes\Action;
use MyApp\MyBundle\Classes\Action\CopyList;
use tests\src\MyApp\MyBundle\Classes\Action\ActionTestCase as TestCase;
class CopyListTest extends TestCase {
private $object;
public function setUp()
{
parent::setUp();
$task = $this->getMockBuilder('MyApp\MyBundle\Model\TaskContext')
->disableOriginalConstructor()
->getMock();
$this->object = new CopyList($task);
}
public function testCreateInstance() {
$task = $this->getMockBuilder('MyApp\MyBundle\Model\TaskContext')
->disableOriginalConstructor()
->getMockForAbstractClass();
$container = $task->createElement($this->getContainerKind(), $this->getContainerType());
$container->setContext($task);
return $container;
}
public function testCloning()
{
$container = $this->createInstance();
$container->setImmutable(true);
$this->assertTrue($container->isImmutable());
$clone = clone $container;
$this->assertNotEquals($container, $clone);
$this->assertFalse($clone->isImmutable());
}
}
Can anyone point me in the right direction?
i have problem with HWIOAuthBundle and google authentication, i can't complete work on OAuthProvider. After flush data, i want return entity object, that i saw example somewhere in stackoverflow.
But when i return $obj;
I catch error :
Catchable Fatal Error: Argument 2 passed to HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken::__construct() must be of the type array, integer given, called in /var/www/integra/vendor/hwi/oauth-bundle/Security/Core/Authentication/Provider/OAuthProvider.php on line 109 and defined
Construct this class :
public function __construct($accessToken, array $roles = array())
{
parent::__construct($roles);
$this->setRawToken($accessToken);
parent::setAuthenticated(count($roles) > 0);
}
Then i return:
return new JsonResponse(['accessToken' => $user->getToken(), 'Roles' => $user->getRoles()]); // I catch error what it loadUserByOAuthUserResponse() must return a UserInterface
class OAuthProvider extends OAuthUserProvider
{
protected $container, $em;
public function __construct(\Doctrine\ORM\EntityManager $em, $container)
{
$this->container = $container;
$this->em = $em;
}
public function loadUserByOAuthUserResponse(UserResponseInterface $response)
{
$email = $response->getEmail();
if ($email === null) {
throw new NotFoundHttpException("User email adress not found", 404);
}
$name = $response->getFirstName();
$surname = $response->getLastName();
$photo = $response->getProfilePicture();
$repository = $this->em->getRepository('IdamasBillingBundle:User');
$user = $repository->searchByNameSurnameEmail($email);
if($user){
$login = new User();
$login->setEmail($email);
$session = $this->container->get('session');
$session->set('login', $login);
return $user;
} else {
$user = new User();
$user->setEmail($email);
$user->setName($name);
$user->setSurname($surname);
$user->setPosition('Just user');
$user->setRoles(1);
$user->setPhoto($photo);
$this->em->persist($user);
$this->em->flush();
$session = $this->container->get('session');
$session->set('login', $user);
// return $user;f
return new JsonResponse(['accessToken' => $user->getToken(), 'Roles' => $user->getRoles()]);
}
//return new RedirectResponse("/billing");
}
}
How i can to do it, that redirect to complete login page?
User object should have roles property, and it must be an array:
class User {
protected $roles = [];
public function getRoles() {
return $this->roles;
}
public function addRole($role) {
$this->roles[] = $role;
}
}
How to render a template outside a controller or in a service?
I've been following the documentation of Symfony2. Doc
namespace Acme\HelloBundle\Newsletter;
use Symfony\Component\Templating\EngineInterface;
class NewsletterManager
{
protected $mailer;
protected $templating;
public function __construct(
\Swift_Mailer $mailer,
EngineInterface $templating
) {
$this->mailer = $mailer;
$this->templating = $templating;
}
// ...
}
This is where i call my helper :
$transport = \Swift_MailTransport::newInstance();
$mailer = \Swift_Mailer::newInstance($transport);
$helper = new MailHelper($mailer);
$helper->sendEmail($from, $to, $subject, $path_to_twig, $arr_to_twig);
So the first thing here missing is the second parameter of the construct method in :
$helper = new MailHelper($mailer);
But how would i instantiate the EngineInterface?
Of course it can't be :
new EngineInterface();
I'm totally lost here.
All what i need to do is render a template for the email that is being sent.
Inject only #twig and pass the rendered template to the mailer body:
<?php
namespace Acme\Bundle\ContractBundle\Event;
use Acme\Bundle\ContractBundle\Event\ContractEvent;
class ContractListener
{
protected $twig;
protected $mailer;
public function __construct(\Twig_Environment $twig, \Swift_Mailer $mailer)
{
$this->twig = $twig;
$this->mailer = $mailer;
}
public function onContractCreated(ContractEvent $event)
{
$contract = $event->getContract();
$body = $this->renderTemplate($contract);
$projectManager = $contract->getProjectManager();
$message = \Swift_Message::newInstance()
->setSubject('Contract ' . $contract->getId() . ' created')
->setFrom('noreply#example.com')
->setTo('dev#example.com')
->setBody($body)
;
$this->mailer->send($message);
}
public function renderTemplate($contract)
{
return $this->twig->render(
'AcmeContractBundle:Contract:mailer.html.twig',
array(
'contract' => $contract
)
);
}
}
I have successfully installed the sncRedisBundle and used the predis element of it within a controller, using:
$this->container->get('snc_redis.default');
I want to do the same within an extension:
class MyExtension extends Extension
{
/**
* {#inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$redis = $container->get('snc_redis.default');
}
}
But I get:
The service definition "snc_redis.default" does not exist.
Is this a scoping issue? How do I access redis from within an Extension?
Thanks!
services:
site:
class: Emlaktown\AppBundle\Site\Site
arguments: [%api_url%, "#request_stack", "#service_container"]
....
use Symfony\Component\DependencyInjection\Container;
....
public function __construct($apiUrl, RequestStack $requestStack, Container $container)
{
$this->client = new Client($apiUrl);
$this->redis = $container->get('snc_redis.cache');
$request = $requestStack->getCurrentRequest();
$this->client->setDefaultOption('Accept-Language', $request->getLocale());
}