PersistentObject.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. <?php
  2. namespace Doctrine\Common\Persistence;
  3. use BadMethodCallException;
  4. use Doctrine\Common\Collections\ArrayCollection;
  5. use Doctrine\Common\Collections\Collection;
  6. use Doctrine\Persistence\Mapping\ClassMetadata;
  7. use Doctrine\Persistence\ObjectManager;
  8. use Doctrine\Persistence\ObjectManagerAware;
  9. use InvalidArgumentException;
  10. use RuntimeException;
  11. use function lcfirst;
  12. use function substr;
  13. /**
  14. * PersistentObject base class that implements getter/setter methods for all mapped fields and associations
  15. * by overriding __call.
  16. *
  17. * This class is a forward compatible implementation of the PersistentObject trait.
  18. *
  19. * Limitations:
  20. *
  21. * 1. All persistent objects have to be associated with a single ObjectManager, multiple
  22. * ObjectManagers are not supported. You can set the ObjectManager with `PersistentObject#setObjectManager()`.
  23. * 2. Setters and getters only work if a ClassMetadata instance was injected into the PersistentObject.
  24. * This is either done on `postLoad` of an object or by accessing the global object manager.
  25. * 3. There are no hooks for setters/getters. Just implement the method yourself instead of relying on __call().
  26. * 4. Slower than handcoded implementations: An average of 7 method calls per access to a field and 11 for an association.
  27. * 5. Only the inverse side associations get autoset on the owning side as well. Setting objects on the owning side
  28. * will not set the inverse side associations.
  29. *
  30. * @deprecated Deprecated `PersistentObject` class in 1.2. Please implement this functionality
  31. * directly in your application if you want ActiveRecord style functionality.
  32. *
  33. * @example
  34. *
  35. * PersistentObject::setObjectManager($em);
  36. *
  37. * class Foo extends PersistentObject
  38. * {
  39. * private $id;
  40. * }
  41. *
  42. * $foo = new Foo();
  43. * $foo->getId(); // method exists through __call
  44. */
  45. abstract class PersistentObject implements ObjectManagerAware
  46. {
  47. /** @var ObjectManager|null */
  48. private static $objectManager = null;
  49. /** @var ClassMetadata|null */
  50. private $cm = null;
  51. /**
  52. * Sets the object manager responsible for all persistent object base classes.
  53. *
  54. * @return void
  55. */
  56. public static function setObjectManager(?ObjectManager $objectManager = null)
  57. {
  58. self::$objectManager = $objectManager;
  59. }
  60. /**
  61. * @return ObjectManager|null
  62. */
  63. public static function getObjectManager()
  64. {
  65. return self::$objectManager;
  66. }
  67. /**
  68. * Injects the Doctrine Object Manager.
  69. *
  70. * @return void
  71. *
  72. * @throws RuntimeException
  73. */
  74. public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata)
  75. {
  76. if ($objectManager !== self::$objectManager) {
  77. throw new RuntimeException('Trying to use PersistentObject with different ObjectManager instances. ' .
  78. 'Was PersistentObject::setObjectManager() called?');
  79. }
  80. $this->cm = $classMetadata;
  81. }
  82. /**
  83. * Sets a persistent fields value.
  84. *
  85. * @param string $field
  86. * @param mixed[] $args
  87. *
  88. * @return void
  89. *
  90. * @throws BadMethodCallException When no persistent field exists by that name.
  91. * @throws InvalidArgumentException When the wrong target object type is passed to an association.
  92. */
  93. private function set($field, $args)
  94. {
  95. if ($this->cm->hasField($field) && ! $this->cm->isIdentifier($field)) {
  96. $this->$field = $args[0];
  97. } elseif ($this->cm->hasAssociation($field) && $this->cm->isSingleValuedAssociation($field)) {
  98. $targetClass = $this->cm->getAssociationTargetClass($field);
  99. if (! ($args[0] instanceof $targetClass) && $args[0] !== null) {
  100. throw new InvalidArgumentException("Expected persistent object of type '" . $targetClass . "'");
  101. }
  102. $this->$field = $args[0];
  103. $this->completeOwningSide($field, $targetClass, $args[0]);
  104. } else {
  105. throw new BadMethodCallException("no field with name '" . $field . "' exists on '" . $this->cm->getName() . "'");
  106. }
  107. }
  108. /**
  109. * Gets a persistent field value.
  110. *
  111. * @param string $field
  112. *
  113. * @return mixed
  114. *
  115. * @throws BadMethodCallException When no persistent field exists by that name.
  116. */
  117. private function get($field)
  118. {
  119. if ($this->cm->hasField($field) || $this->cm->hasAssociation($field)) {
  120. return $this->$field;
  121. }
  122. throw new BadMethodCallException("no field with name '" . $field . "' exists on '" . $this->cm->getName() . "'");
  123. }
  124. /**
  125. * If this is an inverse side association, completes the owning side.
  126. *
  127. * @param string $field
  128. * @param ClassMetadata $targetClass
  129. * @param object $targetObject
  130. *
  131. * @return void
  132. */
  133. private function completeOwningSide($field, $targetClass, $targetObject)
  134. {
  135. // add this object on the owning side as well, for obvious infinite recursion
  136. // reasons this is only done when called on the inverse side.
  137. if (! $this->cm->isAssociationInverseSide($field)) {
  138. return;
  139. }
  140. $mappedByField = $this->cm->getAssociationMappedByTargetField($field);
  141. $targetMetadata = self::$objectManager->getClassMetadata($targetClass);
  142. $setter = ($targetMetadata->isCollectionValuedAssociation($mappedByField) ? 'add' : 'set') . $mappedByField;
  143. $targetObject->$setter($this);
  144. }
  145. /**
  146. * Adds an object to a collection.
  147. *
  148. * @param string $field
  149. * @param mixed[] $args
  150. *
  151. * @return void
  152. *
  153. * @throws BadMethodCallException
  154. * @throws InvalidArgumentException
  155. */
  156. private function add($field, $args)
  157. {
  158. if (! $this->cm->hasAssociation($field) || ! $this->cm->isCollectionValuedAssociation($field)) {
  159. throw new BadMethodCallException('There is no method add' . $field . '() on ' . $this->cm->getName());
  160. }
  161. $targetClass = $this->cm->getAssociationTargetClass($field);
  162. if (! ($args[0] instanceof $targetClass)) {
  163. throw new InvalidArgumentException("Expected persistent object of type '" . $targetClass . "'");
  164. }
  165. if (! ($this->$field instanceof Collection)) {
  166. $this->$field = new ArrayCollection($this->$field ?: []);
  167. }
  168. $this->$field->add($args[0]);
  169. $this->completeOwningSide($field, $targetClass, $args[0]);
  170. }
  171. /**
  172. * Initializes Doctrine Metadata for this class.
  173. *
  174. * @return void
  175. *
  176. * @throws RuntimeException
  177. */
  178. private function initializeDoctrine()
  179. {
  180. if ($this->cm !== null) {
  181. return;
  182. }
  183. if (! self::$objectManager) {
  184. throw new RuntimeException('No runtime object manager set. Call PersistentObject#setObjectManager().');
  185. }
  186. $this->cm = self::$objectManager->getClassMetadata(static::class);
  187. }
  188. /**
  189. * Magic methods.
  190. *
  191. * @param string $method
  192. * @param mixed[] $args
  193. *
  194. * @return mixed
  195. *
  196. * @throws BadMethodCallException
  197. */
  198. public function __call($method, $args)
  199. {
  200. $this->initializeDoctrine();
  201. $command = substr($method, 0, 3);
  202. $field = lcfirst(substr($method, 3));
  203. if ($command === 'set') {
  204. $this->set($field, $args);
  205. } elseif ($command === 'get') {
  206. return $this->get($field);
  207. } elseif ($command === 'add') {
  208. $this->add($field, $args);
  209. } else {
  210. throw new BadMethodCallException('There is no method ' . $method . ' on ' . $this->cm->getName());
  211. }
  212. }
  213. }