Search by

zdenekgebauer / google-tag-manager

zdenekgebauer

Google Tag Manager data layer generator

Package info

github.com/zdenekgebauer/google-tag-manager

pkg:composer/zdenekgebauer/google-tag-manager

Statistics

Installs: 4

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

2.0.0 2026-11-15 08:26 UTC

This package is auto-updated.

Last update: 2026-11-15 08:28:14 UTC


README

PHP library generating Google Tag Manager data layer pushes (window.dataLayer.push({...});) for Google Analytics 4 events.

Features

  • All GA4 recommended events for all properties, ecommerce, games and lead generation
  • Ecommerce reset ({"ecommerce":null}) to clear the previous ecommerce object
  • Validation of required properties before rendering
  • Custom data layer content by extending DataLayerContent

Requirements

PHP 8.4 or newer. No runtime dependencies.

Installation

composer require zdenekgebauer/google-tag-manager

Usage

Simple event

use ZdenekGebauer\GoogleTagManager\DataLayer;
use ZdenekGebauer\GoogleTagManager\Ga4\EventShare;

$event = new EventShare();
$event->method = 'Twitter';
$event->contentType = 'image';
$event->itemId = 'C_12345';

echo new DataLayer($event)->render();
// window.dataLayer.push({"event":"share","method":"Twitter","content_type":"image","item_id":"C_12345"});

Ecommerce event with items

use ZdenekGebauer\GoogleTagManager\DataLayer;
use ZdenekGebauer\GoogleTagManager\Ga4\CustomerType;
use ZdenekGebauer\GoogleTagManager\Ga4\EcommerceReset;
use ZdenekGebauer\GoogleTagManager\Ga4\EventPurchase;
use ZdenekGebauer\GoogleTagManager\Ga4\Item;

$event = new EventPurchase();
$event->transactionId = 'T_12345';
$event->value = 9.99;
$event->currency = 'USD';
$event->customerType = CustomerType::Returning;

$item = new Item('SKU_12', 'Some gadget', 9.99, 1);
$item->brand = 'Acme';
$item->category = 'Cool Gadgets';
$item->setCustomParameter('item_size', 'XL');
$event->addItem($item);

echo new DataLayer(new EcommerceReset())->render(); // window.dataLayer.push({"ecommerce":null});
echo new DataLayer($event)->render();
// window.dataLayer.push({"event":"purchase","ecommerce":{"transaction_id":"T_12345","value":9.99,"currency":"USD",
// "customer_type":"returning","items":[{"item_id":"SKU_12","item_name":"Some gadget","index":0,"item_brand":"Acme",
// "item_category":"Cool Gadgets","price":9.99,"quantity":1,"item_size":"XL"}]}});

Google recommends clearing the previous ecommerce object before every ecommerce event, so render EcommerceReset first.

Full refund

A full refund needs only the transaction id; add items for a partial refund.

use ZdenekGebauer\GoogleTagManager\DataLayer;
use ZdenekGebauer\GoogleTagManager\Ga4\EventRefund;

$event = new EventRefund();
$event->transactionId = 'T_12345';

echo new DataLayer($event)->render();
// window.dataLayer.push({"event":"refund","ecommerce":{"transaction_id":"T_12345"}});

Custom content

use ZdenekGebauer\GoogleTagManager\DataLayer;
use ZdenekGebauer\GoogleTagManager\DataLayerContent;
use ZdenekGebauer\GoogleTagManager\Ga4\Utils;

class MyDataLayerContent extends DataLayerContent
{
    public ?string $requiredProperty = null;

    public ?string $optionalProperty = null;

    public function __construct()
    {
        $this->requiredProperties = ['requiredProperty'];
    }

    public function assertValid(): void
    {
        parent::assertValid(); // checks the required properties
        // ... some additional check
    }

    public function jsonSerialize(): \stdClass
    {
        $result = new \stdClass();
        $result->required_property = $this->requiredProperty;
        Utils::addProperty($result, 'optional_property', $this->optionalProperty);
        return $result;
    }
}

$content = new MyDataLayerContent();
$content->requiredProperty = 'some';
echo new DataLayer($content)->render(); // window.dataLayer.push({"required_property":"some"});

API

DataLayer

  • new DataLayer(DataLayerContent $content) validates the content and throws \LogicException when a required property is null, value is set without currency, or an ecommerce event has no items.
  • render(): string returns window.dataLayer.push(<json>);, or an empty string when the content serializes to an empty object. Throws \JsonException when the content cannot be encoded.

