Skip to content

Commit

Permalink
Allowing use of DSN for redis and mongo factories
Browse files Browse the repository at this point in the history
Fixing style issuesgs

Fixing style issues

Adding valid check

Creating AbstractDsnFactory

Updating DSN to parse multiple hosts.

Removing static methods

Adding static back in
  • Loading branch information
cryptiklemur committed Jan 26, 2016
1 parent 667cf8d commit 4ece7b9
Show file tree
Hide file tree
Showing 5 changed files with 388 additions and 25 deletions.
250 changes: 250 additions & 0 deletions src/DSN.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
<?php

/*
* This file is part of php-cache\adapter-bundle package.
*
* (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/

namespace Cache\AdapterBundle;

/**
* @author Aaron Scherer <aequasi@gmail.com>
*
* @see https://github.com/snc/SncRedisBundle/blob/master/DependencyInjection/Configuration/RedisDsn.php
*/
class DSN
{
/**
* @type string
*/
protected $dsn;

/**
* @type string
*/
protected $protocol;

/**
* @type array
*/
protected $authentication;

/**
* @type array
*/
protected $hosts;

/**
* @type int
*/
protected $database;

/**
* @type int
*/
protected $weight;

/**
* @type string
*/
protected $alias;

/**
* Constructor.
*
* @param string $dsn
*/
public function __construct($dsn)
{
$this->dsn = $dsn;
$this->parseDsn($dsn);
}

/**
* @return string
*/
public function getDsn()
{
return $this->dsn;
}

/**
* @return string
*/
public function getProtocol()
{
return $this->protocol;
}

/**
* @return int|null
*/
public function getDatabase()
{
return $this->database;
}

/**
* @return int
*/
public function getWeight()
{
return $this->weight;
}

/**
* @return string
*/
public function getHosts()
{
return $this->hosts;
}

public function getFirstHost()
{
return $this->hosts[0];
}

/**
* @return array
*/
public function getAuthentication()
{
return $this->authentication;
}

public function getUsername()
{
return $this->authentication['username'];
}

public function getPassword()
{
return $this->authentication['password'];
}

/**
* @return string
*/
public function getAlias()
{
return $this->alias;
}

/**
* @return bool
*/
public function isValid()
{
if (null === $this->getProtocol()) {
return false;
}

if (!in_array($this->getProtocol(), ['redis', 'mongodb', 'tcp'])) {
return false;
}

if (empty($this->getHosts())) {
return false;
}

return true;
}

private function parseProtocol($dsn)
{
$regex = '/^(\w+):\/\//i';

preg_match($regex, $dsn, $matches);

if (isset($matches[1])) {
$this->protocol = $matches[1];
}
}

/**
* @param string $dsn
*/
private function parseDsn($dsn)
{
$this->parseProtocol($dsn);

// Remove the protocol
$dsn = str_replace($this->protocol.'://', '', $dsn);

// Parse and remove auth if they exist
if (false !== $pos = strrpos($dsn, '@')) {
$temp = explode(':', str_replace('\@', '@', substr($dsn, 0, $pos)));
$dsn = substr($dsn, $pos + 1);

$auth = [];
if (count($temp) === 2) {
$auth['username'] = $temp[0];
$auth['password'] = $temp[1];
} else {
$auth['password'] = $temp[0];
}

$this->authentication = $auth;
}

$temp = explode('/', $dsn);
$this->parseHosts($temp[0]);
if (isset($params[1])) {
$params = $temp[1];

$params = preg_replace_callback('/\?(weight|alias)=[^&]+.*$/', [$this, 'parseParameters'], $params);

// parse parameters
if (preg_match('#^(.*)/(\d+)$#', $params, $matches)) {
// parse database
$this->database = (int) $matches[2];
}
}
}

private function parseHosts($hostString)
{
preg_match_all('/(?P<host>[\w-._]+)(?::(?P<port>\d+))?/mi', $hostString, $matches);

$hosts = [];
foreach ($matches['host'] as $index => $match) {
$hosts[] = ['host' => $match, 'port' => $matches['port'][$index]];
}

$this->hosts = $hosts;
}

/**
* @param array $matches
*
* @return string
*/
protected function parseParameters($matches)
{
$parameters = explode('&', substr($matches[0], 1));
foreach ($parameters as $parameter) {
$kv = explode('=', $parameter, 2);
if (2 === count($kv)) {
switch ($kv[0]) {
case 'weight':
if ($kv[1]) {
$this->weight = (int) $kv[1];
}
break;
case 'alias':
if ($kv[1]) {
$this->alias = $kv[1];
}
break;
}
}
}

return '';
}
}
77 changes: 77 additions & 0 deletions src/Factory/AbstractDsnFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

