DefinitionCacheFactory.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Responsible for creating definition caches.
  4. */
  5. class HTMLPurifier_DefinitionCacheFactory
  6. {
  7. protected $caches = array('Serializer' => array());
  8. protected $implementations = array();
  9. protected $decorators = array();
  10. /**
  11. * Initialize default decorators
  12. */
  13. public function setup() {
  14. $this->addDecorator('Cleanup');
  15. }
  16. /**
  17. * Retrieves an instance of global definition cache factory.
  18. */
  19. public static function instance($prototype = null) {
  20. static $instance;
  21. if ($prototype !== null) {
  22. $instance = $prototype;
  23. } elseif ($instance === null || $prototype === true) {
  24. $instance = new HTMLPurifier_DefinitionCacheFactory();
  25. $instance->setup();
  26. }
  27. return $instance;
  28. }
  29. /**
  30. * Registers a new definition cache object
  31. * @param $short Short name of cache object, for reference
  32. * @param $long Full class name of cache object, for construction
  33. */
  34. public function register($short, $long) {
  35. $this->implementations[$short] = $long;
  36. }
  37. /**
  38. * Factory method that creates a cache object based on configuration
  39. * @param $name Name of definitions handled by cache
  40. * @param $config Instance of HTMLPurifier_Config
  41. */
  42. public function create($type, $config) {
  43. $method = $config->get('Cache.DefinitionImpl');
  44. if ($method === null) {
  45. return new HTMLPurifier_DefinitionCache_Null($type);
  46. }
  47. if (!empty($this->caches[$method][$type])) {
  48. return $this->caches[$method][$type];
  49. }
  50. if (
  51. isset($this->implementations[$method]) &&
  52. class_exists($class = $this->implementations[$method], false)
  53. ) {
  54. $cache = new $class($type);
  55. } else {
  56. if ($method != 'Serializer') {
  57. trigger_error("Unrecognized DefinitionCache $method, using Serializer instead", E_USER_WARNING);
  58. }
  59. $cache = new HTMLPurifier_DefinitionCache_Serializer($type);
  60. }
  61. foreach ($this->decorators as $decorator) {
  62. $new_cache = $decorator->decorate($cache);
  63. // prevent infinite recursion in PHP 4
  64. unset($cache);
  65. $cache = $new_cache;
  66. }
  67. $this->caches[$method][$type] = $cache;
  68. return $this->caches[$method][$type];
  69. }
  70. /**
  71. * Registers a decorator to add to all new cache objects
  72. * @param
  73. */
  74. public function addDecorator($decorator) {
  75. if (is_string($decorator)) {
  76. $class = "HTMLPurifier_DefinitionCache_Decorator_$decorator";
  77. $decorator = new $class;
  78. }
  79. $this->decorators[$decorator->name] = $decorator;
  80. }
  81. }
  82. // vim: et sw=4 sts=4