You are here

protected function PageContextService::buildInitiateCheckout in Simple Facebook Pixel 8

Builds Initiate Checkout event data.

1 call to PageContextService::buildInitiateCheckout()
PageContextService::build in src/PageContextService.php
Builds events data.

File

src/PageContextService.php, line 193

Class

PageContextService
Class PageContextService.

Namespace

Drupal\simple_facebook_pixel

Code

protected function buildInitiateCheckout() {
  if (!class_exists('Drupal\\commerce_product\\Entity\\Product')) {
    return;
  }
  if (!$this->configFactory
    ->get('initiate_checkout_enabled')) {
    return;
  }
  $attributes = $this->request->attributes
    ->all();
  if (isset($attributes['_route']) && $attributes['_route'] == 'commerce_checkout.form' && isset($attributes['step']) && $attributes['step'] == 'order_information') {

    /** @var \Drupal\commerce_order\Entity\Order $commerce_order */
    $commerce_order = $attributes['commerce_order'];
    $skus = [];
    $contents = [];

    /** @var \Drupal\commerce_order\Entity\OrderItem $item */
    foreach ($commerce_order
      ->getItems() as $item) {
      $purchased_entity = $item
        ->getPurchasedEntity();
      if (!$purchased_entity) {
        continue;
      }
      $skus[] = $purchased_entity
        ->getSku();
      $contents[] = [
        'id' => $purchased_entity
          ->getSku(),
        'quantity' => $item
          ->getQuantity(),
      ];
    }
    $data = [
      'num_items' => count($commerce_order
        ->getItems()),
      'value' => $commerce_order
        ->getTotalPrice()
        ->getNumber(),
      'currency' => $commerce_order
        ->getTotalPrice()
        ->getCurrencyCode(),
      'content_ids' => $skus,
      'contents' => $contents,
    ];
    $this->pixelBuilder
      ->addEvent('InitiateCheckout', $data);
  }
}