Reflections.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * @package ActiveRecord
  4. */
  5. namespace ActiveRecord;
  6. use ReflectionClass;
  7. /**
  8. * Simple class that caches reflections of classes.
  9. *
  10. * @package ActiveRecord
  11. */
  12. class Reflections extends Singleton
  13. {
  14. /**
  15. * Current reflections.
  16. *
  17. * @var array
  18. */
  19. private $reflections = array();
  20. /**
  21. * Instantiates a new ReflectionClass for the given class.
  22. *
  23. * @param string $class Name of a class
  24. * @return Reflections $this so you can chain calls like Reflections::instance()->add('class')->get()
  25. */
  26. public function add($class=null)
  27. {
  28. $class = $this->get_class($class);
  29. if (!isset($this->reflections[$class]))
  30. $this->reflections[$class] = new ReflectionClass($class);
  31. return $this;
  32. }
  33. /**
  34. * Destroys the cached ReflectionClass.
  35. *
  36. * Put this here mainly for testing purposes.
  37. *
  38. * @param string $class Name of a class.
  39. * @return void
  40. */
  41. public function destroy($class)
  42. {
  43. if (isset($this->reflections[$class]))
  44. $this->reflections[$class] = null;
  45. }
  46. /**
  47. * Get a cached ReflectionClass.
  48. *
  49. * @param string $class Optional name of a class
  50. * @return mixed null or a ReflectionClass instance
  51. * @throws ActiveRecordException if class was not found
  52. */
  53. public function get($class=null)
  54. {
  55. $class = $this->get_class($class);
  56. if (isset($this->reflections[$class]))
  57. return $this->reflections[$class];
  58. throw new ActiveRecordException("Class not found: $class");
  59. }
  60. /**
  61. * Retrieve a class name to be reflected.
  62. *
  63. * @param mixed $mixed An object or name of a class
  64. * @return string
  65. */
  66. private function get_class($mixed=null)
  67. {
  68. if (is_object($mixed))
  69. return get_class($mixed);
  70. if (!is_null($mixed))
  71. return $mixed;
  72. return $this->get_called_class();
  73. }
  74. }
  75. ?>