/*
* This file is part of php-cache\adapter-bundle package.
*
* (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/

namespace Cache\AdapterBundle\Factory;

use Cache\AdapterBundle\DSN;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
abstract class AbstractDsnFactory extends AbstractAdapterFactory
{
/**
* @type DSN
*/
private $DSN;

/**
* @return DSN
*/
protected function getDsn()
{
return $this->DSN;
}

/**
* {@inheritdoc}
*/
protected static function configureOptionResolver(OptionsResolver $resolver)
{
$resolver->setDefaults(['dsn' => '']);
$resolver->setAllowedTypes('dsn', ['string']);
}

/**
* {@inheritdoc}
*/
public static function validate(array $options, $adapterName)
{
parent::validate($options, $adapterName);

if (empty($options['dsn'])) {
return;
}

$dsn = new DSN($options['dsn']);
if (!$dsn->isValid()) {
throw new \InvalidArgumentException('Invalid DSN: '.$options['dsn']);
}
}

/**
* {@inheritdoc}
*/
public function createAdapter(array $options = [])
{
if (!empty($options['dsn'])) {
$dsn = new DSN($options['dsn']);
if (!$dsn->isValid()) {
throw new \InvalidArgumentException('Invalid DSN: '.$options['dsn']);
}

$this->DSN = $dsn;
}

return parent::createAdapter($options);
}
}
26 changes: 18 additions & 8 deletions src/Factory/MongoDBFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,24 @@
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class MongoDBFactory extends AbstractAdapterFactory
class MongoDBFactory extends AbstractDsnFactory
{
protected static $dependencies = [
['requiredClass' => 'Cache\Adapter\MongoDB\MongoDBCachePool', 'packageName' => 'cache/mongodb-adapter'],
['requiredClass' => 'Cache\Adapter\MongoDB\MongoDBCachePool', 'packageName' => 'cache/mongodb-adapter'],
];

/**
* {@inheritdoc}
*/
public function getAdapter(array $config)
{
$manager = new Manager(sprintf('mongodb://%s:%s', $config['host'], $config['port']));
$dsn = static::getDsn();
if (empty($dsn)) {
$manager = new Manager(sprintf('mongodb://%s:%s', $config['host'], $config['port']));
} else {
$manager = new Manager($dsn->getDsn());
}

$collection = MongoDBCachePool::createCollection($manager, $config['namespace']);

return new MongoDBCachePool($collection);
Expand All @@ -40,11 +46,15 @@ public function getAdapter(array $config)
*/
protected static function configureOptionResolver(OptionsResolver $resolver)
{
$resolver->setDefaults([
'host' => '127.0.0.1',
'port' => 11211,
'namespace' => 'cache',
]);
parent::configureOptionResolver($resolver);

$resolver->setDefaults(
[
'host' => '127.0.0.1',
'port' => 11211,
'namespace' => 'cache',
]
);

$resolver->setAllowedTypes('host', ['string']);
$resolver->setAllowedTypes('port', ['string', 'int']);
Expand Down
Loading

0 comments on commit 4ece7b9

Please sign in to comment.