Context.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * Registry object that contains information about the current context.
  4. * @warning Is a bit buggy when variables are set to null: it thinks
  5. * they don't exist! So use false instead, please.
  6. * @note Since the variables Context deals with may not be objects,
  7. * references are very important here! Do not remove!
  8. */
  9. class HTMLPurifier_Context
  10. {
  11. /**
  12. * Private array that stores the references.
  13. * @type array
  14. */
  15. private $_storage = array();
  16. /**
  17. * Registers a variable into the context.
  18. * @param string $name String name
  19. * @param mixed $ref Reference to variable to be registered
  20. */
  21. public function register($name, &$ref)
  22. {
  23. if (array_key_exists($name, $this->_storage)) {
  24. throw new Exception("Name $name produces collision, cannot re-register");
  25. }
  26. $this->_storage[$name] =& $ref;
  27. }
  28. /**
  29. * Retrieves a variable reference from the context.
  30. * @param string $name String name
  31. * @param bool $ignore_error Boolean whether or not to ignore error
  32. * @return mixed
  33. */
  34. public function &get($name, $ignore_error = false)
  35. {
  36. if (!array_key_exists($name, $this->_storage)) {
  37. if (!$ignore_error) {
  38. throw new Exception("Attempted to retrieve non-existent variable $name");
  39. }
  40. $var = null; // so we can return by reference
  41. return $var;
  42. }
  43. return $this->_storage[$name];
  44. }
  45. /**
  46. * Destroys a variable in the context.
  47. * @param string $name String name
  48. */
  49. public function destroy($name)
  50. {
  51. if (!array_key_exists($name, $this->_storage)) {
  52. throw new Exception("Attempted to destroy non-existent variable $name");
  53. }
  54. unset($this->_storage[$name]);
  55. }
  56. /**
  57. * Checks whether or not the variable exists.
  58. * @param string $name String name
  59. * @return bool
  60. */
  61. public function exists($name)
  62. {
  63. return array_key_exists($name, $this->_storage);
  64. }
  65. /**
  66. * Loads a series of variables from an associative array
  67. * @param array $context_array Assoc array of variables to load
  68. */
  69. public function loadArray($context_array)
  70. {
  71. foreach ($context_array as $key => $discard) {
  72. $this->register($key, $context_array[$key]);
  73. }
  74. }
  75. }
  76. // vim: et sw=4 sts=4