(C)oncept-Labs Arrays API

Installs: 4

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/concept-labs/debug

1.1.0 2025-10-13 14:28 UTC

This package is auto-updated.

Last update: 2025-10-13 14:47:52 UTC


README

PHP Version License: MIT Concept

A powerful PHP debugging and profiling library providing comprehensive tools for debugging, performance analysis, memory profiling, and more.

Installation

composer require concept-labs/debug

Features

  • 🐛 Variable Dumping - Pretty print variables with dump() and dd()
  • ⏱️ Performance Profiling - Measure execution time and memory usage
  • 📊 Memory Tracking - Monitor memory consumption and detect leaks
  • 📝 Logging - Built-in logging with severity levels
  • 🔍 Variable Inspection - Deep inspection of variable types and properties
  • 📚 Stack Traces - Formatted backtraces and call stacks
  • Assertions - Debug assertions with detailed error messages
  • 📈 Benchmarking - Measure callback execution time

Usage

Basic Debugging

use Concept\Debug\Debug;

// Dump variables
Debug::dump($var1, $var2, $var3);

// Dump and die
Debug::dd($someVariable);

// Throw exception with context
Debug::throw('Something went wrong', $context);

Performance Profiling

// Timer API
Debug::timerStart('operation');
// ... your code ...
$elapsed = Debug::timerStop('operation', true); // true = output result

// Get elapsed time without stopping
$currentTime = Debug::timerGet('operation');

// Benchmark a callback
$result = Debug::benchmark(function() {
    // ... code to benchmark ...
    return someValue();
}, 'My Benchmark');

// Profile with detailed metrics
Debug::profileStart('complex-operation');
// ... your code ...
$profile = Debug::profileEnd('complex-operation', true);
// Returns: ['elapsed_time' => ..., 'memory_used' => ...]

// Profile a callback
$data = Debug::profile(function() {
    return expensiveOperation();
}, 'expensive-op');
// Returns: ['result' => ..., 'profile' => [...]]

Memory Profiling

// Get current memory usage
$bytes = Debug::memoryUsage();
$formatted = Debug::memoryUsage(false, true); // "2.5 MB"

// Get peak memory usage
$peak = Debug::memoryPeak(false, true);

// Take memory snapshots
Debug::memorySnapshot('before-operation');
// ... your code ...
Debug::memorySnapshot('after-operation');

// Compare snapshots
$diff = Debug::memoryDiff('before-operation', 'after-operation', true);
echo "Memory used: $diff";

// Format bytes
echo Debug::formatBytes(1536); // "1.5 KB"

Variable Inspection

// Get detailed variable information
$info = Debug::inspect($variable);
// Returns: ['type' => 'object', 'class' => 'MyClass', 'methods' => [...], ...]

// Print inspection
Debug::printInspect($variable);

// Calculate variable size
$size = Debug::sizeOf($largeArray);
echo "Variable size: " . Debug::formatBytes($size);

// JSON dump
Debug::json($data);

Stack Traces

// Get backtrace
$trace = Debug::backtrace();

// Print formatted backtrace
Debug::printBacktrace(10); // limit to 10 frames

// Get stack trace as string
$traceString = Debug::getStackTrace();

Logging

// Log messages with severity levels
Debug::log('User logged in', 'info', ['user_id' => 123]);
Debug::log('Database connection failed', 'error');
Debug::log('Deprecated function called', 'warning');

// Get logs
$allLogs = Debug::getLogs();
$errorLogs = Debug::getLogs('error');

// Print logs
Debug::printLogs(); // all logs
Debug::printLogs('error'); // only errors

// Clear logs
Debug::clearLogs();

Assertions

// Assert conditions
Debug::assert($userId > 0, 'User ID must be positive');

// Non-throwing assertion (logs only)
$isValid = Debug::assert($condition, 'Check failed', false);

Context Information

// Get execution context
$context = Debug::context();
// Returns: memory usage, peak memory, execution time, included files, PHP version, etc.

// Print context
Debug::printContext();

Utilities

// Print all active timers
Debug::printTimers();

API Reference

Basic Debugging Methods

  • dump(...$vars) - Print variables in readable format
  • dd(...$vars) - Dump and die
  • throw(string $message, ...$vars) - Throw exception with context

Performance Methods

  • timerStart(string $label) - Start a timer
  • timerStop(string $label, bool $output = false) - Stop timer and get elapsed time
  • timerGet(string $label) - Get elapsed time without stopping
  • benchmark(callable $callback, ?string $label = null, bool $output = true) - Benchmark a callback
  • profileStart(string $label) - Start profiling
  • profileEnd(string $label, bool $output = false) - Stop profiling and get results
  • profile(callable $callback, ?string $label = null) - Profile a callback execution

Memory Methods

  • memoryUsage(bool $realUsage = false, bool $formatted = false) - Get current memory usage
  • memoryPeak(bool $realUsage = false, bool $formatted = false) - Get peak memory usage
  • memorySnapshot(string $label, bool $realUsage = false) - Take memory snapshot
  • memoryDiff(string $labelStart, string $labelEnd, bool $formatted = false) - Compare snapshots
  • formatBytes(int $bytes, int $precision = 2) - Format bytes to human-readable string

Inspection Methods

  • inspect($var) - Get detailed variable information
  • printInspect($var) - Print variable inspection
  • sizeOf($var) - Calculate variable size in bytes
  • json($var, int $options = ...) - Dump variable as JSON

Stack Trace Methods

  • backtrace(int $limit = 0, int $options = ...) - Get backtrace array
  • printBacktrace(int $limit = 0) - Print formatted backtrace
  • getStackTrace(int $limit = 0) - Get stack trace as string

Logging Methods

  • log(string $message, string $level = 'info', array $context = []) - Log a message
  • getLogs(?string $level = null) - Get log entries
  • printLogs(?string $level = null) - Print logs
  • clearLogs() - Clear all logs

Assertion Methods

  • assert(bool $condition, string $message = 'Assertion failed', bool $throwException = true) - Assert condition

Context Methods

  • context() - Get execution context information
  • printContext() - Print execution context
  • printTimers() - Print all active timers

Examples

Profile Database Query

Debug::profileStart('db-query');
$results = $db->query('SELECT * FROM users WHERE active = 1');
$profile = Debug::profileEnd('db-query', true);
// Output: Profile 'db-query':
//   Time: 0.045123 seconds
//   Memory: 2.5 MB

Track Memory Leaks

Debug::memorySnapshot('start');
for ($i = 0; $i < 1000; $i++) {
    processItem($i);
    if ($i % 100 === 0) {
        Debug::memorySnapshot("iteration-$i");
        $diff = Debug::memoryDiff('start', "iteration-$i", true);
        Debug::log("Memory at iteration $i: $diff", 'info');
    }
}
Debug::printLogs();

Benchmark Different Approaches

$time1 = Debug::benchmark(function() {
    return array_filter($array, fn($x) => $x > 10);
}, 'Array Filter');

$time2 = Debug::benchmark(function() {
    $result = [];
    foreach ($array as $x) {
        if ($x > 10) $result[] = $x;
    }
    return $result;
}, 'Foreach Loop');

echo "Filter is " . ($time2 / $time1) . "x faster\n";

Requirements

  • PHP >= 8.0

License

MIT License - see LICENSE file for details

Author

Viktor Halytskyi - concept.galitsky@gmail.com