source: pro-violet-viettel/sourcecode/application/libraries/Doctrine/Common/Persistence/PersistentObject.php @ 356

Last change on this file since 356 was 345, checked in by quyenla, 11 years ago

collaborator page

File size: 8.1 KB
Line 
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 LGPL. For more information, see
17 * <http://www.doctrine-project.org>.
18 */
19
20namespace Doctrine\Common\Persistence;
21
22use Doctrine\Common\Persistence\Mapping\ClassMetadata;
23use Doctrine\Common\Collections\ArrayCollection;
24use 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 */
58abstract 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    public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata)
95    {
96        if ($objectManager !== self::$objectManager) {
97            throw new \RuntimeException("Trying to use PersistentObject with different ObjectManager instances. " .
98                "Was PersistentObject::setObjectManager() called?");
99        }
100
101        $this->cm = $classMetadata;
102    }
103
104    /**
105     * Sets a persistent fields value.
106     *
107     * @throws InvalidArgumentException - When the wrong target object type is passed to an association
108     * @throws BadMethodCallException - When no persistent field exists by that name.
109     * @param string $field
110     * @param array $args
111     * @return void
112     */
113    private function set($field, $args)
114    {
115        $this->initializeDoctrine();
116
117        if ($this->cm->hasField($field) && !$this->cm->isIdentifier($field)) {
118            $this->$field = $args[0];
119        } else if ($this->cm->hasAssociation($field) && $this->cm->isSingleValuedAssociation($field)) {
120            $targetClass = $this->cm->getAssociationTargetClass($field);
121            if (!($args[0] instanceof $targetClass) && $args[0] !== null) {
122                throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'");
123            }
124            $this->$field = $args[0];
125            $this->completeOwningSide($field, $targetClass, $args[0]);
126        } else {
127            throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
128        }
129    }
130
131    /**
132     * Get persistent field value.
133     *
134     * @throws BadMethodCallException - When no persistent field exists by that name.
135     * @param string $field
136     * @return mixed
137     */
138    private function get($field)
139    {
140        $this->initializeDoctrine();
141
142        if ( $this->cm->hasField($field) || $this->cm->hasAssociation($field) ) {
143            return $this->$field;
144        } else {
145            throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
146        }
147    }
148
149    /**
150     * If this is an inverse side association complete the owning side.
151     *
152     * @param string $field
153     * @param ClassMetadata $targetClass
154     * @param object $targetObject
155     */
156    private function completeOwningSide($field, $targetClass, $targetObject)
157    {
158        // add this object on the owning side aswell, for obvious infinite recursion
159        // reasons this is only done when called on the inverse side.
160        if ($this->cm->isAssociationInverseSide($field)) {
161            $mappedByField = $this->cm->getAssociationMappedByTargetField($field);
162            $targetMetadata = self::$objectManager->getClassMetadata($targetClass);
163
164            $setter = ($targetMetadata->isCollectionValuedAssociation($mappedByField) ? "add" : "set").$mappedByField;
165            $targetObject->$setter($this);
166        }
167    }
168
169    /**
170     * Add an object to a collection
171     *
172     * @param type $field
173     * @param assoc $args
174     */
175    private function add($field, $args)
176    {
177        $this->initializeDoctrine();
178
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    /**
195     * Initialize Doctrine Metadata for this class.
196     *
197     * @return void
198     */
199    private function initializeDoctrine()
200    {
201        if ($this->cm !== null) {
202            return;
203        }
204
205        if (!self::$objectManager) {
206            throw new \RuntimeException("No runtime object manager set. Call PersistentObject#setObjectManager().");
207        }
208
209        $this->cm = self::$objectManager->getClassMetadata(get_class($this));
210    }
211
212    /**
213     * Magic method that implements
214     *
215     * @param string $method
216     * @param array $args
217     * @return mixed
218     */
219    public function __call($method, $args)
220    {
221        $command = substr($method, 0, 3);
222        $field = lcfirst(substr($method, 3));
223        if ($command == "set") {
224            $this->set($field, $args);
225        } else if ($command == "get") {
226            return $this->get($field);
227        } else if ($command == "add") {
228            $this->add($field, $args);
229        } else {
230            throw new \BadMethodCallException("There is no method ".$method." on ".$this->cm->getName());
231        }
232    }
233}
Note: See TracBrowser for help on using the repository browser.