<?php

class PhonalisaIniWriter {
    
    
    
    public static function writeIniFile($data, $fileName)
    {
        $fileContent = array();
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $fileContent[] = "[$key]";
                PhonalisaIniWriter::getFileContentFromArray($fileContent,$value);
            } else {
                $fileContent[] = PhonalisaIniWriter::getFileContentFromKeyValue($key, $value);
            }
        } 
        PhonalisaIniWriter::safeFileRewrite($fileName, implode("\r\n", $fileContent));
    }
    
    private static function getFileContentFromArray(&$fileContent, $data)
    {
        
        foreach ($data as $key => $value) {
            $fileContent[] = PhonalisaIniWriter::getFileContentFromKeyValue($key, $value);
        } 
    }
    
    private static function getFileContentFromKeyValue($key,$value)
    {
        return "$key = ".(is_numeric($value) ? $value : '"'.$value.'"');
    }
    
    public static function safeFileRewrite($fileName, $dataToSave)
    {    
        if ($fp = fopen($fileName, 'w')) {
            $startTime = microtime(TRUE);
            do {            
                $canWrite = flock($fp, LOCK_EX);
               // If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
               if(!$canWrite) usleep(round(rand(0, 100)*1000));
            } while ((!$canWrite) && ((microtime(TRUE)-$startTime) < 5));

            //file was locked so now we can store information
            if ($canWrite) {           
                fwrite($fp, $dataToSave);
                flock($fp, LOCK_UN);
            }
            fclose($fp);
        }
    }
}
