<?php

declare(strict_types=1);

namespace PhpWA\Runtime;

use PhpWA\Storage\PrivateFileArea;

final class PrivateFileAccountLockProvider implements AccountLockProviderInterface
{
    /** @var PrivateFileArea */ private $files;

    public function __construct(string $directory)
    {
        $this->files = new PrivateFileArea($directory);
    }

    public function acquire(string $accountId): ?AccountLockInterface
    {
        $path = $this->files->accountPath('worker', $accountId, '.lock');
        $handle = $this->files->openLock($path, true);
        return is_resource($handle) ? new FileAccountLock($handle) : null;
    }
}
