Failed Conditions
Pull Request — master (#1)
by Jonathan
13:22 queued 10:46
created

PersistentObject::set()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 10
cts 10
cp 1
rs 8.2222
c 0
b 0
f 0
cc 7
eloc 10
nc 4
nop 2
crap 7
1
<?php
2
namespace Doctrine\Common\Persistence;
3
4
use Doctrine\Common\Collections\ArrayCollection;
5
use Doctrine\Common\Collections\Collection;
6
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
7
8
/**
9
 * PersistentObject base class that implements getter/setter methods for all mapped fields and associations
10
 * by overriding __call.
11
 *
12
 * This class is a forward compatible implementation of the PersistentObject trait.
13
 *
14
 * Limitations:
15
 *
16
 * 1. All persistent objects have to be associated with a single ObjectManager, multiple
17
 *    ObjectManagers are not supported. You can set the ObjectManager with `PersistentObject#setObjectManager()`.
18
 * 2. Setters and getters only work if a ClassMetadata instance was injected into the PersistentObject.
19
 *    This is either done on `postLoad` of an object or by accessing the global object manager.
20
 * 3. There are no hooks for setters/getters. Just implement the method yourself instead of relying on __call().
21
 * 4. Slower than handcoded implementations: An average of 7 method calls per access to a field and 11 for an association.
22
 * 5. Only the inverse side associations get autoset on the owning side as well. Setting objects on the owning side
23
 *    will not set the inverse side associations.
24
 *
25
 * @example
26
 *
27
 *  PersistentObject::setObjectManager($em);
28
 *
29
 *  class Foo extends PersistentObject
30
 *  {
31
 *      private $id;
32
 *  }
33
 *
34
 *  $foo = new Foo();
35
 *  $foo->getId(); // method exists through __call
36
 *
37
 * @author Benjamin Eberlei <[email protected]>
38
 */
39
abstract class PersistentObject implements ObjectManagerAware
40
{
41
    /**
42
     * @var ObjectManager|null
43
     */
44
    private static $objectManager = null;
45
46
    /**
47
     * @var ClassMetadata|null
48
     */
49
    private $cm = null;
50
51
    /**
52
     * Sets the object manager responsible for all persistent object base classes.
53
     *
54
     * @param ObjectManager|null $objectManager
55
     *
56
     * @return void
57
     */
58 18
    public static function setObjectManager(ObjectManager $objectManager = null)
59
    {
60 18
        self::$objectManager = $objectManager;
61 18
    }
62
63
    /**
64
     * @return ObjectManager|null
65
     */
66 1
    public static function getObjectManager()
67
    {
68 1
        return self::$objectManager;
69
    }
70
71
    /**
72
     * Injects the Doctrine Object Manager.
73
     *
74
     * @param ObjectManager $objectManager
75
     * @param ClassMetadata $classMetadata
76
     *
77
     * @return void
78
     *
79
     * @throws \RuntimeException
80
     */
81 18
    public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata)
82
    {
83 18
        if ($objectManager !== self::$objectManager) {
84 1
            throw new \RuntimeException("Trying to use PersistentObject with different ObjectManager instances. " .
85 1
                "Was PersistentObject::setObjectManager() called?");
86
        }
87
88 18
        $this->cm = $classMetadata;
89 18
    }
90
91
    /**
92
     * Sets a persistent fields value.
93
     *
94
     * @param string $field
95
     * @param array  $args
96
     *
97
     * @return void
98
     *
99
     * @throws \BadMethodCallException   When no persistent field exists by that name.
100
     * @throws \InvalidArgumentException When the wrong target object type is passed to an association.
101
     */
102 7
    private function set($field, $args)
103
    {
104 7
        if ($this->cm->hasField($field) && ! $this->cm->isIdentifier($field)) {
0 ignored issues
show
Bug introduced by
The method hasField() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

104
        if ($this->cm->/** @scrutinizer ignore-call */ hasField($field) && ! $this->cm->isIdentifier($field)) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
105 1
            $this->$field = $args[0];
106 6
        } elseif ($this->cm->hasAssociation($field) && $this->cm->isSingleValuedAssociation($field)) {
107 4
            $targetClass = $this->cm->getAssociationTargetClass($field);
108 4
            if ( ! ($args[0] instanceof $targetClass) && $args[0] !== null) {
109 1
                throw new \InvalidArgumentException("Expected persistent object of type '" . $targetClass . "'");
110
            }
111 3
            $this->$field = $args[0];
112 3
            $this->completeOwningSide($field, $targetClass, $args[0]);
0 ignored issues
show
Bug introduced by
$targetClass of type string is incompatible with the type Doctrine\Common\Persistence\Mapping\ClassMetadata expected by parameter $targetClass of Doctrine\Common\Persiste...t::completeOwningSide(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

112
            $this->completeOwningSide($field, /** @scrutinizer ignore-type */ $targetClass, $args[0]);
Loading history...
113
        } else {
114 2
            throw new \BadMethodCallException("no field with name '" . $field . "' exists on '" . $this->cm->getName() . "'");
115
        }
116 4
    }
117
118
    /**
119
     * Gets a persistent field value.
120
     *
121
     * @param string $field
122
     *
123
     * @return mixed
124
     *
125
     * @throws \BadMethodCallException When no persistent field exists by that name.
126
     */
127 8
    private function get($field)
128
    {
129 8
        if ($this->cm->hasField($field) || $this->cm->hasAssociation($field)) {
130 7
            return $this->$field;
131
        }
132
133 1
        throw new \BadMethodCallException("no field with name '" . $field . "' exists on '" . $this->cm->getName() . "'");
134
    }
135
136
    /**
137
     * If this is an inverse side association, completes the owning side.
138
     *
139
     * @param string        $field
140
     * @param ClassMetadata $targetClass
141
     * @param object        $targetObject
142
     *
143
     * @return void
144
     */
145 3
    private function completeOwningSide($field, $targetClass, $targetObject)
146
    {
147
        // add this object on the owning side as well, for obvious infinite recursion
148
        // reasons this is only done when called on the inverse side.
149 3
        if ($this->cm->isAssociationInverseSide($field)) {
150 1
            $mappedByField  = $this->cm->getAssociationMappedByTargetField($field);
151 1
            $targetMetadata = self::$objectManager->getClassMetadata($targetClass);
0 ignored issues
show
Bug introduced by
$targetClass of type Doctrine\Common\Persistence\Mapping\ClassMetadata is incompatible with the type string expected by parameter $className of Doctrine\Common\Persiste...ger::getClassMetadata(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

151
            $targetMetadata = self::$objectManager->getClassMetadata(/** @scrutinizer ignore-type */ $targetClass);
Loading history...
Bug introduced by
The method getClassMetadata() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

151
            /** @scrutinizer ignore-call */ 
152
            $targetMetadata = self::$objectManager->getClassMetadata($targetClass);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
152
153 1
            $setter = ($targetMetadata->isCollectionValuedAssociation($mappedByField) ? "add" : "set") . $mappedByField;
154 1
            $targetObject->$setter($this);
155
        }
156 3
    }
157
158
    /**
159
     * Adds an object to a collection.
160
     *
161
     * @param string $field
162
     * @param array  $args
163
     *
164
     * @return void
165
     *
166
     * @throws \BadMethodCallException
167
     * @throws \InvalidArgumentException
168
     */
169 3
    private function add($field, $args)
170
    {
171 3
        if ($this->cm->hasAssociation($field) && $this->cm->isCollectionValuedAssociation($field)) {
172 2
            $targetClass = $this->cm->getAssociationTargetClass($field);
173 2
            if ( ! ($args[0] instanceof $targetClass)) {
174 1
                throw new \InvalidArgumentException("Expected persistent object of type '" . $targetClass . "'");
175
            }
176 1
            if ( ! ($this->$field instanceof Collection)) {
177 1
                $this->$field = new ArrayCollection($this->$field ?: []);
178
            }
179 1
            $this->$field->add($args[0]);
180 1
            $this->completeOwningSide($field, $targetClass, $args[0]);
0 ignored issues
show
Bug introduced by
$targetClass of type string is incompatible with the type Doctrine\Common\Persistence\Mapping\ClassMetadata expected by parameter $targetClass of Doctrine\Common\Persiste...t::completeOwningSide(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

180
            $this->completeOwningSide($field, /** @scrutinizer ignore-type */ $targetClass, $args[0]);
Loading history...
181
        } else {
182 1
            throw new \BadMethodCallException("There is no method add" . $field . "() on " . $this->cm->getName());
183
        }
184 1
    }
185
186
    /**
187
     * Initializes Doctrine Metadata for this class.
188
     *
189
     * @return void
190
     *
191
     * @throws \RuntimeException
192
     */
193 16
    private function initializeDoctrine()
194
    {
195 16
        if ($this->cm !== null) {
196 14
            return;
197
        }
198
199 3
        if ( ! self::$objectManager) {
200 1
            throw new \RuntimeException("No runtime object manager set. Call PersistentObject#setObjectManager().");
201
        }
202
203 2
        $this->cm = self::$objectManager->getClassMetadata(get_class($this));
204 2
    }
205
206
    /**
207
     * Magic methods.
208
     *
209
     * @param string $method
210
     * @param array  $args
211
     *
212
     * @return mixed
213
     *
214
     * @throws \BadMethodCallException
215
     */
216 16
    public function __call($method, $args)
217
    {
218 16
        $this->initializeDoctrine();
219
220 15
        $command = substr($method, 0, 3);
221 15
        $field   = lcfirst(substr($method, 3));
222 15
        if ($command == "set") {
223 7
            $this->set($field, $args);
224 12
        } elseif ($command == "get") {
225 8
            return $this->get($field);
226 5
        } elseif ($command == "add") {
227 3
            $this->add($field, $args);
228
        } else {
229 2
            throw new \BadMethodCallException("There is no method " . $method . " on " . $this->cm->getName());
230
        }
231 4
    }
232
}
233