PersistentObject.php 8.3KB

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