<?php
namespace App\Listener\V2;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use App\Entity;
use App\Event;
/**
* Met à jour les meta data des utilisateurs avec les events custom de l'app
* Fais les majs des meta data avec des native query pour sortir du lifecycle
*/
class AppEventSubscriber implements EventSubscriberInterface
{
protected $mailjet;
public function __construct(\App\Service\Mailjet $mailjet)
{
$this->mailjet = $mailjet;
}
public static function getSubscribedEvents()
{
return [
Event\UserLoginEvent::NAME => ['onAppUserLogin', 0],
Event\UserActionEvent::NAME => ['onAppUserAction', 0],
Event\EmailSentEvent::NAME => ['onAppEmailSent', 0],
];
}
/**
* Quand un utilisateur se log (utilisé aussi quand il clique sur un lien)
*/
public function onAppUserLogin(Event\UserLoginEvent $event)
{
$em = $event->getEntityManager();
$user = $event->getUser();
if ($user instanceof Entity\User) {
$date = new \DateTime('now');
$date = $date->format('Y-m-d H:i:s');
$em->getConnection()->prepare("INSERT INTO user_meta_data
SET last_connection = '" . $date . "',
user_id = '" . $user->getId() . "'
ON DUPLICATE KEY UPDATE
last_connection = '" . $date . "'
")->execute();
// Mailetjet dernière connexion
$this->mailjet->updateContacts($user, [
'derniere_connexion' => time()
]);
}
}
/**
* Quand un utilisateur fait une action
*/
public function onAppUserAction(Event\UserActionEvent $event)
{
$em = $event->getEntityManager();
$user = $event->getUser();
$action = $event->getAction();
if ($user instanceof Entity\User) {
$date = new \DateTime('now');
$date = $date->format('Y-m-d H:i:s');
$em->getConnection()->prepare("INSERT INTO user_meta_data
SET last_action = '" . $action . "',
last_action_date = '" . $date . "',
user_id = '" . $user->getId() . "'
ON DUPLICATE KEY UPDATE
last_action = '" . $action . "',
last_action_date = '" . $date . "'
")->execute();
}
}
/**
* Quand un mail est reçu
*/
public function onAppEmailSent(Event\EmailSentEvent $event)
{
$em = $event->getEntityManager();
$dests = $event->getDests();
$subject = $event->getSubject();
$subject = addslashes($subject);
foreach ($dests as $email => $user) {
if ($user instanceof Entity\User) {
$date = new \DateTime('now');
$date = $date->format('Y-m-d H:i:s');
$em->getConnection()->prepare("INSERT INTO user_meta_data
SET last_received_email = '" . $subject . "',
last_received_email_date = '" . $date . "',
user_id = '" . $user->getId() . "'
ON DUPLICATE KEY UPDATE
last_received_email = '" . $subject . "',
last_received_email_date = '" . $date . "'
")->execute();
}
}
}
}