Events (ZdenekGebauer\GoogleTagManager\Ga4)

Properties are public and optional unless shown in bold; optional properties left null are not rendered. value and currency are both optional, but currency is required whenever value is set.

General

Class event Properties
EventEarnVirtualCurrency earn_virtual_currency virtualCurrencyName, value
EventJoinGroup join_group groupId
EventLogin login method
EventSearch search searchTerm
EventSelectContent select_content contentType, contentId (must not be purely numeric)
EventShare share method, contentType, itemId
EventSignUp sign_up method
EventSpendVirtualCurrency spend_virtual_currency value, virtualCurrencyName, itemName
EventTutorialBegin tutorial_begin —
EventTutorialComplete tutorial_complete —

Ecommerce

Rendered inside the ecommerce object. Render EcommerceReset before each of them.

Class event Properties Items
EventAddPaymentInfo add_payment_info currency, value, coupon, paymentType required
EventAddShippingInfo add_shipping_info currency, value, coupon, shippingTier required
EventAddToCart add_to_cart value, currency required
EventAddToWishlist add_to_wishlist currency, value required
EventBeginCheckout begin_checkout currency, value, coupon required
EventPurchase purchase transactionId, affiliation, value, tax, shipping, currency, coupon, customerType required
EventRefund refund transactionId, currency, value, coupon, shipping, tax optional
EventRemoveFromCart remove_from_cart value, currency required
EventSelectItem select_item itemListId, itemListName required
EventSelectPromotion select_promotion creativeName, creativeSlot, promotionId, promotionName optional
EventViewCart view_cart value, currency required
EventViewItem view_item currency, value required
EventViewItemList view_item_list currency, itemListId, itemListName required
EventViewPromotion view_promotion creativeName, creativeSlot, promotionId, promotionName required
EcommerceReset — renders {"ecommerce":null} —

EventPurchase::$customerType takes the enum CustomerType::New or CustomerType::Returning. An event accepts at most 200 items; addItem() throws \LogicException on the 201st.

Games

Class event Properties
EventLevelEnd level_end levelName, success (bool)
EventLevelStart level_start levelName
EventLevelUp level_up level, character
EventPostScore post_score score (int or float), level, character
EventUnlockAchievement unlock_achievement achievementId

Lead generation

Class event Properties
EventCloseConvertLead close_convert_lead currency, value
EventCloseUnconvertLead close_unconvert_lead currency, value, unconvertLeadReason
EventDisqualifyLead disqualify_lead currency, value, disqualifiedLeadReason
EventGenerateLead generate_lead currency, value, leadSource
EventQualifyLead qualify_lead currency, value
EventWorkingLead working_lead currency, value, leadStatus

Item

new Item(
    ?string $itemId = null,
    ?string $name = null,
    ?float  $price = null,
    ?int    $quantity = null,
)

Optional properties: affiliation, brand, category … category5, coupon, creativeName, creativeSlot, currency, discount, googleBusinessVertical, listId, listName, locationId, promotionId, promotionName, variant. addItem() throws \LogicException when both itemId and name are empty. Items are rendered with their position as index; properties left null are not rendered.

setCustomParameter(string $name, string|int|float $value) adds a custom item parameter, rendered after the prescribed ones. An item accepts up to 27 custom parameters; setting an existing name again replaces its value. It throws \LogicException on the 28th parameter and on names of prescribed item parameters (price, item_id, …). A parameter GA4 prescribes in the future may become a reserved name in a minor release.

Upgrading from 1.x

  • PHP 8.4 or newer is required.
  • Items no longer render item_id, item_name, price and quantity as null; update assertions that compare the exact output.
  • value and currency are optional on add_to_cart, remove_from_cart, view_cart and purchase; only value without currency throws \LogicException. Code that relied on the exception for a missing value or currency has to check it itself.
  • An event accepts at most 200 items, addItem() throws \LogicException on the 201st.
  • EventSelectContent rejects a purely numeric contentId.
  • The license changed from WTFPL to MIT.

Official documentation

Development

Local environment runs on Lando (Docker, PHP 8.5 + xdebug):

lando start                # start the environment
lando install              # install dependencies
lando tests                # run the test suite
lando coverage             # test suite with code coverage
lando dependency-analyser  # composer.json dependencies against their usage
lando ecs                  # coding standards (lando ecs-fix to apply)
lando infection            # mutation testing, requires 100 % MSI
lando phpstan              # static analysis, level max
lando rector               # modernization dry-run (lando rector-fix to apply)

License

MIT — see LICENSE.