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