|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Craft; |
| 4 | + |
| 5 | +class FbPixel_AddToCartService extends BaseApplicationComponent |
| 6 | +{ |
| 7 | + const FLASH_NAME = '_fbPixelVariantIds'; |
| 8 | + |
| 9 | + private $variantIds; |
| 10 | + |
| 11 | + public function listen() |
| 12 | + { |
| 13 | + craft()->on('multiAdd_cart.MultiAddToCart', [ |
| 14 | + craft()->fbPixel_addToCart, 'addFlash' |
| 15 | + ]); |
| 16 | + |
| 17 | + craft()->fbPixel_addToCart->checkFlash(); |
| 18 | + } |
| 19 | + |
| 20 | + public function checkFlash() |
| 21 | + { |
| 22 | + if (craft()->userSession->hasFlash(self::FLASH_NAME)) { |
| 23 | + $this->variantIds = craft()->userSession->getFlash(self::FLASH_NAME, null, true); |
| 24 | + $this->addHook(); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + public function addHook() |
| 29 | + { |
| 30 | + craft()->templates->hook('fbPixel.renderBase', [ |
| 31 | + $this, 'renderTemplate' |
| 32 | + ]); |
| 33 | + } |
| 34 | + |
| 35 | + public function addFlash($event) |
| 36 | + { |
| 37 | + $lineItems = $event->params['lineItems']; |
| 38 | + |
| 39 | + $variantIds = craft()->userSession->getFlash(self::FLASH_NAME); |
| 40 | + |
| 41 | + if (empty($variantIds)) { |
| 42 | + $variantIds = []; |
| 43 | + } |
| 44 | + |
| 45 | + $variantIds = array_merge( |
| 46 | + $variantIds, |
| 47 | + $this->getVariantIds($event->params['lineItems']) |
| 48 | + ); |
| 49 | + |
| 50 | + craft()->userSession->setFlash(self::FLASH_NAME, $variantIds); |
| 51 | + } |
| 52 | + |
| 53 | + public function renderTemplate() |
| 54 | + { |
| 55 | + $template = ''; |
| 56 | + |
| 57 | + foreach ($this->variantIds as $variantId) { |
| 58 | + $variant = craft()->commerce_variants->getVariantById($variantId); |
| 59 | + |
| 60 | + $eventData = [ |
| 61 | + 'value' => $variant->salePrice, |
| 62 | + 'currency' => 'USD', |
| 63 | + 'content_name' => 'Add To Cart', |
| 64 | + 'content_ids' => $variant->sku, |
| 65 | + 'content_type' => 'product' |
| 66 | + ]; |
| 67 | + |
| 68 | + $template .= craft()->fbPixel->renderEvent('AddToCart', $eventData); |
| 69 | + } |
| 70 | + |
| 71 | + return $template; |
| 72 | + } |
| 73 | + |
| 74 | + private function getVariantIds($lineItems) |
| 75 | + { |
| 76 | + return array_map( function($lineItem) { |
| 77 | + $purchasable = $lineItem->purchasable; |
| 78 | + |
| 79 | + if (!empty($purchasable->defaultVariant)) { |
| 80 | + return $purchasable->defaultVariant->id; |
| 81 | + } else { |
| 82 | + return $purchasable->id; |
| 83 | + } |
| 84 | + |
| 85 | + }, $lineItems); |
| 86 | + } |
| 87 | +} |
0 commit comments