MappedEventSubscriber.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. <?php
  2. namespace Gedmo\Mapping;
  3. use Doctrine\Common\Annotations\Reader;
  4. use Doctrine\Common\Cache\ArrayCache;
  5. use Doctrine\Common\EventSubscriber;
  6. use Doctrine\Common\Persistence\ObjectManager;
  7. use Doctrine\Common\EventArgs;
  8. use Gedmo\Mapping\Event\AdapterInterface;
  9. /**
  10. * This is extension of event subscriber class and is
  11. * used specifically for handling the extension metadata
  12. * mapping for extensions.
  13. *
  14. * It dries up some reusable code which is common for
  15. * all extensions who maps additional metadata through
  16. * extended drivers
  17. *
  18. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. abstract class MappedEventSubscriber implements EventSubscriber
  22. {
  23. /**
  24. * Static List of cached object configurations
  25. * leaving it static for reasons to look into
  26. * other listener configuration
  27. *
  28. * @var array
  29. */
  30. protected static $configurations = array();
  31. /**
  32. * Listener name, etc: sluggable
  33. *
  34. * @var string
  35. */
  36. protected $name;
  37. /**
  38. * ExtensionMetadataFactory used to read the extension
  39. * metadata through the extension drivers
  40. *
  41. * @var ExtensionMetadataFactory
  42. */
  43. private $extensionMetadataFactory = array();
  44. /**
  45. * List of event adapters used for this listener
  46. *
  47. * @var array
  48. */
  49. private $adapters = array();
  50. /**
  51. * Custom annotation reader
  52. *
  53. * @var object
  54. */
  55. private $annotationReader;
  56. /**
  57. * @var \Doctrine\Common\Annotations\AnnotationReader
  58. */
  59. private static $defaultAnnotationReader;
  60. /**
  61. * Constructor
  62. */
  63. public function __construct()
  64. {
  65. $parts = explode('\\', $this->getNamespace());
  66. $this->name = end($parts);
  67. }
  68. /**
  69. * Get an event adapter to handle event specific
  70. * methods
  71. *
  72. * @param EventArgs $args
  73. *
  74. * @throws \Gedmo\Exception\InvalidArgumentException - if event is not recognized
  75. *
  76. * @return \Gedmo\Mapping\Event\AdapterInterface
  77. */
  78. protected function getEventAdapter(EventArgs $args)
  79. {
  80. $class = get_class($args);
  81. if (preg_match('@Doctrine\\\([^\\\]+)@', $class, $m) && in_array($m[1], array('ODM', 'ORM'))) {
  82. if (!isset($this->adapters[$m[1]])) {
  83. $adapterClass = $this->getNamespace().'\\Mapping\\Event\\Adapter\\'.$m[1];
  84. if (!class_exists($adapterClass)) {
  85. $adapterClass = 'Gedmo\\Mapping\\Event\\Adapter\\'.$m[1];
  86. }
  87. $this->adapters[$m[1]] = new $adapterClass();
  88. }
  89. $this->adapters[$m[1]]->setEventArgs($args);
  90. return $this->adapters[$m[1]];
  91. } else {
  92. throw new \Gedmo\Exception\InvalidArgumentException('Event mapper does not support event arg class: '.$class);
  93. }
  94. }
  95. /**
  96. * Get the configuration for specific object class
  97. * if cache driver is present it scans it also
  98. *
  99. * @param ObjectManager $objectManager
  100. * @param string $class
  101. *
  102. * @return array
  103. */
  104. public function getConfiguration(ObjectManager $objectManager, $class)
  105. {
  106. $config = array();
  107. if (isset(self::$configurations[$this->name][$class])) {
  108. $config = self::$configurations[$this->name][$class];
  109. } else {
  110. $factory = $objectManager->getMetadataFactory();
  111. $cacheDriver = $factory->getCacheDriver();
  112. if ($cacheDriver) {
  113. $cacheId = ExtensionMetadataFactory::getCacheId($class, $this->getNamespace());
  114. if (($cached = $cacheDriver->fetch($cacheId)) !== false) {
  115. self::$configurations[$this->name][$class] = $cached;
  116. $config = $cached;
  117. } else {
  118. // re-generate metadata on cache miss
  119. $this->loadMetadataForObjectClass($objectManager, $factory->getMetadataFor($class));
  120. if (isset(self::$configurations[$this->name][$class])) {
  121. $config = self::$configurations[$this->name][$class];
  122. }
  123. }
  124. $objectClass = isset($config['useObjectClass']) ? $config['useObjectClass'] : $class;
  125. if ($objectClass !== $class) {
  126. $this->getConfiguration($objectManager, $objectClass);
  127. }
  128. }
  129. }
  130. return $config;
  131. }
  132. /**
  133. * Get extended metadata mapping reader
  134. *
  135. * @param ObjectManager $objectManager
  136. *
  137. * @return ExtensionMetadataFactory
  138. */
  139. public function getExtensionMetadataFactory(ObjectManager $objectManager)
  140. {
  141. $oid = spl_object_hash($objectManager);
  142. if (!isset($this->extensionMetadataFactory[$oid])) {
  143. if (is_null($this->annotationReader)) {
  144. // create default annotation reader for extensions
  145. $this->annotationReader = $this->getDefaultAnnotationReader();
  146. }
  147. $this->extensionMetadataFactory[$oid] = new ExtensionMetadataFactory(
  148. $objectManager,
  149. $this->getNamespace(),
  150. $this->annotationReader
  151. );
  152. }
  153. return $this->extensionMetadataFactory[$oid];
  154. }
  155. /**
  156. * Set annotation reader class
  157. * since older doctrine versions do not provide an interface
  158. * it must provide these methods:
  159. * getClassAnnotations([reflectionClass])
  160. * getClassAnnotation([reflectionClass], [name])
  161. * getPropertyAnnotations([reflectionProperty])
  162. * getPropertyAnnotation([reflectionProperty], [name])
  163. *
  164. * @param Reader $reader - annotation reader class
  165. */
  166. public function setAnnotationReader($reader)
  167. {
  168. $this->annotationReader = $reader;
  169. }
  170. /**
  171. * Scans the objects for extended annotations
  172. * event subscribers must subscribe to loadClassMetadata event
  173. *
  174. * @param ObjectManager $objectManager
  175. * @param object $metadata
  176. * @return void
  177. */
  178. public function loadMetadataForObjectClass(ObjectManager $objectManager, $metadata)
  179. {
  180. $factory = $this->getExtensionMetadataFactory($objectManager);
  181. try {
  182. $config = $factory->getExtensionMetadata($metadata);
  183. } catch (\ReflectionException $e) {
  184. // entity\document generator is running
  185. $config = false; // will not store a cached version, to remap later
  186. }
  187. if ($config) {
  188. self::$configurations[$this->name][$metadata->name] = $config;
  189. }
  190. }
  191. /**
  192. * Get the namespace of extension event subscriber.
  193. * used for cache id of extensions also to know where
  194. * to find Mapping drivers and event adapters
  195. *
  196. * @return string
  197. */
  198. abstract protected function getNamespace();
  199. /**
  200. * Create default annotation reader for extensions
  201. *
  202. * @return \Doctrine\Common\Annotations\AnnotationReader
  203. */
  204. private function getDefaultAnnotationReader()
  205. {
  206. if (null === self::$defaultAnnotationReader) {
  207. if (version_compare(\Doctrine\Common\Version::VERSION, '2.2.0-DEV', '>=')) {
  208. $reader = new \Doctrine\Common\Annotations\AnnotationReader();
  209. \Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace(
  210. 'Gedmo\\Mapping\\Annotation',
  211. __DIR__.'/../../'
  212. );
  213. $reader = new \Doctrine\Common\Annotations\CachedReader($reader, new ArrayCache());
  214. } elseif (version_compare(\Doctrine\Common\Version::VERSION, '2.1.0RC4-DEV', '>=')) {
  215. $reader = new \Doctrine\Common\Annotations\AnnotationReader();
  216. \Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace(
  217. 'Gedmo\\Mapping\\Annotation',
  218. __DIR__.'/../../'
  219. );
  220. $reader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\\');
  221. $reader = new \Doctrine\Common\Annotations\CachedReader($reader, new ArrayCache());
  222. } elseif (version_compare(\Doctrine\Common\Version::VERSION, '2.1.0-BETA3-DEV', '>=')) {
  223. $reader = new \Doctrine\Common\Annotations\AnnotationReader();
  224. $reader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\\');
  225. $reader->setIgnoreNotImportedAnnotations(true);
  226. $reader->setAnnotationNamespaceAlias('Gedmo\\Mapping\\Annotation\\', 'gedmo');
  227. $reader->setEnableParsePhpImports(false);
  228. $reader->setAutoloadAnnotations(true);
  229. $reader = new \Doctrine\Common\Annotations\CachedReader(
  230. new \Doctrine\Common\Annotations\IndexedReader($reader), new ArrayCache()
  231. );
  232. } else {
  233. $reader = new \Doctrine\Common\Annotations\AnnotationReader();
  234. $reader->setAutoloadAnnotations(true);
  235. $reader->setAnnotationNamespaceAlias('Gedmo\\Mapping\\Annotation\\', 'gedmo');
  236. $reader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\\');
  237. }
  238. self::$defaultAnnotationReader = $reader;
  239. }
  240. return self::$defaultAnnotationReader;
  241. }
  242. /**
  243. * Sets the value for a mapped field
  244. *
  245. * @param AdapterInterface $adapter
  246. * @param object $object
  247. * @param string $field
  248. * @param mixed $oldValue
  249. * @param mixed $newValue
  250. */
  251. protected function setFieldValue(AdapterInterface $adapter, $object, $field, $oldValue, $newValue)
  252. {
  253. $manager = $adapter->getObjectManager();
  254. $meta = $manager->getClassMetadata(get_class($object));
  255. $uow = $manager->getUnitOfWork();
  256. $meta->getReflectionProperty($field)->setValue($object, $newValue);
  257. $uow->propertyChanged($object, $field, $oldValue, $newValue);
  258. $adapter->recomputeSingleObjectChangeSet($uow, $meta, $object);
  259. }
  260. }