Hydrator.php 16.4 KB
Newer Older
1 2
<?php
/*
3
 *  $Id$
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
19
 * <http://www.phpdoctrine.org>.
20 21 22
 */

/**
23 24
 * The hydrator has the tedious task to construct object or array graphs out of
 * a database result set.
25 26
 *
 * @package     Doctrine
27
 * @subpackage  Hydrator
28
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
29
 * @link        www.phpdoctrine.org
30 31 32
 * @since       1.0
 * @version     $Revision: 3192 $
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
33
 * @author      Roman Borschel <roman@code-factory.org>
34
 */
35
class Doctrine_Hydrator extends Doctrine_Hydrator_Abstract
36
{
37 38 39
    /**
     * hydrateResultSet
     *
romanb's avatar
romanb committed
40
     * This is method defines the core of Doctrine's object population algorithm.
41 42 43 44 45 46 47
     *
     * The key idea is the loop over the rowset only once doing all the needed operations
     * within this massive loop.
     *
     * @todo: Detailed documentation. Refactor (too long & nesting level).
     *
     * @param mixed $stmt
48
     * @param array $aliasMap  Array that maps DQL aliases to their components
49 50 51 52
     *                         (DQL alias => array(
     *                              'table' => Table object,
     *                              'parent' => Parent DQL alias (if any),
     *                              'relation' => Relation object (if any),
53 54
     *                              'map' => Custom index to use as the key in the result (if any),
     *                              'agg' => List of aggregate values (sql alias => dql alias)
55
     *                              )
56
     *                         )
57
     * @return mixed  The created object/array graph.
58
     */
59
    public function hydrateResultSet($parserResult)
60
    {        
61
        if ($parserResult->getHydrationMode() === null) {
62
            $hydrationMode = $this->_hydrationMode;
63 64
        } else {
            $hydrationMode = $parserResult->getHydrationMode();
65
        }
66
        
67 68
        $stmt = $parserResult->getDatabaseStatement();
        
69 70 71
        if ($hydrationMode == Doctrine::HYDRATE_NONE) {
            return $stmt->fetchAll(PDO::FETCH_NUM);
        }
72

73 74
        $this->_tableAliases = $parserResult->getTableToClassAliasMap();
        $this->_queryComponents = $parserResult->getQueryComponents();
75

76
        if ($hydrationMode == Doctrine::HYDRATE_ARRAY) {
77
            $driver = new Doctrine_Hydrator_ArrayDriver();
78
        } else {
79
            $driver = new Doctrine_Hydrator_RecordDriver($this->_em);
80 81 82 83
        }

        $event = new Doctrine_Event(null, Doctrine_Event::HYDRATE, null);

84 85
        //$s = microtime(true);
        
86
        // Used variables during hydration
87
        reset($this->_queryComponents);
88

89
        $rootAlias = key($this->_queryComponents);
90
        $rootComponentName = $this->_queryComponents[$rootAlias]['table']->getComponentName();
91 92
        // if only one component is involved we can make our lives easier
        $isSimpleQuery = count($this->_queryComponents) <= 1;
93

94 95
        // Holds hydration listeners that get called during hydration
        $listeners = array();
96

romanb's avatar
romanb committed
97 98
        // Lookup map to quickly discover/lookup existing records in the result
        // It's the identifier "memory"
99
        $identifierMap = array();
100

101 102
        // Holds for each component the last previously seen element in the result set
        $prev = array();
103 104

        // Holds the values of the identifier/primary key fields of components,
105
        // separated by a pipe '|' and grouped by component alias (r, u, i, ... whatever)
romanb's avatar
romanb committed
106 107 108 109
        // the $idTemplate is a prepared template. $id is set to a fresh template when
        // starting to process a row.
        $id = array();
        $idTemplate = array();
110

111
        // Holds the resulting hydrated data structure
112
        $result = $driver->getElementCollection($rootComponentName);
113 114

        if ($stmt === false || $stmt === 0) {
115
            return $result;
116 117
        }

118
        // Initialize
119 120
        foreach ($this->_queryComponents as $dqlAlias => $component) {
            // disable lazy-loading of related elements during hydration
romanb's avatar
romanb committed
121
            $component['table']->setAttribute(Doctrine::ATTR_LOAD_REFERENCES, false);
122
            $componentName = $component['table']->getClassName();
romanb's avatar
romanb committed
123
            $listeners[$componentName] = $component['table']->getRecordListener();
124 125
            $identifierMap[$dqlAlias] = array();
            $prev[$dqlAlias] = array();
romanb's avatar
romanb committed
126
            $idTemplate[$dqlAlias] = '';
127
        }
128

129 130
        // Process result set
        $cache = array();
131

132
        while ($data = $stmt->fetch(Doctrine::FETCH_ASSOC)) {
romanb's avatar
romanb committed
133
            $id = $idTemplate; // initialize the id-memory
134 135
            $nonemptyComponents = array();
            $rowData = $this->_gatherRowData($data, $cache, $id, $nonemptyComponents);
136

137
            //
romanb's avatar
romanb committed
138
            // hydrate the data of the root entity from the current row
139
            //
140 141
            $class = $this->_queryComponents[$rootAlias]['table'];
            $componentName = $class->getComponentName();
142 143
            
            // just event stuff
144
            $event->set('data', $rowData[$rootAlias]);
145

146
            $listeners[$componentName]->preHydrate($event);
147

148
            $index = false;
149
            if ($isSimpleQuery || ! isset($identifierMap[$rootAlias][$id[$rootAlias]])) {
150 151 152
                $element = $driver->getElement($rowData[$rootAlias], $componentName);
                
                // just event stuff
153
                $event->set('data', $element);
154

155
                $listeners[$componentName]->postHydrate($event);
156
                //--
157

158 159 160
                // do we need to index by a custom field?
                if ($field = $this->_getCustomIndexField($rootAlias)) {
                    if (isset($result[$field])) {
161
                        throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found non-unique key mapping.");
162
                    } else if ( ! isset($element[$field])) {
163
                        throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found a non-existent key.");
164
                    }
165

166
                    $result[$element[$field]] = $element;
167
                } else {
168
                    $result[] = $element;
169 170
                }

171 172 173
                $identifierMap[$rootAlias][$id[$rootAlias]] = $driver->getLastKey($result);
            } else {
                $index = $identifierMap[$rootAlias][$id[$rootAlias]];
174 175
            }

176 177
            $this->_setLastElement($prev, $result, $index, $rootAlias, false);
            unset($rowData[$rootAlias]);
178 179
            // End hydrate data of the root component for the current row

180
            // $prev[$rootAlias] now points to the last element in $result.
181
            // now hydrate the rest of the data found in the current row, that belongs to other
182 183
            // (related) components.
            foreach ($rowData as $dqlAlias => $data) {
184
                $index = false;
185
                $map = $this->_queryComponents[$dqlAlias];
186
                $componentName = $map['table']->getComponentName();
187 188
                
                // just event stuff
189
                $event->set('data', $data);
190

191
                $listeners[$componentName]->preHydrate($event);
192
                //--
193

194
                $parent = $map['parent'];
195
                $relation = $map['relation'];
196
                $relationAlias = $relation->getAlias();
197

198
                $path = $parent . '.' . $dqlAlias;
199 200

                if ( ! isset($prev[$parent])) {
romanb's avatar
romanb committed
201
                    continue;
202 203 204
                }
                
                // check the type of the relation
205
                if ( ! $relation->isOneToOne()) {
206
                    $oneToOne = false;
207
                    // append element
208
                    if (isset($nonemptyComponents[$dqlAlias])) {
209
                        $driver->initRelatedCollection($prev[$parent], $relationAlias);
210
                        if ( ! isset($identifierMap[$path][$id[$parent]][$id[$dqlAlias]])) {
211
                            $element = $driver->getElement($data, $componentName);
212
                            
213
                            // just event stuff
214 215
                            $event->set('data', $element);
                            $listeners[$componentName]->postHydrate($event);
216
                            //--
217
                            
218
                            if ($field = $this->_getCustomIndexField($dqlAlias)) {
219 220
                                // TODO: we should check this earlier. Fields used in INDEXBY
                                //       must be unique. Then this can be removed here.
221
                                if (isset($prev[$parent][$relationAlias][$field])) {
222
                                    throw Doctrine_Hydrator_Exception::nonUniqueKeyMapping();
223
                                } else if ( ! isset($element[$field])) {
224
                                    throw Doctrine_Hydrator_Exception::nonExistantFieldUsedAsIndex($field);
225
                                }
226

227
                                $prev[$parent][$relationAlias][$element[$field]] = $element;
228
                            } else {
229
                                $prev[$parent][$relationAlias][] = $element;
230 231
                            }

232
                            $identifierMap[$path][$id[$parent]][$id[$dqlAlias]] = $driver->getLastKey($prev[$parent][$relationAlias]);
233
                        } else {
234
                            $index = $identifierMap[$path][$id[$parent]][$id[$dqlAlias]];
235
                        }
236
                        // register collection for later snapshots
237
                        //$driver->registerCollection($prev[$parent][$relationAlias]);
238 239
                    } else if ( ! isset($prev[$parent][$relationAlias])) {
                        $prev[$parent][$relationAlias] = $driver->getNullPointer();
240 241
                    }
                } else {
242 243
                    // 1-1 relation
                    $oneToOne = true; 
244

245 246
                    if ( ! isset($nonemptyComponents[$dqlAlias])) {
                        $prev[$parent][$relationAlias] = $driver->getNullPointer();
romanb's avatar
romanb committed
247
                    } else if ( ! isset($prev[$parent][$relationAlias])) {
248
                        $element = $driver->getElement($data, $componentName);
249
                        $prev[$parent][$relationAlias] = $element;
250 251
                    }
                }
252 253 254 255
                if ($prev[$parent][$relationAlias] !== null) {
                    $coll =& $prev[$parent][$relationAlias];
                    $this->_setLastElement($prev, $coll, $index, $dqlAlias, $oneToOne);
                }
256
            }
257
        }
258

259
        $stmt->closeCursor();
260
        $driver->flush();
261 262

        // Re-enable lazy loading
263
        foreach ($this->_queryComponents as $dqlAlias => $data) {
romanb's avatar
romanb committed
264
            $data['table']->setAttribute(Doctrine::ATTR_LOAD_REFERENCES, true);
265
        }
266

romanb's avatar
romanb committed
267
        //$e = microtime(true);
268
        //echo 'Hydration took: ' . ($e - $s) . ' for '.count($result).' records<br />';
269

270
        return $result;
271 272 273 274 275 276 277 278
    }

    /**
     * _setLastElement
     *
     * sets the last element of given data array / collection
     * as previous element
     *
279 280 281 282 283
     * @param array $prev  The array that contains the pointers to the latest element of each class.
     * @param array|Collection  The object collection.
     * @param boolean|integer $index  Index of the element in the collection.
     * @param string $dqlAlias
     * @param boolean $oneToOne  Whether it is a single-valued association or not.
284 285 286
     * @return void
     * @todo Detailed documentation
     */
287
    protected function _setLastElement(&$prev, &$coll, $index, $dqlAlias, $oneToOne)
288
    {
289
        if ($coll === $this->_nullObject) {
290 291
            return false;
        }
292

293
        if ($index !== false) {
294
            // Link element at $index to previous element for the component 
295
            // identified by the DQL alias $alias
296
            $prev[$dqlAlias] =& $coll[$index];
297 298
            return;
        }
299

300 301
        if (is_array($coll) && $coll) {
            if ($oneToOne) {
302
                $prev[$dqlAlias] =& $coll;
303
            } else {
304
                end($coll);
305
                $prev[$dqlAlias] =& $coll[key($coll)];
306
            }
307
        } else if ($coll instanceof Doctrine_Entity) {
romanb's avatar
romanb committed
308
            $prev[$dqlAlias] = $coll;
309
        } else if (count($coll) > 0) {
310 311 312
            $prev[$dqlAlias] = $coll->getLast();
        } else if (isset($prev[$dqlAlias])) {
            unset($prev[$dqlAlias]);
313 314
        }
    }
315 316


317
    /**
318 319
     * _gatherRowData
     *
320
     * Puts the fields of a data row into a new array, grouped by the component
321
     * they belong to. The column names in the result set are mapped to their
322 323
     * field names during this procedure.
     * 
324
     * @return array  An array with all the fields (name => value) of the data row,
325 326
     *                grouped by their component (alias).
     */
327
    protected function _gatherRowData(&$data, &$cache, &$id, &$nonemptyComponents)
328 329
    {
        $rowData = array();
330

331 332 333
        foreach ($data as $key => $value) {
            // Parse each column name only once. Cache the results.
            if ( ! isset($cache[$key])) {
334
                // cache general information like the column name <-> field name mapping
335
                $e = explode('__', $key);
336
                $columnName = strtolower(array_pop($e));                
337
                $cache[$key]['dqlAlias'] = $this->_tableAliases[strtolower(implode('__', $e))];
338
                $mapper = $this->_queryComponents[$cache[$key]['dqlAlias']]['mapper'];
339
                $classMetadata = $mapper->getClassMetadata();
340 341 342 343 344 345 346
                // check whether it's an aggregate value or a regular field
                if (isset($this->_queryComponents[$cache[$key]['dqlAlias']]['agg'][$columnName])) {
                    $fieldName = $this->_queryComponents[$cache[$key]['dqlAlias']]['agg'][$columnName];
                } else {
                    $fieldName = $mapper->getFieldName($columnName);
                }
                
347
                $cache[$key]['fieldName'] = $fieldName;
348 349
                
                // cache identifier information
350
                if ($classMetadata->isIdentifier($fieldName)) {
romanb's avatar
romanb committed
351
                    $cache[$key]['isIdentifier'] = true;
352 353 354
                } else {
                    $cache[$key]['isIdentifier'] = false;
                }
355 356
                
                // cache type information
357
                $type = $classMetadata->getTypeOfColumn($columnName);
358 359 360
                if ($type == 'integer' || $type == 'string') {
                    $cache[$key]['isSimpleType'] = true;
                } else {
361
                    $cache[$key]['type'] = $type;
362
                    $cache[$key]['isSimpleType'] = false;
romanb's avatar
romanb committed
363
                }
364 365
            }

366
            $mapper = $this->_queryComponents[$cache[$key]['dqlAlias']]['mapper'];
367
            $dqlAlias = $cache[$key]['dqlAlias'];
368 369
            $fieldName = $cache[$key]['fieldName'];

370
            if ($cache[$key]['isIdentifier']) {
371
                $id[$dqlAlias] .= '|' . $value;
372 373
            }

374 375 376
            if ($cache[$key]['isSimpleType']) {
                $rowData[$dqlAlias][$fieldName] = $value;
            } else {
377 378
                $rowData[$dqlAlias][$fieldName] = $mapper->prepareValue(
                        $fieldName, $value, $cache[$key]['type']);
379
            }
380

381 382
            if ( ! isset($nonemptyComponents[$dqlAlias]) && $value !== null) {
                $nonemptyComponents[$dqlAlias] = true;
383 384
            }
        }
385

386 387
        return $rowData;
    }
388 389 390 391 392


    /**
     * _getCustomIndexField
     *
393
     * Gets the custom field used for indexing for the specified component alias.
394
     *
395 396 397 398 399
     * @return string  The field name of the field used for indexing or NULL
     *                 if the component does not use any custom field indices.
     */
    protected function _getCustomIndexField($alias)
    {
400
        return isset($this->_queryComponents[$alias]['map']) ? $this->_queryComponents[$alias]['map'] : null;
401
    }
402

403
}