<?php

namespace EesyPHP;

/*
 * Performance monitoring
 */

class SentryTransaction {

    /**
     * The Sentry transaction object
     * @var \Sentry\Tracing\Transaction
     */
    private $transaction;

    /**
     * The Sentry transaction context object
     * @var \Sentry\Tracing\TransactionContext
     */
    private $context;

    /**
     * Constructor: start a Sentry transaction
     * @param string|null $op The operation name
     * @param string|null $name The transaction name
     * @return void
     */
    public function __construct($op=null, $name=null) {
        // In phpstan context, do not initialize
        // @phpstan-ignore-next-line
        if (defined('__PHPSTAN_RUNNING__') && constant('__PHPSTAN_RUNNING__'))
          return;
        // Setup context for the full transaction
        $this->context = new \Sentry\Tracing\TransactionContext();
        $this->context->setName(
            $name?$name:
            (php_sapi_name()=='cli'?'CLI execution':'HTTP request')
        );
        $this->context->setOp(
            $op?$op:
            (php_sapi_name()=='cli'?'cli.command':'http.request')
        );

        // Start the transaction
        $this->transaction = \Sentry\startTransaction($this->context);

        // Set the current transaction as the current span so we can retrieve it later
        \Sentry\SentrySdk::getCurrentHub()->setSpan($this->transaction);
    }

    /**
     * Destructor: Stop the current Sentry transaction
     * @return void
     */
    public function __destruct() {
        // In phpstan context, do nothing
        // @phpstan-ignore-next-line
        if (defined('__PHPSTAN_RUNNING__') && constant('__PHPSTAN_RUNNING__'))
          return;
        SentrySpan :: finishAll();
        $this->transaction->finish();
    }
}

# vim: tabstop=2 shiftwidth=2 softtabstop=2 expandtab
