<?php
namespace Drupal\hederavita_core\EventSubscriber;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Path\CurrentPathStack;
use Drupal\marketing_tools\GoogleEventStorage;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Hederavita Core event subscriber.
*/
class OderPlacedSubscriber implements EventSubscriberInterface {
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* The marketing tool.
*
* @var \Drupal\marketing_tools\GoogleEventStorage
*/
protected $marketing_tool;
/**
* The current path.
*
* @var \Drupal\Core\Path\CurrentPathStack
*/
protected $current_path;
/**
* Constructs event subscriber.
*
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger.
* @param \Drupal\marketing_tools\GoogleEventStorage $marketing_tool
* The marketing tool.
* @param \Drupal\Core\Path\CurrentPathStack $current_path
*/
public function __construct(MessengerInterface $messenger, GoogleEventStorage $marketing_tool, CurrentPathStack $current_path) {
$this->messenger = $messenger;
$this->marketing_tool = $marketing_tool;
$this->current_path = $current_path;
}
/**
* Kernel request event handler.
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
* Response event.
*/
public function onKernelRequest(GetResponseEvent $event) {
$this->messenger->addStatus(__FUNCTION__);
}
/**
* Kernel response event handler.
*
* @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
* Response event.
*/
public function onKernelResponse(FilterResponseEvent $event) {
$this->messenger->addStatus(__FUNCTION__);
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events = [
'commerce_order.place.pre_transition' => ['addEvent', 50],
];
return $events;
}
/**
* Create google event
*
* @return void
*/
public function addEvent() {
$path = $this->current_path->getPath();
$path_parts = explode('/', $path);
foreach ($path_parts as $path_part) {
if (is_numeric($path_part)) {
$order = \Drupal::entityTypeManager()
->getStorage('commerce_order')
->load($path_part);
}
}
/** @var \Drupal\commerce_order\Entity\Order $order */
$value = $order->getTotalPrice()->getNumber();
$order_id = $order->id();
$this->marketing_tool->addEvent([
'event' => 'conversion',
'sendTo' => 'GTM-PZQ4TQZ',
'value' => $value,
'currency' => 'RSD',
'transaction_id' => $order_id,
]);
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter