<?php

declare(strict_types=1);

namespace PhpWA\Runtime;

 
final class FileAccountLock implements AccountLockInterface
{
      private $handle;

     
    public function __construct($handle)
    {
        if (!is_resource($handle)) {
            throw new \InvalidArgumentException('Account lock handle must be a resource.');
        }
        $this->handle = $handle;
    }

    public function release(): void
    {
        if (!is_resource($this->handle)) {
            return;
        }
        $handle = $this->handle;
        SafeRuntime::call(static function () use ($handle): bool {
            return flock($handle, LOCK_UN);
        }, false);
        fclose($this->handle);
        $this->handle = null;
    }

    public function isHeld(): bool
    {
        return is_resource($this->handle);
    }

    public function __destruct()
    {
        $this->release();
    }
}
