Plugin Directory

Changeset 2882488


Ignore:
Timestamp:
03/18/2023 09:56:46 AM (3 years ago)
Author:
handcraftbyte
Message:

Code cleanup & disp name change

Location:
gtm-ecommerce-woo/trunk
Files:
10 edited

Legend:

Unmodified
Added
Removed
  • gtm-ecommerce-woo/trunk/gtm-ecommerce-woo.php

    r2819367 r2882488  
    11<?php
    22/**
    3  * Plugin Name: Google Tag Manager for WooCommerce FREE
     3 * Plugin Name: GTM for WooCommerce FREE
    44 * Plugin URI:  https://wordpress.org/plugins/gtm-ecommerce-woo
    55 * Description: Push WooCommerce eCommerce (GA4 and UA compatible) information to GTM DataLayer. Use any GTM integration to measure your customers' activities.
    6  * Version:     1.10.6
     6 * Version:     1.10.7
    77 * Author:      Handcraft Byte
    88 * Author URI:  https://handcraftbyte.com/
     
    1313 *
    1414 * WC requires at least: 4.0
    15  * WC tested up to: 7.1.0
     15 * WC tested up to: 7.5.0
    1616 */
    1717
     
    4444register_activation_hook( __FILE__, [$pluginService, 'activationHook'] );
    4545register_deactivation_hook( __FILE__, [$monitorService, 'deactivationHook'] );
    46 
  • gtm-ecommerce-woo/trunk/lib/Container.php

    r2773695 r2882488  
    1818class Container {
    1919
    20     public function __construct( $pluginVersion ) {
     20    /** @var EventStrategiesService */
     21    public $eventStrategiesService;
     22
     23    /** @var GtmSnippetService */
     24    public $gtmSnippetService;
     25
     26    /** @var SettingsService */
     27    public $settingsService;
     28
     29    /** @var PluginService */
     30    public $pluginService;
     31
     32    /** @var MonitorService */
     33    public $monitorService;
     34
     35    /** @var ThemeValidatorService */
     36    public $themeValidatorService;
     37
     38    /** @var EventInspectorService */
     39    public $eventInspectorService;
     40
     41    public function __construct( string $pluginVersion ) {
    2142        $snakeCaseNamespace = 'gtm_ecommerce_woo';
    2243        $spineCaseNamespace = 'gtm-ecommerce-woo';
     
    3859            // 'refund',
    3960        ];
    40         $tagConciergeApiUrl = getenv('TAG_CONCIERGE_API_URL') ? getenv('TAG_CONCIERGE_API_URL') : 'https://api.tagconcierge.com';
    41         $tagConciergeEdgeUrl = getenv('TAG_CONCIERGE_EDGE_URL') ? getenv('TAG_CONCIERGE_EDGE_URL') : 'https://edge.tagconcierge.com';
     61        $tagConciergeApiUrl = getenv('TAG_CONCIERGE_API_URL') ?: 'https://api.tagconcierge.com';
     62        $tagConciergeEdgeUrl = getenv('TAG_CONCIERGE_EDGE_URL') ?: 'https://edge.tagconcierge.com';
    4263
    4364        $wpSettingsUtil = new WpSettingsUtil($snakeCaseNamespace, $spineCaseNamespace);
    4465        $wcTransformerUtil = new WcTransformerUtil();
    45         $wcOutputUtil = new WcOutputUtil();
     66        $wcOutputUtil = new WcOutputUtil($pluginVersion);
    4667
    4768        $eventStrategies = [
     
    5071        ];
    5172
    52         $events = array_map(function( $eventStrategy) {
     73        $events = array_map(static function( $eventStrategy) {
    5374            return $eventStrategy->getEventName();
    5475        }, $eventStrategies);
    5576
    56         $this->eventStrategiesService = new EventStrategiesService($wpSettingsUtil, $eventStrategies);
     77        $this->eventStrategiesService = new EventStrategiesService($wpSettingsUtil, $wcOutputUtil, $eventStrategies);
    5778        $this->gtmSnippetService = new GtmSnippetService($wpSettingsUtil);
    5879        $this->settingsService = new SettingsService($wpSettingsUtil, $events, $proEvents, $serverEvents, $tagConciergeApiUrl, $pluginVersion);
    59         $this->pluginService = new PluginService($spineCaseNamespace, $wpSettingsUtil, $pluginVersion);
     80        $this->pluginService = new PluginService($spineCaseNamespace, $wpSettingsUtil, $wcOutputUtil, $pluginVersion);
    6081        $this->monitorService = new MonitorService($snakeCaseNamespace, $spineCaseNamespace, $wcTransformerUtil, $wpSettingsUtil, $wcOutputUtil, $tagConciergeApiUrl, $tagConciergeEdgeUrl);
    6182        $this->themeValidatorService = new ThemeValidatorService($snakeCaseNamespace, $spineCaseNamespace, $wcTransformerUtil, $wpSettingsUtil, $wcOutputUtil, $events, $tagConciergeApiUrl, $pluginVersion);
     
    6485    }
    6586
    66     public function getSettingsService() {
     87    public function getSettingsService(): SettingsService {
    6788        return $this->settingsService;
    6889    }
    6990
    70     public function getGtmSnippetService() {
     91    public function getGtmSnippetService(): GtmSnippetService {
    7192        return $this->gtmSnippetService;
    7293    }
    7394
    74     public function getEventStrategiesService() {
     95    public function getEventStrategiesService(): EventStrategiesService {
    7596        return $this->eventStrategiesService;
    7697    }
    7798
    78     public function getPluginService() {
     99    public function getPluginService(): PluginService {
    79100        return $this->pluginService;
    80101    }
    81102
    82     public function getMonitorService() {
     103    public function getMonitorService(): MonitorService {
    83104        return $this->monitorService;
    84105    }
    85106
    86     public function getThemeValidatorService() {
     107    public function getThemeValidatorService(): ThemeValidatorService {
    87108        return $this->themeValidatorService;
    88109    }
    89110
    90     public function getEventInspectorService() {
     111    public function getEventInspectorService(): EventInspectorService {
    91112        return $this->eventInspectorService;
    92113    }
  • gtm-ecommerce-woo/trunk/lib/EventStrategy/AddToCartStrategy.php

    r2764750 r2882488  
    6363     */
    6464    public function onCartSubmitScript( $item) {
    65         $this->wcOutput->globalVariable('gtm_ecommerce_woo_item', $item);
    66         $this->wcOutput->script(<<<'EOD'
     65        $bypassUnquote = <<<'EOD'
     66var $form = jQuery(ev.currentTarget).parents('form.cart');
     67var quantity = jQuery('[name="quantity"]', $form).val();
     68var product_id = jQuery('[name="add-to-cart"]', $form).val();
     69EOD;
     70
     71        $jsonItem = json_encode($item);
     72        $this->wcOutput->script(<<<EOD
    6773jQuery(document).on('click', '.cart .single_add_to_cart_button', function(ev) {
    68     var $form = jQuery(ev.currentTarget).parents('form.cart');
    69     var quantity = jQuery('[name="quantity"]', $form).val();
    70     var product_id = jQuery('[name="add-to-cart"]', $form).val();
     74    ${bypassUnquote}
    7175
    72     var item = gtm_ecommerce_woo_item;
     76    var item = ${jsonItem};
    7377    item.quantity = parseInt(quantity);
    7478    dataLayer.push({
     
    8993     */
    9094    public function onCartLinkClick( $items) {
    91         $this->wcOutput->globalVariable('gtm_ecommerce_woo_items_by_product_id', $items);
     95        if (true === method_exists($this->wcOutput,'addItems')) {
     96            $this->wcOutput->addItems($items, 'product_id');
     97        } else {
     98            $this->wcOutput->globalVariable('gtm_ecommerce_woo_items_by_product_id', $items);
     99        }
     100
    92101        $this->wcOutput->script(<<<'EOD'
    93102jQuery(document).on('click', '.ajax_add_to_cart', function(ev) {
    94     var quantity = jQuery(ev.currentTarget).data('quantity');
    95     var product_id = jQuery(ev.currentTarget).data('product_id');
    96     var item = gtm_ecommerce_woo_items_by_product_id[product_id];
    97     item.quantity =  parseInt(quantity);
     103    var targetElement = jQuery(ev.currentTarget);
     104    if (0 === targetElement.length) {
     105        return;
     106    }
     107    var product_id = targetElement.data('product_id');
     108    if (undefined === product_id) {
     109        return;
     110    }
     111    var quantity = targetElement.data('quantity') ?? 1;
     112    var item = {};
     113
     114    if ('undefined' === typeof gtm_ecommerce_pro) {
     115        item = gtm_ecommerce_woo_items_by_product_id[product_id];
     116    } else {
     117        item = gtm_ecommerce_pro.getItemByProductId(product_id);
     118    }
     119
     120    item.quantity = parseInt(quantity);
    98121    dataLayer.push({
    99122      'event': 'add_to_cart',
  • gtm-ecommerce-woo/trunk/lib/GaEcommerceEntity/Event.php

    r2773695 r2882488  
    2121    }
    2222
    23     public function setItems( $items ) {
     23    public function setItems( array $items ): Event
     24    {
    2425        $this->items = array_values($items);
    2526        return $this;
    2627    }
    2728
    28     public function addItem( $item ) {
     29    public function addItem( Item $item ): Event
     30    {
    2931        $this->items[] = $item;
    3032        return $this;
    3133    }
    3234
    33     public function setCurrency( $currency ) {
     35    public function setCurrency( string $currency ): Event
     36    {
    3437        $this->currency = $currency;
    3538        return $this;
    3639    }
    3740
    38     public function setTransactionId( $transactionId ) {
     41    public function setTransactionId( $transactionId ): Event
     42    {
    3943        $this->transactionId = $transactionId;
    4044        return $this;
    4145    }
    4246
    43     public function setAffiliation( $affiliation ) {
     47    public function setAffiliation( string $affiliation ): Event
     48    {
    4449        $this->affiliation = $affiliation;
    4550        return $this;
    4651    }
    4752
    48     public function setValue( $value ) {
     53    public function setValue( float $value ): Event
     54    {
    4955        $this->value = $value;
    5056        return $this;
    5157    }
    5258
    53     public function setTax( $tax ) {
     59    public function setTax( float $tax ): Event
     60    {
    5461        $this->tax = $tax;
    5562        return $this;
    5663    }
    5764
    58     public function setShipping( $shipping ) {
     65    public function setShipping( float $shipping ): Event
     66    {
    5967        $this->shipping = $shipping;
    6068        return $this;
    6169    }
    6270
    63     public function setCoupon( $coupon ) {
     71    public function setCoupon( string $coupon ): Event
     72    {
    6473        $this->coupon = $coupon;
    6574        return $this;
    6675    }
    6776
    68     public function setExtraProperty( $propName, $propValue ) {
     77    public function setExtraProperty( string $propName, string $propValue ): Event
     78    {
    6979        $this->extraProps[$propName] = $propValue;
    7080        return $this;
    7181    }
    7282
    73     public function getValue() {
     83    public function getValue(): float
     84    {
     85        if (null !== $this->value) {
     86            return $this->value;
     87        }
     88
    7489        if (!is_array($this->items) || count($this->items) === 0) {
    7590            return 0;
    7691        }
    77         return array_reduce($this->items, function( $carry, $item ) {
    78             $itemPrice = isset($item->price) ? $item->price : 0;
    79             $itemQuantity = isset($item->quantity) ? $item->quantity : 1;
     92
     93        $value = array_reduce($this->items, static function( $carry, $item ) {
     94            $itemPrice = $item->price ?? 0;
     95            $itemQuantity = $item->quantity ?? 1;
    8096            return $carry + ((float) $itemPrice * (float) $itemQuantity);
    8197        }, 0);
     98
     99        return round($value, 2);
    82100    }
    83101
    84102    public function jsonSerialize() {
     103        apply_filters('gtm_ecommerce_woo_event_middleware', $this);
     104
    85105        /**
    86106         * Allow to customize the ecommerce event properties
     
    117137                'event' => $this->name,
    118138                'ecommerce' => [
     139                    'coupon' => $this->coupon,
    119140                    'value' => $this->getValue(),
    120141                    'items' => $this->items,
     
    123144        }
    124145
     146        if (null === $this->coupon || true === empty($this->coupon)) {
     147            unset($jsonEvent['ecommerce']['coupon'], $jsonEvent['ecommerce']['purchase']['coupon']);
     148        }
     149
    125150        foreach ($this->extraProps as $propName => $propValue) {
    126151            $jsonEvent[$propName] = $propValue;
    127152        }
    128153
    129         return array_filter($jsonEvent, function( $value ) {
     154        return array_filter($jsonEvent, static function( $value ) {
    130155            return !is_null($value) && '' !== $value;
    131156        });
  • gtm-ecommerce-woo/trunk/lib/Service/EventStrategiesService.php

    r2773695 r2882488  
    22
    33namespace GtmEcommerceWoo\Lib\Service;
     4
     5use GtmEcommerceWoo\Lib\EventStrategy\AbstractEventStrategy;
     6use GtmEcommerceWoo\Lib\Util\WcOutputUtil;
     7use GtmEcommerceWoo\Lib\Util\WpSettingsUtil;
    48
    59/**
     
    812class EventStrategiesService {
    913
     14    /** @var AbstractEventStrategy[] */
    1015    protected $eventStrategies = [];
     16
     17    /** @var WpSettingsUtil */
    1118    protected $wpSettingsUtil;
    1219
    13     public function __construct( $wpSettingsUtil, $eventStrategies) {
     20    /** @var WcOutputUtil */
     21    protected $wcOutputUtil;
     22
     23    /**
     24     * @param WpSettingsUtil $wpSettingsUtil
     25     * @param AbstractEventStrategy[] $eventStrategies
     26     */
     27    public function __construct( WpSettingsUtil $wpSettingsUtil, WcOutputUtil $wcOutputUtil, array $eventStrategies) {
    1428        $this->eventStrategies = $eventStrategies;
    1529        $this->wpSettingsUtil = $wpSettingsUtil;
     30        $this->wcOutputUtil = $wcOutputUtil;
    1631    }
    1732
  • gtm-ecommerce-woo/trunk/lib/Service/MonitorService.php

    r2773695 r2882488  
    2727
    2828    public function initialize() {
     29        if ($this->wpSettingsUtil->getOption('monitor_enabled') !== '1') {
     30            return;
     31        }
     32
    2933        $cronName = $this->snakeCaseNamespace . '_cron_monitor';
    30         if ($this->wpSettingsUtil->getOption('monitor_enabled') !== '1') {
    31             $timestamp = wp_next_scheduled( $cronName );
     34        if ($timestamp = wp_next_scheduled( $cronName )) {
    3235            wp_unschedule_event( $timestamp, $cronName );
    33             return;
    34         }
    35 
    36         add_action( $cronName, [$this, 'cronJob'] );
    37         if ( ! wp_next_scheduled( $cronName ) ) {
    38             wp_schedule_event( time(), 'hourly', $cronName );
    39         }
    40 
    41         // add_action( 'rest_api_init', function () {
    42         //   register_rest_route( 'gtm-ecommerce-woo/v1', '/track', array(
    43         //     'methods' => 'POST',
    44         //     'callback' => [$this, 'trackEvents'],
    45         //   ) );
    46         // } );
     36        }
    4737
    4838        add_action( 'wp_head', [$this, 'uuidHash'] );
     
    5343        add_action( 'woocommerce_order_status_changed', [$this, 'orderStatusChanged']);
    5444    }
    55 
    56     public function deactivationHook() {
    57         $cronName = $this->snakeCaseNamespace . '_cron_debugger';
    58         $timestamp = wp_next_scheduled( $cronName );
    59         wp_unschedule_event( $timestamp, $cronName );
    60     }
    61 
    62     // function
    6345
    6446    public function uuidHash() {
     
    7153        echo '})(dataLayer);';
    7254        echo "</script>\n";
    73     }
    74 
    75 
    76     // switch to save_post_shop_order hook
    77     public function cronJob() {
    78         $lastRun = get_transient( $this->snakeCaseNamespace . '_monitor_last_run' );
    79         if (false === $lastRun) {
    80             $lastRun = time() - HOUR_IN_SECONDS * 24;
    81         }
    82 
    83         set_transient( $this->snakeCaseNamespace . '_monitor_last_run', time() );
    8455    }
    8556
  • gtm-ecommerce-woo/trunk/lib/Service/PluginService.php

    r2773695 r2882488  
    22
    33namespace GtmEcommerceWoo\Lib\Service;
     4
     5use GtmEcommerceWoo\Lib\Util\WcOutputUtil;
     6use GtmEcommerceWoo\Lib\Util\WpSettingsUtil;
    47
    58/**
     
    710 */
    811class PluginService {
     12    /** @var WpSettingsUtil */
     13    protected $wpSettingsUtil;
     14
     15    /** @var WcOutputUtil */
     16    protected $wcOutputUtil;
    917    protected $spineCaseNamespace;
    10     protected $wpSettingsUtil;
    1118    protected $pluginVersion;
    1219    protected $feedbackUrl = 'https://wordpress.org/plugins/gtm-ecommerce-woo/#reviews';
    1320    protected $feedbackDays = 7;
    1421
    15     public function __construct( $spineCaseNamespace, $wpSettingsUtil, $pluginVersion ) {
     22    public function __construct( $spineCaseNamespace, $wpSettingsUtil, $wcOutputUtil, $pluginVersion ) {
    1623        $this->spineCaseNamespace = $spineCaseNamespace;
    1724        $this->wpSettingsUtil = $wpSettingsUtil;
     25        $this->wcOutputUtil = $wcOutputUtil;
    1826        $this->pluginVersion = $pluginVersion;
    1927    }
  • gtm-ecommerce-woo/trunk/lib/Util/WcOutputUtil.php

    r2773695 r2882488  
    44
    55class WcOutputUtil {
    6 
     6    protected $pluginDir = __DIR__;
     7    protected $pluginVersion = '';
    78    protected $scripts = [];
    89    protected $scriptFiles = [];
    910
    10     public function __construct() {
     11    public function __construct($pluginVersion) {
     12        $this->pluginVersion = $pluginVersion;
    1113        add_action( 'wp_footer', [$this, 'wpFooter'], 20 );
    1214        add_action( 'wp_enqueue_scripts', [$this, 'wpEnqueueScripts'] );
     
    5658            wp_enqueue_script(
    5759                $scriptFile['name'],
    58                 plugins_url( 'js/' . $scriptFile['name'] . '.js', MAIN_FILE ),
     60                plugin_dir_url( dirname( $this->pluginDir ) ) . 'js/' . $scriptFile['name'] . '.js',
    5961                $scriptFile['deps'],
    60                 '1.0.0',
     62                $this->pluginVersion,
    6163                $scriptFile['in_footer']
    6264            );
  • gtm-ecommerce-woo/trunk/readme.txt

    r2819367 r2882488  
    1 === Google Tag Manager for WooCommerce FREE ===
     1=== GTM for WooCommerce FREE ===
    22Contributors: Handcraft Byte
    33Tags: google tag manager, GA4, ecommerce events, Google Analytics, Facebook Pixel, shopping behavior
    44Requires at least: 5.1.0
    55Tested up to: 6.1.1
    6 Requires PHP: 7.2
     6Requires PHP: 7.0
    77Stable tag: trunk
    88License: GPLv2 or later
    99License URI: http://www.gnu.org/licenses/gpl-2.0.html
    1010
    11 Push WooCommerce eCommerce information (**GA4 Ecommerce and UA Enhanced Ecommerce compatible**) to GTM DataLayer. Use any GTM integration to measure your customers' activities.
     11Push WooCommerce eCommerce information (**GA4 Ecommerce and UA Enhanced Ecommerce compatible**) to GTM DataLayer. Use any Google Tag Manager integration to measure your customers' activities.
    1212
    1313== Description ==
     
    4444### Only single plugin needed
    4545
    46 Without Google Tag Manager for WooCommerce plugin, you would need a separate plugin for each of those integrations. And each additional plugin may make your Wordpress setup more complex.
    47 With Google Tag Manager for WooCommerce, all data is sent in standardized Google format to GTM and everything else is configured there.
     46Without GTM for WooCommerce plugin, you would need a separate plugin for each of those integrations. And each additional plugin may make your Wordpress setup more complex.
     47With GTM for WooCommerce, all data is sent in standardized Google format to GTM and everything else is configured there.
    4848
    4949### Reporting consistency
     
    5858== Installation ==
    5959
    60 1. Upload or install Google Tag Manager for WooCommerce plugin from WordPress plugins directory.
     601. Upload or install GTM for WooCommerce plugin from WordPress plugins directory.
    61612. Activate the plugin through the `Plugins` menu in WordPress.
    62623. That's it! If GTM is already implemented in your WordPress your eCommerce data will be pushed to GTM DataLayer. If not head to `Settings > Google Tag Manager` and paste in GTM snippets.
     
    106106== Screenshots ==
    107107
    108 1. **Google Tag Manager for WooCommerce** settings and GTM snippets
     1081. **GTM for WooCommerce** settings and GTM snippets
    1091092. eCommerce results in GA4 property
    1101103. eCommerce results in Universal Analytics property
     
    118118== Changelog ==
    119119
     120= 1.10.7 =
     121
     122* adjust the name to WordPress directory requirements
     123* tested against latest versions of WordPress and WooCommerce
     124* adjust required PHP version
     125
    120126= 1.10.6 =
    121127
  • gtm-ecommerce-woo/trunk/vendor/composer/installed.php

    r2773695 r2882488  
    44        'pretty_version' => 'dev-main',
    55        'version' => 'dev-main',
    6         'reference' => '87db683de6ac50748828aeb06590c3c5b74deb91',
     6        'reference' => '04baf68a97233e399c89e24640356308844ef967',
    77        'type' => 'project',
    88        'install_path' => __DIR__ . '/../../../',
     
    1414            'pretty_version' => 'dev-main',
    1515            'version' => 'dev-main',
    16             'reference' => '87db683de6ac50748828aeb06590c3c5b74deb91',
     16            'reference' => '04baf68a97233e399c89e24640356308844ef967',
    1717            'type' => 'project',
    1818            'install_path' => __DIR__ . '/../../../',
Note: See TracChangeset for help on using the changeset viewer.