static function captureBuffers(?int $targetLevel = null, bool $catchExceptions = false): string
    {
        $output = '';
        $stopLevel = $targetLevel ?? 0;

        foreach (self::iterateBufferLevels(PHP_OUTPUT_HANDLER_CLEANABLE) as $level) {
            if ($level <= $stopLevel) {
                break;
            }

            try {
                $output = ob_get_clean() . $output;
            } catch (\Throwable $e) {
                if (!$catchExceptions) {
                    throw $e;
                }
            }
        }

        return $output;
    }