deblan.tv/vendor/trinity/src/Trinity/Bundle/NotificationBundle/Notifier/BasicNotifier.php
2016-06-20 11:37:14 +02:00

109 lines
2.4 KiB
PHP

<?php
namespace Trinity\Bundle\NotificationBundle\Notifier;
use Symfony\Component\Security\Core\SecurityContextInterface;
class BasicNotifier extends AbstractNotifier
{
protected $securityContext;
protected $twig;
protected $user;
public function __construct(SecurityContextInterface $securityContext, \Twig_Environment $twig)
{
$this->securityContext = $securityContext;
$this->twig = clone $twig;
$this->twig->setLoader(new \Twig_Loader_String());
}
public function setSecurityContext(SecurityContextInterface $securityContext)
{
$this->securityContext = $securityContext;
return $this;
}
public function getSecurityContext()
{
return $this->securityContext;
}
public function setTwig(\Twig_Environment $twig)
{
$this->twig = $twig;
return $this;
}
public function getTwig()
{
return $this->twig;
}
public function setUser($user)
{
$this->user = $user;
return $this;
}
public function getUser()
{
if ($this->user) {
return $this->user;
}
if (null === $token = $this->securityContext->getToken()) {
return null;
}
if (!is_object($user = $token->getUser())) {
return null;
}
return $user;
}
public function notify($template = null, array $data = array())
{
$notification = $this->getNewNotification();
$content = '';
if($template) {
$template = $this->loadTemplate($template);
$data = array_merge($this->getDefaultData(), $data);
$content = $this->twig->render($template->getContent(), $data);
$logContent = $this->twig->render($template->getLogContent(), $data);
} else {
$logContent = implode(' / ', $data);
}
$notification
->setContentRender($content)
->setLogContentRender($logContent)
->setTemplate($template)
->setIsRead(false);
if ($this->getUser()) {
$notification->setUser($this->getUser());
}
$notification->save();
}
public function getDefaultData()
{
return array_merge(
array(
'user' => $this->getUser(),
),
parent::getDefaultData()
);
}
}