1: <?php
2:
3: namespace Guzzle\Cache;
4:
5: use Guzzle\Common\FromConfigInterface;
6: use Guzzle\Common\Exception\InvalidArgumentException;
7: use Guzzle\Common\Exception\RuntimeException;
8:
9: 10: 11: 12:
13: class CacheAdapterFactory implements FromConfigInterface
14: {
15: 16: 17: 18: 19: 20: 21: 22:
23: public static function factory($config = array())
24: {
25: if (!is_array($config)) {
26: throw new InvalidArgumentException('$config must be an array');
27: }
28:
29: if (!isset($config['cache.adapter']) && !isset($config['cache.provider'])) {
30: $config['cache.adapter'] = 'Guzzle\Cache\NullCacheAdapter';
31: $config['cache.provider'] = null;
32: } else {
33:
34: foreach (array('cache.adapter', 'cache.provider') as $required) {
35: if (!isset($config[$required])) {
36: throw new InvalidArgumentException("{$required} is a required CacheAdapterFactory option");
37: }
38: if (is_string($config[$required])) {
39:
40: $config[$required] = str_replace('.', '\\', $config[$required]);
41: if (!class_exists($config[$required])) {
42: throw new InvalidArgumentException("{$config[$required]} is not a valid class for {$required}");
43: }
44: }
45: }
46:
47: if (is_string($config['cache.provider'])) {
48: $args = isset($config['cache.provider.args']) ? $config['cache.provider.args'] : null;
49: $config['cache.provider'] = self::createObject($config['cache.provider'], $args);
50: }
51: }
52:
53:
54: if (is_string($config['cache.adapter'])) {
55: $args = isset($config['cache.adapter.args']) ? $config['cache.adapter.args'] : array();
56: array_unshift($args, $config['cache.provider']);
57: $config['cache.adapter'] = self::createObject($config['cache.adapter'], $args);
58: }
59:
60: return $config['cache.adapter'];
61: }
62:
63: 64: 65: 66: 67: 68: 69: 70: 71:
72: protected static function createObject($className, array $args = null)
73: {
74: try {
75: if (!$args) {
76: return new $className;
77: } else {
78: $c = new \ReflectionClass($className);
79: return $c->newInstanceArgs($args);
80: }
81: } catch (\Exception $e) {
82: throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
83: }
84: }
85: }
86: