<?php

class LockHelper
{
    //const ANTIGUEDAD_MAXIMA = 10026; //2,785 hrs

    const ANTIGUEDAD_MAXIMA = 43200;  //12 hrs

    private $lock;

    public function __construct($lock)
    {
        $this->lock = $lock;
    }

    public function existeLock()
    {
        if(!file_exists($this->lock)){
            return false;
        }

        $this->manejaLock(function ($handle){
            if($handle){
                $creacion_archivo = fread($handle, filesize($this->lock));
                if((time() - (int)$creacion_archivo) > self::ANTIGUEDAD_MAXIMA){
                    $this->destruyeLock();
                }
            }
        }, 'r');

        return file_exists($this->lock);
    }

    private function manejaLock(Closure $callback = null, $permiso = 'w')
    {
        $handle = fopen($this->lock, $permiso);
        if($callback){
            $callback($handle);
        }
        fclose($handle);
        chmod($this->lock, 0777);
    }

    public function creaLock()
    {
        $this->manejaLock(function ($handle){
            fwrite($handle, time());
        });
        return $this->existeLock();
    }

    public function destruyeLock(){
        chmod($this->lock, 0777);
        return unlink($this->lock);
    }
}
