<?php

namespace onespace\tools\rabbit\helpers;

use Yii;

/**
 * This allows the class to clear memory in memory ways. The primary way is to clear logs
 */
trait MemoryHelper {
    /**
     * Flush logs from memory. Set threshold and iterator to run it every so often on
     * a loop, otherwise leave both to null to always flush when called.
     */
    protected function flushLogs(?int $threshold = null, ?int $iterator = null): void {
        if ($threshold === null || $iterator === null || $iterator % $threshold === 0) {
            Yii::getLogger()->flush(true);
        }
    }

    /**
     * Container for the original memory limit, when temporarily increase the limit for easy restore.
     */
    private ?string $memoryLimit = null;

    /**
     * Increase the memory limit if needed
     *
     * @param string $limit Something like '150M' or '1G'
     */
    protected function setMemoryLimit(string $limit): void {
        if ($this->memoryLimit === null) {
            $this->memoryLimit = ini_get('memory_limit');
        }

        ini_set('memory_limit', $limit);
    }

    /**
     * Restory the memory limit back to it's original value
     */
    protected function restoreMemoryLimit(): void {
        if ($this->memoryLimit === null) {
            Yii::warning("Cannot restore a memory limit, if it hasn't previously been set", __METHOD__);
            return;
        }

        ini_set('memory_limit', $this->memoryLimit);
        $this->memoryLimit = null;
    }
}
