PersistentObject.php 7.3 KB

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