1: <?php
2:
3: namespace Guzzle\Inflection;
4:
5: /**
6: * Decorator used to add memoization to previously inflected words
7: */
8: class MemoizingInflector implements InflectorInterface
9: {
10: /**
11: * @var array Array of cached inflections
12: */
13: protected $cache = array(
14: 'snake' => array(),
15: 'camel' => array()
16: );
17:
18: /**
19: * @var int Max entries per cache
20: */
21: protected $maxCacheSize;
22:
23: /**
24: * @var InflectorInterface Decorated inflector
25: */
26: protected $decoratedInflector;
27:
28: /**
29: * @param InflectorInterface $inflector Inflector being decorated
30: * @param int $maxCacheSize Maximum number of cached items to hold per cache
31: */
32: public function __construct(InflectorInterface $inflector, $maxCacheSize = 500)
33: {
34: $this->decoratedInflector = $inflector;
35: $this->maxCacheSize = $maxCacheSize;
36: }
37:
38: /**
39: * {@inheritdoc}
40: */
41: public function snake($word)
42: {
43: if (!isset($this->cache['snake'][$word])) {
44: $this->pruneCache('snake');
45: $this->cache['snake'][$word] = $this->decoratedInflector->snake($word);
46: }
47:
48: return $this->cache['snake'][$word];
49: }
50:
51: /**
52: * Converts strings from snake_case to upper CamelCase
53: *
54: * @param string $word Value to convert into upper CamelCase
55: *
56: * @return string
57: */
58: public function camel($word)
59: {
60: if (!isset($this->cache['camel'][$word])) {
61: $this->pruneCache('camel');
62: $this->cache['camel'][$word] = $this->decoratedInflector->camel($word);
63: }
64:
65: return $this->cache['camel'][$word];
66: }
67:
68: /**
69: * Prune one of the named caches by removing 20% of the cache if it is full
70: *
71: * @param string $cache Type of cache to prune
72: */
73: protected function pruneCache($cache)
74: {
75: if (count($this->cache[$cache]) == $this->maxCacheSize) {
76: $this->cache[$cache] = array_slice($this->cache[$cache], $this->maxCacheSize * 0.2);
77: }
78: }
79: }
80: