Completed
Push — master ( 858d65...3ffc2a )
by Maciej
15s queued 14s
created

CollectionPersister::update()   C

Complexity

Conditions 8
Paths 8

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 8.6298

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 29
ccs 11
cts 14
cp 0.7856
rs 5.3846
cc 8
eloc 20
nc 8
nop 2
crap 8.6298
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\ODM\MongoDB\Persisters;
21
22
use Doctrine\ODM\MongoDB\DocumentManager;
23
use Doctrine\ODM\MongoDB\LockException;
24
use Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo;
25
use Doctrine\ODM\MongoDB\PersistentCollection\PersistentCollectionInterface;
26
use Doctrine\ODM\MongoDB\UnitOfWork;
27
use Doctrine\ODM\MongoDB\Utility\CollectionHelper;
28
29
/**
30
 * The CollectionPersister is responsible for persisting collections of embedded
31
 * or referenced documents. When a PersistentCollection is scheduledForDeletion
32
 * in the UnitOfWork by calling PersistentCollection::clear() or is
33
 * de-referenced in the domain application code, CollectionPersister::delete()
34
 * will be called. When documents within the PersistentCollection are added or
35
 * removed, CollectionPersister::update() will be called, which may set the
36
 * entire collection or delete/insert individual elements, depending on the
37
 * mapping strategy.
38
 *
39
 * @since       1.0
40
 */
