PersistentObject.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\Common\Persistence;
  20. use Doctrine\Common\Collections\ArrayCollection;
  21. use Doctrine\Common\Collections\Collection;
  22. use Doctrine\Common\Persistence\Mapping\ClassMetadata;
  23. /**
  24. * PersistentObject base class that implements getter/setter methods for all mapped fields and associations
  25. * by overriding __call.
  26. *
  27. * This class is a forward compatible implementation of the PersistentObject trait.
  28. *
  29. * Limitations:
  30. *
  31. * 1. All persistent objects have to be associated with a single ObjectManager, multiple
  32. * ObjectManagers are not supported. You can set the ObjectManager with `PersistentObject#setObjectManager()`.
  33. * 2. Setters and getters only work if a ClassMetadata instance was injected into the PersistentObject.
  34. * This is either done on `postLoad` of an object or by accessing the global object manager.
  35. * 3. There are no hooks for setters/getters. Just implement the method yourself instead of relying on __call().
  36. * 4. Slower than handcoded implementations: An average of 7 method calls per access to a field and 11 for an association.
  37. * 5. Only the inverse side associations get autoset on the owning side as well. Setting objects on the owning side
  38. * will not set the inverse side associations.
  39. *
  40. * @example
  41. *
  42. * PersistentObject::setObjectManager($em);
  43. *
  44. * class Foo extends PersistentObject
  45. * {
  46. * private $id;
  47. * }
  48. *
  49. * $foo = new Foo();
  50. * $foo->getId(); // method exists through __call
  51. *
  52. * @author Benjamin Eberlei <kontakt@beberlei.de>
  53. */
  54. abstract class PersistentObject implements ObjectManagerAware
  55. {
  56. /**
  57. * @var ObjectManager|null
  58. */
  59. private static $objectManager = null;
  60. /**
  61. * @var ClassMetadata|null
  62. */
  63. private $cm = null;
  64. /**
  65. * Sets the object manager responsible for all persistent object base classes.
  66. *
  67. * @param ObjectManager|null $objectManager
  68. *
  69. * @return void
  70. */
  71. static public function setObjectManager(ObjectManager $objectManager = null)
  72. {
  73. self::$objectManager = $objectManager;
  74. }
  75. /**
  76. * @return ObjectManager|null
  77. */
  78. static public function getObjectManager()
  79. {
  80. return self::$objectManager;
  81. }
  82. /**
  83. * Injects the Doctrine Object Manager.
  84. *
  85. * @param ObjectManager $objectManager
  86. * @param ClassMetadata $classMetadata
  87. *
  88. * @return void
  89. *
  90. * @throws \RuntimeException
  91. */
  92. public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata)
  93. {
  94. if ($objectManager !== self::$objectManager) {
  95. throw new \RuntimeException("Trying to use PersistentObject with different ObjectManager instances. " .
  96. "Was PersistentObject::setObjectManager() called?");
  97. }
  98. $this->cm = $classMetadata;
  99. }
  100. /**
  101. * Sets a persistent fields value.
  102. *
  103. * @param string $field
  104. * @param array $args
  105. *
  106. * @return void
  107. *
  108. * @throws \BadMethodCallException When no persistent field exists by that name.
  109. * @throws \InvalidArgumentException When the wrong target object type is passed to an association.
  110. */
  111. private function set($field, $args)
  112. {
  113. if ($this->cm->hasField($field) && !$this->cm->isIdentifier($field)) {
  114. $this->$field = $args[0];
  115. } else if ($this->cm->hasAssociation($field) && $this->cm->isSingleValuedAssociation($field)) {
  116. $targetClass = $this->cm->getAssociationTargetClass($field);
  117. if (!($args[0] instanceof $targetClass) && $args[0] !== null) {
  118. throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'");
  119. }
  120. $this->$field = $args[0];
  121. $this->completeOwningSide($field, $targetClass, $args[0]);
  122. } else {
  123. throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
  124. }
  125. }
  126. /**
  127. * Gets a persistent field value.
  128. *
  129. * @param string $field
  130. *
  131. * @return mixed
  132. *
  133. * @throws \BadMethodCallException When no persistent field exists by that name.
  134. */
  135. private function get($field)
  136. {
  137. if ( $this->cm->hasField($field) || $this->cm->hasAssociation($field) ) {
  138. return $this->$field;
  139. }
  140. throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
  141. }
  142. /**
  143. * If this is an inverse side association, completes the owning side.
  144. *
  145. * @param string $field
  146. * @param ClassMetadata $targetClass
  147. * @param object $targetObject
  148. *
  149. * @return void
  150. */
  151. private function completeOwningSide($field, $targetClass, $targetObject)
  152. {
  153. // add this object on the owning side as well, for obvious infinite recursion
  154. // reasons this is only done when called on the inverse side.
  155. if ($this->cm->isAssociationInverseSide($field)) {
  156. $mappedByField = $this->cm->getAssociationMappedByTargetField($field);
  157. $targetMetadata = self::$objectManager->getClassMetadata($targetClass);
  158. $setter = ($targetMetadata->isCollectionValuedAssociation($mappedByField) ? "add" : "set").$mappedByField;
  159. $targetObject->$setter($this);
  160. }
  161. }
  162. /**
  163. * Adds an object to a collection.
  164. *
  165. * @param string $field
  166. * @param array $args
  167. *
  168. * @return void
  169. *
  170. * @throws \BadMethodCallException
  171. * @throws \InvalidArgumentException
  172. */
  173. private function add($field, $args)
  174. {
  175. if ($this->cm->hasAssociation($field) && $this->cm->isCollectionValuedAssociation($field)) {
  176. $targetClass = $this->cm->getAssociationTargetClass($field);
  177. if (!($args[0] instanceof $targetClass)) {
  178. throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'");
  179. }
  180. if (!($this->$field instanceof Collection)) {
  181. $this->$field = new ArrayCollection($this->$field ?: []);
  182. }
  183. $this->$field->add($args[0]);
  184. $this->completeOwningSide($field, $targetClass, $args[0]);
  185. } else {
  186. throw new \BadMethodCallException("There is no method add".$field."() on ".$this->cm->getName());
  187. }
  188. }
  189. /**
  190. * Initializes Doctrine Metadata for this class.
  191. *
  192. * @return void
  193. *
  194. * @throws \RuntimeException
  195. */
  196. private function initializeDoctrine()
  197. {
  198. if ($this->cm !== null) {
  199. return;
  200. }
  201. if (!self::$objectManager) {
  202. throw new \RuntimeException("No runtime object manager set. Call PersistentObject#setObjectManager().");
  203. }
  204. $this->cm = self::$objectManager->getClassMetadata(get_class($this));
  205. }
  206. /**
  207. * Magic methods.
  208. *
  209. * @param string $method
  210. * @param array $args
  211. *
  212. * @return mixed
  213. *
  214. * @throws \BadMethodCallException
  215. */
  216. public function __call($method, $args)
  217. {
  218. $this->initializeDoctrine();
  219. $command = substr($method, 0, 3);
  220. $field = lcfirst(substr($method, 3));
  221. if ($command == "set") {
  222. $this->set($field, $args);
  223. } else if ($command == "get") {
  224. return $this->get($field);
  225. } else if ($command == "add") {
  226. $this->add($field, $args);
  227. } else {
  228. throw new \BadMethodCallException("There is no method ".$method." on ".$this->cm->getName());
  229. }
  230. }
  231. }