<?php
declare(strict_types=1);
namespace Workshop;
use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Lock\Store\FlockStore;
use Symfony\Component\Lock\Store\RedisStore;
use Predis\Client;

final class Stores {
    public static function factory(string $type, string $directory): LockFactory {
        if ($type === 'flock') {
            if (!is_dir($directory) && !mkdir($directory, 0700, true) && !is_dir($directory)) {
                throw new \RuntimeException('Cannot create private lock directory');
            }
            return new LockFactory(new FlockStore($directory));
        }
        if ($type !== 'redis') throw new \InvalidArgumentException('Unknown store');
        $host = getenv('LOCK_REDIS_HOST') ?: '127.0.0.1';
        $port = (int)(getenv('LOCK_REDIS_PORT') ?: 8533);
        $password = getenv('LOCK_REDIS_PASSWORD');
        $options = ['scheme'=>'tcp','host'=>$host,'port'=>$port,'timeout'=>2,'read_write_timeout'=>2];
        if ($password !== false && $password !== '') $options['password'] = $password;
        return new LockFactory(new RedisStore(new Client($options)));
    }
}