41
class CollectionPersister
42
{
43
    /**
44
     * The DocumentManager instance.
45
     *
46
     * @var DocumentManager
47
     */
48
    private $dm;
49
50
    /**
51
     * The PersistenceBuilder instance.
52
     *
53
     * @var PersistenceBuilder
54
     */
55
    private $pb;
56
57
    /**
58
     * Constructs a new CollectionPersister instance.
59
     *
60
     * @param DocumentManager $dm
61
     * @param PersistenceBuilder $pb
62
     * @param UnitOfWork $uow
63
     */
64 783
    public function __construct(DocumentManager $dm, PersistenceBuilder $pb, UnitOfWork $uow)
65
    {
66 783
        $this->dm = $dm;
67 783
        $this->pb = $pb;
68 783
        $this->uow = $uow;
0 ignored issues
show
Bug introduced by
The property uow does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
69 783
    }
70
71
    /**
72
     * Deletes a PersistentCollection instance completely from a document using $unset.
73
     *
74
     * @param PersistentCollectionInterface $coll
75
     * @param array $options
76
     */
77 35
    public function delete(PersistentCollectionInterface $coll, array $options)
78
    {
79 35
        $mapping = $coll->getMapping();
80 35
        if ($mapping['isInverseSide']) {
81
            return; // ignore inverse side
82
        }
83 35
        if (CollectionHelper::isAtomic($mapping['strategy'])) {
84
            throw new \UnexpectedValueException($mapping['strategy'] . ' delete collection strategy should have been handled by DocumentPersister. Please report a bug in issue tracker');
85
        }
86 35
        list($propertyPath, $parent) = $this->getPathAndParent($coll);
87 35
        $query = array('$unset' => array($propertyPath => true));
88 35
        $this->executeQuery($parent, $query, $options);
89 34
    }
90
91
    /**
92
     * Updates a PersistentCollection instance deleting removed rows and
93
     * inserting new rows.
94
     *
95
     * @param PersistentCollectionInterface $coll
96
     * @param array $options
97
     */
98 99
    public function update(PersistentCollectionInterface $coll, array $options)
99
    {
100 99
        $mapping = $coll->getMapping();
101
102 99
        if ($mapping['isInverseSide']) {
103
            return; // ignore inverse side
104
        }
105
106 99
        switch ($mapping['strategy']) {
107
            case ClassMetadataInfo::STORAGE_STRATEGY_ATOMIC_SET:
108
            case ClassMetadataInfo::STORAGE_STRATEGY_ATOMIC_SET_ARRAY:
109
                throw new \UnexpectedValueException($mapping['strategy'] . ' update collection strategy should have been handled by DocumentPersister. Please report a bug in issue tracker');
110
111
            case ClassMetadataInfo::STORAGE_STRATEGY_SET:
112
            case ClassMetadataInfo::STORAGE_STRATEGY_SET_ARRAY:
113 10
                $this->setCollection($coll, $options);
114 10
                break;
115
116
            case ClassMetadataInfo::STORAGE_STRATEGY_ADD_TO_SET:
117
            case ClassMetadataInfo::STORAGE_STRATEGY_PUSH_ALL:
118 90
                $coll->initialize();
119 90
                $this->deleteElements($coll, $options);
120 90
                $this->insertElements($coll, $options);
121 89
                break;
122
123
            default:
124
                throw new \UnexpectedValueException('Unsupported collection strategy: ' . $mapping['strategy']);
125
        }
126 98
    }
127
128
    /**
129
     * Sets a PersistentCollection instance.
130
     *
131
     * This method is intended to be used with the "set" or "setArray"
132
     * strategies. The "setArray" strategy will ensure that the collection is
133
     * set as a BSON array, which means the collection elements will be
134
     * reindexed numerically before storage.
135
     *
136
     * @param PersistentCollectionInterface $coll
137
     * @param array $options
138
     */
139 10
    private function setCollection(PersistentCollectionInterface $coll, array $options)
140
    {
141 10
        list($propertyPath, $parent) = $this->getPathAndParent($coll);
142 10
        $coll->initialize();
143 10
        $mapping = $coll->getMapping();
144 10
        $setData = $this->pb->prepareAssociatedCollectionValue($coll, CollectionHelper::usesSet($mapping['strategy']));
145 10
        $query = array('$set' => array($propertyPath => $setData));
146 10
        $this->executeQuery($parent, $query, $options);
147 10
    }
148
149
    /**
150
     * Deletes removed elements from a PersistentCollection instance.
151
     *
152
     * This method is intended to be used with the "pushAll" and "addToSet"
153
     * strategies.
154
     *
155
     * @param PersistentCollectionInterface $coll
156
     * @param array $options
157
     */
158 90
    private function deleteElements(PersistentCollectionInterface $coll, array $options)
159
    {
160 90
        $deleteDiff = $coll->getDeleteDiff();
161
162 90
        if (empty($deleteDiff)) {
163 70
            return;
164
        }
165
166 29
        list($propertyPath, $parent) = $this->getPathAndParent($coll);
167
168 29
        $query = array('$unset' => array());
169
170 29
        foreach ($deleteDiff as $key => $document) {
171 29
            $query['$unset'][$propertyPath . '.' . $key] = true;
172
        }
173
174 29
        $this->executeQuery($parent, $query, $options);
175
176
        /**
177
         * @todo This is a hack right now because we don't have a proper way to
178
         * remove an element from an array by its key. Unsetting the key results
179
         * in the element being left in the array as null so we have to pull
180
         * null values.
181
         */
182 29
        $this->executeQuery($parent, array('$pull' => array($propertyPath => null)), $options);
183 29
    }
184
185
    /**
186
     * Inserts new elements for a PersistentCollection instance.
187
     *
188
     * This method is intended to be used with the "pushAll" and "addToSet"
189
     * strategies.
190
     *
191
     * @param PersistentCollectionInterface $coll
192
     * @param array $options
193
     */
194 90
    private function insertElements(PersistentCollectionInterface $coll, array $options)
195
    {
196 90
        $insertDiff = $coll->getInsertDiff();
197
198 90
        if (empty($insertDiff)) {
199 21
            return;
200
        }
201
202 75
        $mapping = $coll->getMapping();
203
204 75
        switch ($mapping['strategy']) {
205
            case ClassMetadataInfo::STORAGE_STRATEGY_PUSH_ALL:
206 71
                $operator = 'push';
207 71
                break;
208
209
            case ClassMetadataInfo::STORAGE_STRATEGY_ADD_TO_SET:
210 6
                $operator = 'addToSet';
211 6
                break;
212
213
            default:
214
                throw new \LogicException("Invalid strategy {$mapping['strategy']} given for insertElements");
215
        }
216
217 75
        list($propertyPath, $parent) = $this->getPathAndParent($coll);
218
219 75
        $callback = isset($mapping['embedded'])
220
            ? function($v) use ($mapping) { return $this->pb->prepareEmbeddedDocumentValue($mapping, $v); }
221
            : function($v) use ($mapping) { return $this->pb->prepareReferencedDocumentValue($mapping, $v); };
222
223 75
        $value = array_values(array_map($callback, $insertDiff));
224
225 75
        $query = ['$' . $operator => [$propertyPath => ['$each' => $value]]];
226
227 75
        $this->executeQuery($parent, $query, $options);
228 74
    }
229
230
    /**
231
     * Gets the parent information for a given PersistentCollection. It will
232
     * retrieve the top-level persistent Document that the PersistentCollection
233
     * lives in. We can use this to issue queries when updating a
234
     * PersistentCollection that is multiple levels deep inside an embedded
235
     * document.
236
     *
237
     *     <code>
238
     *     list($path, $parent) = $this->getPathAndParent($coll)
239
     *     </code>
240
     *
241
     * @param PersistentCollectionInterface $coll
242
     * @return array $pathAndParent
243
     */
244 110
    private function getPathAndParent(PersistentCollectionInterface $coll)
245
    {
246 110
        $mapping = $coll->getMapping();
247 110
        $fields = array();
248 110
        $parent = $coll->getOwner();
249 110
        while (null !== ($association = $this->uow->getParentAssociation($parent))) {
250 15
            list($m, $owner, $field) = $association;
251 15
            if (isset($m['reference'])) {
252
                break;
253
            }
254 15
            $parent = $owner;
255 15
            $fields[] = $field;
256
        }
257 110
        $propertyPath = implode('.', array_reverse($fields));
258 110
        $path = $mapping['name'];
259 110
        if ($propertyPath) {
260 15
            $path = $propertyPath . '.' . $path;
261
        }
262 110
        return array($path, $parent);
263
    }
264
265
    /**
266
     * Executes a query updating the given document.
267
     *
268
     * @param object $document
269
     * @param array $newObj
270
     * @param array $options
271
     */
272 110
    private function executeQuery($document, array $newObj, array $options)
273
    {
274 110
        $className = get_class($document);
275 110
        $class = $this->dm->getClassMetadata($className);
276 110
        $id = $class->getDatabaseIdentifierValue($this->uow->getDocumentIdentifier($document));
277 110
        $query = array('_id' => $id);
278 110
        if ($class->isVersioned) {
279 5
            $query[$class->fieldMappings[$class->versionField]['name']] = $class->reflFields[$class->versionField]->getValue($document);
280
        }
281 110
        $collection = $this->dm->getDocumentCollection($className);
282 110
        $result = $collection->update($query, $newObj, $options);
283 110
        if ($class->isVersioned && ! $result['n']) {
284 2
            throw LockException::lockFailed($document);
285
        }
286 108
    }
287
}
288