Skip to content

autoinstrument classes for cDebug::enter() and cDebug::leave() #4

@open768

Description

@open768

copilot suggests its possible to autoinstrument classes

<?php

class cDebug {
    private static $appClasses = [];

    public static function initialize() {
        // Get the list of declared classes before including application files
        $coreClasses = get_declared_classes();

        // Include your application files
        require_once "manifest.php";
        require_once "orm_manifest.php";

        // Get the list of declared classes after including application files
        $allClasses = get_declared_classes();

        // Determine the classes declared by the application
        self::$appClasses = array_diff($allClasses, $coreClasses);
    }

    public static function instrumentAll() {
        foreach (self::$appClasses as $className) {
            self::instrument($className);
        }
    }

    private static function instrument($className) {
        $reflectionClass = new ReflectionClass($className);
        $methods = $reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC);

        foreach ($methods as $method) {
            $methodName = $method->getName();
            if ($methodName !== '__construct') {
                self::wrapMethod($className, $methodName);
            }
        }
    }

    private static function wrapMethod($className, $methodName) {
        $originalMethod = new ReflectionMethod($className, $methodName);
        $originalMethod->setAccessible(true);

        $classInstance = new $className();
        $originalMethodClosure = $originalMethod->getClosure($classInstance);

        $newMethod = function () use ($originalMethodClosure, $methodName) {
            cDebug::enter($methodName);
            $result = call_user_func_array($originalMethodClosure, func_get_args());
            cDebug::leave($methodName);
            return $result;
        };

        $classInstance->$methodName = Closure::bind($newMethod, $classInstance, $className);
    }

    public static function enter($methodName) {
        echo "Entering method: $methodName\n";
    }

    public static function leave($methodName) {
        echo "Leaving method: $methodName\n";
    }
}

// Initialize and instrument all application classes
cDebug::initialize();
cDebug::instrumentAll();

// Example usage
$manifest = new cCuriosityORMManifest();
$manifest->updateIndex();

Metadata

Metadata

Assignees

No one assigned

    Projects

    Status

    parked

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions