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