Skip to content

Instantly share code, notes, and snippets.

@WyriHaximus
Created May 9, 2016 13:18
Show Gist options
  • Select an option

  • Save WyriHaximus/806a18ea8ba6e5d242ce3bb4bc7fcb1f to your computer and use it in GitHub Desktop.

Select an option

Save WyriHaximus/806a18ea8ba6e5d242ce3bb4bc7fcb1f to your computer and use it in GitHub Desktop.
<?php
namespace App\Di\Provider;
use Clue\React\Redis\Client;
use Clue\React\Redis\Factory;
use Ray\Di\Di\Inject;
use Ray\Di\ProviderInterface;
use React\Cache\CacheInterface;
use React\Dns\Protocol\BinaryDumper;
use React\Dns\Protocol\Parser;
use React\Dns\Query\CachedExecutor;
use React\Dns\Query\Executor;
use React\Dns\Query\RecordCache;
use React\Dns\Query\RetryExecutor;
use React\Dns\Resolver\Resolver;
use React\EventLoop\LoopInterface;
use WyriHaximus\React\Cache\Redis;
use function React\Promise\reject;
use function React\Promise\resolve;
class DNSProvider implements ProviderInterface
{
protected $loop;
/**
* @Inject
*/
public function __construct(LoopInterface $loop)
{
$this->loop = $loop;
}
public function get()
{
return new Resolver(
'8.8.8.8:53',
new CachedExecutor(
new RetryExecutor(
new Executor(
$this->loop,
new Parser(),
new BinaryDumper()
)
),
new RecordCache(new class($this->loop) implements CacheInterface {
/**
* @var Redis
*/
private $redis;
private $data = [];
public function __construct(LoopInterface $loop)
{
(new Factory($loop))->createClient()->then(function (Client $client) {
$this->redis = new Redis($client, 'react:cache:cns:');
foreach ($this->data as $key => $value) {
$this->redis->set($key, $value);
}
$this->data = [];
});
}
public function get($key)
{
if ($this->redis instanceof Redis) {
return $this->redis->get($key);
}
if (isset($this->data[$key])) {
return resolve($this->data[$key]);
}
return reject();
}
public function set($key, $value)
{
if ($this->redis instanceof Redis) {
$this->redis->set($key, $value);
return;
}
$this->data[$key] = $value;
}
public function remove($key)
{
if ($this->redis instanceof Redis) {
$this->redis->remove($key);
return;
}
if (isset($this->data[$key])) {
unset($this->data[$key]);
}
}
})
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment