PersistentObject.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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\Persistence\Mapping\ClassMetadata;
  21. use Doctrine\Common\Collections\ArrayCollection;
  22. use Doctrine\Common\Collections\Collection;
  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. $this->initializeDoctrine();
  114. if ($this->cm->hasField($field) && !$this->cm->isIdentifier($field)) {
  115. $this->$field = $args[0];
  116. } else if ($this->cm->hasAssociation($field) && $this->cm->isSingleValuedAssociation($field)) {
  117. $targetClass = $this->cm->getAssociationTargetClass($field);
  118. if (!($args[0] instanceof $targetClass) && $args[0] !== null) {
  119. throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'");
  120. }
  121. $this->$field = $args[0];
  122. $this->completeOwningSide($field, $targetClass, $args[0]);
  123. } else {
  124. throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
  125. }
  126. }
  127. /**
  128. * Gets a persistent field value.
  129. *
  130. * @param string $field
  131. *
  132. * @return mixed
  133. *
  134. * @throws \BadMethodCallException When no persistent field exists by that name.
  135. */
  136. private function get($field)
  137. {
  138. $this->initializeDoctrine();
  139. if ( $this->cm->hasField($field) || $this->cm->hasAssociation($field) ) {
  140. return $this->$field;
  141. } else {
  142. throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
  143. }
  144. }
  145. /**
  146. * If this is an inverse side association, completes the owning side.
  147. *
  148. * @param string $field
  149. * @param ClassMetadata $targetClass
  150. * @param object $targetObject
  151. *
  152. * @return void
  153. */
  154. private function completeOwningSide($field, $targetClass, $targetObject)
  155. {
  156. // add this object on the owning side as well, for obvious infinite recursion
  157. // reasons this is only done when called on the inverse side.
  158. if ($this->cm->isAssociationInverseSide($field)) {
  159. $mappedByField = $this->cm->getAssociationMappedByTargetField($field);
  160. $targetMetadata = self::$objectManager->getClassMetadata($targetClass);
  161. $setter = ($targetMetadata->isCollectionValuedAssociation($mappedByField) ? "add" : "set").$mappedByField;
  162. $targetObject->$setter($this);
  163. }
  164. }
  165. /**
  166. * Adds an object to a collection.
  167. *
  168. * @param string $field
  169. * @param array $args
  170. *
  171. * @return void
  172. *
  173. * @throws \BadMethodCallException
  174. * @throws \InvalidArgumentException
  175. */
  176. private function add($field, $args)
  177. {
  178. $this->initializeDoctrine();
  179. if ($this->cm->hasAssociation($field) && $this->cm->isCollectionValuedAssociation($field)) {
  180. $targetClass = $this->cm->getAssociationTargetClass($field);
  181. if (!($args[0] instanceof $targetClass)) {
  182. throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'");
  183. }
  184. if (!($this->$field instanceof Collection)) {
  185. $this->$field = new ArrayCollection($this->$field ?: array());
  186. }
  187. $this->$field->add($args[0]);
  188. $this->completeOwningSide($field, $targetClass, $args[0]);
  189. } else {
  190. throw new \BadMethodCallException("There is no method add".$field."() on ".$this->cm->getName());
  191. }
  192. }
  193. /**
  194. * Initializes Doctrine Metadata for this class.
  195. *
  196. * @return void
  197. *
  198. * @throws \RuntimeException
  199. */
  200. private function initializeDoctrine()
  201. {
  202. if ($this->cm !== null) {
  203. return;
  204. }
  205. if (!self::$objectManager) {
  206. throw new \RuntimeException("No runtime object manager set. Call PersistentObject#setObjectManager().");
  207. }
  208. $this->cm = self::$objectManager->getClassMetadata(get_class($this));
  209. }
  210. /**
  211. * Magic methods.
  212. *
  213. * @param string $method
  214. * @param array $args
  215. *
  216. * @return mixed
  217. *
  218. * @throws \BadMethodCallException
  219. */
  220. public function __call($method, $args)
  221. {
  222. $command = substr($method, 0, 3);
  223. $field = lcfirst(substr($method, 3));
  224. if ($command == "set") {
  225. $this->set($field, $args);
  226. } else if ($command == "get") {
  227. return $this->get($field);
  228. } else if ($command == "add") {
  229. $this->add($field, $args);
  230. } else {
  231. throw new \BadMethodCallException("There is no method ".$method." on ".$this->cm->getName());
  232. }
  233. }
  234. }