<?php
namespace App\Shared\Helpers;

/**
 * A simple static class to collect metrics during a request.
 */
class MetricCollector
{
    private static $metrics = [];

    /**
     * Add a metric to the collection.
     * @param string $key
     * @param mixed $value
     */
    public static function add(string $key, $value)
    {
        // If the key already exists, turn it into an array to store multiple values.
        if (isset(self::$metrics[$key])) {
            if (!is_array(self::$metrics[$key])) {
                self::$metrics[$key] = [self::$metrics[$key]];
            }
            self::$metrics[$key][] = $value;
        } else {
            self::$metrics[$key] = $value;
        }
    }

    /**
     * Retrieve all collected metrics.
     * @return array
     */
    public static function getAll(): array
    {
        return self::$metrics;
    }

    /**
     * Clear all metrics.
     * Should be called at the beginning of each request.
     */
    public static function clear()
    {
        self::$metrics = [];
    }
}
