<?php

class CLock
{

  private $filename;

  private $filepath;

  private $id;

  private $handle;

  public function __construct($id = null)
  {
    $this->id = $id;
    if ($this->id == null)
      $this->id = md5 ( microtime ( true ) . uniqid ( null, true ) );
    $this->filename = "{$this->id}.lck";
    $this->filepath = pathCombine ( app ()->basePath, $this->filename );
    $this->handle = false;
  }

  public function isLocked()
  {
    return $this->handle !== false;
  }

  public function lock()
  {
    if ($this->isLocked ())
      return true;
    $this->handle = fopen ( $this->filepath, 'w' );
    if ($this->handle === false)
      return false;
    if (! flock ( $this->handle, LOCK_EX ))
    {
      fclose ( $this->handle );
      $this->handle = false;
      return false;
    }
    
    return true;
  }

  public function tryLock()
  {
    while ( ! $this->lock () )
    {
    }
  }

  public function unlock()
  {
    if ($this->isLocked ())
    {
      fclose ( $this->handle );
      $this->handle = false;
    }
  }

  function __destruct()
  {
    $this->unlock ();
  }
}