AbstractHydrator.php 10.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?php
/*
 *  $Id: Hydrate.php 3192 2007-11-19 17:55:23Z romanb $
 *
 * 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.doctrine-project.org>.
20 21
 */

22 23
namespace Doctrine\ORM\Internal\Hydration;

24
use Doctrine\DBAL\Connection,
25
    Doctrine\DBAL\Types\Type;
romanb's avatar
romanb committed
26

27
/**
28 29
 * Base class for all hydrators. A hydrator is a class that provides some form
 * of transformation of an SQL result set into another structure.
30 31
 *
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
32 33
 * @link        www.doctrine-project.org
 * @since       2.0
34 35
 * @version     $Revision: 3192 $
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
romanb's avatar
romanb committed
36
 * @author      Roman Borschel <roman@code-factory.org>
37
 */
38
abstract class AbstractHydrator
39
{
40
    /** @var ResultSetMapping The ResultSetMapping. */
41
    protected $_rsm;
42

43
    /** @var EntityManager The EntityManager instance. */
44
    protected $_em;
45

46 47 48
    /** @var AbstractPlatform The dbms Platform instance */
    protected $_platform;

49 50 51 52 53 54 55 56
    /** @var UnitOfWork The UnitOfWork of the associated EntityManager. */
    protected $_uow;

    /** @var array The cache used during row-by-row hydration. */
    protected $_cache = array();

    /** @var Statement The statement that provides the data to hydrate. */
    protected $_stmt;
57 58 59
    
    /** @var array The query hints. */
    protected $_hints;
60

61
    /**
62
     * Initializes a new instance of a class derived from <tt>AbstractHydrator</tt>.
63
     *
64
     * @param Doctrine\ORM\EntityManager $em The EntityManager to use.
65
     */
66
    public function __construct(\Doctrine\ORM\EntityManager $em)
67
    {
68
        $this->_em = $em;
69
        $this->_platform = $em->getConnection()->getDatabasePlatform();
70
        $this->_uow = $em->getUnitOfWork();
71
    }
72 73

    /**
74
     * Initiates a row-by-row hydration.
75
     *
76
     * @param object $stmt
77
     * @param object $resultSetMapping
78 79
     * @return IterableResult
     */
80
    public function iterate($stmt, $resultSetMapping, array $hints = array())
81 82
    {
        $this->_stmt = $stmt;
83
        $this->_rsm = $resultSetMapping;
84
        $this->_hints = $hints;
85
        $this->_prepare();
86
        return new IterableResult($this);
87 88 89 90
    }

    /**
     * Hydrates all rows returned by the passed statement instance at once.
91
     *
92
     * @param object $stmt
93
     * @param object $resultSetMapping
94
     * @return mixed
95
     */
96
    public function hydrateAll($stmt, $resultSetMapping, array $hints = array())
97
    {
98
        $this->_stmt = $stmt;
99
        $this->_rsm = $resultSetMapping;
100
        $this->_hints = $hints;
101
        $this->_prepare();
102
        $result = $this->_hydrateAll();
103 104
        $this->_cleanup();
        return $result;
105 106 107
    }

    /**
108 109
     * Hydrates a single row returned by the current statement instance during
     * row-by-row hydration with {@link iterate()}.
110
     *
111 112 113 114
     * @return mixed
     */
    public function hydrateRow()
    {
115
        $row = $this->_stmt->fetch(Connection::FETCH_ASSOC);
116 117 118 119 120 121 122 123 124 125 126 127 128
        if ( ! $row) {
            $this->_cleanup();
            return false;
        }
        $result = $this->_getRowContainer();
        $this->_hydrateRow($row, $this->_cache, $result);
        return $result;
    }

    /**
     * Excutes one-time preparation tasks once each time hydration is started
     * through {@link hydrateAll} or {@link iterate()}.
     */
129 130
    protected function _prepare()
    {}
131 132 133 134

    /**
     * Excutes one-time cleanup tasks at the end of a hydration that was initiated
     * through {@link hydrateAll} or {@link iterate()}.
135
     */
136
    protected function _cleanup()
137
    {
138
        $this->_rsm = null;
139 140
        $this->_stmt->closeCursor();
        $this->_stmt = null;
141 142 143
    }

    /**
144 145 146
     * Hydrates a single row from the current statement instance.
     *
     * Template method.
147
     *
148 149 150 151
     * @param array $data The row data.
     * @param array $cache The cache to use.
     * @param mixed $result The result to fill.
     */
152
    protected function _hydrateRow(array &$data, array &$cache, array &$result)
153
    {
154
        throw new HydrationException("_hydrateRow() not implemented by this hydrator.");
155
    }
156 157 158 159

    /**
     * Hydrates all rows from the current statement instance at once.
     */
160
    abstract protected function _hydrateAll();
161 162 163

    /**
     * Gets the row container used during row-by-row hydration through {@link iterate()}.
164
     */
165 166 167 168
    protected function _getRowContainer()
    {
        return array();        
    }
169 170 171

    /**
     * Processes a row of the result set.
172
     * Used for identity-based hydration (HYDRATE_OBJECT and HYDRATE_ARRAY).
173 174 175 176 177 178
     * Puts the elements of a result row into a new array, grouped by the class
     * they belong to. The column names in the result set are mapped to their
     * field names during this procedure as well as any necessary conversions on
     * the values applied.
     *
     * @return array  An array with all the fields (name => value) of the data row,
179
     *                grouped by their component alias.
180 181
     */
    protected function _gatherRowData(&$data, &$cache, &$id, &$nonemptyComponents)
182
    {
183 184 185 186 187
        $rowData = array();

        foreach ($data as $key => $value) {
            // Parse each column name only once. Cache the results.
            if ( ! isset($cache[$key])) {
188
                if (isset($this->_rsm->scalarMappings[$key])) {
189
                    $cache[$key]['fieldName'] = $this->_rsm->scalarMappings[$key];
190
                    $cache[$key]['isScalar'] = true;
191 192
                } else if (isset($this->_rsm->fieldMappings[$key])) {
                    $fieldName = $this->_rsm->fieldMappings[$key];
romanb's avatar
romanb committed
193
                    $classMetadata = $this->_em->getClassMetadata($this->_rsm->declaringClasses[$key]);
194
                    $cache[$key]['fieldName'] = $fieldName;
195
                    $cache[$key]['type'] = Type::getType($classMetadata->fieldMappings[$fieldName]['type']);
196
                    $cache[$key]['isIdentifier'] = $classMetadata->isIdentifier($fieldName);
197
                    $cache[$key]['dqlAlias'] = $this->_rsm->columnOwnerMap[$key];
198
                } else {
199 200 201
                    // Meta column (has meaning in relational schema only, i.e. foreign keys or discriminator columns).
                    $cache[$key]['isMetaColumn'] = true;
                    $cache[$key]['fieldName'] = $this->_rsm->metaMappings[$key];
202
                    $cache[$key]['dqlAlias'] = $this->_rsm->columnOwnerMap[$key];
203 204
                }
            }
romanb's avatar
romanb committed
205 206
            
            if (isset($cache[$key]['isScalar'])) {
207
                $rowData['scalars'][$cache[$key]['fieldName']] = $value;
208 209 210
                continue;
            }

211 212
            $dqlAlias = $cache[$key]['dqlAlias'];

213
            if (isset($cache[$key]['isMetaColumn'])) {
214
                $rowData[$dqlAlias][$cache[$key]['fieldName']] = $value;
215 216 217
                continue;
            }

218 219 220 221
            if ($cache[$key]['isIdentifier']) {
                $id[$dqlAlias] .= '|' . $value;
            }

222
            $rowData[$dqlAlias][$cache[$key]['fieldName']] = $cache[$key]['type']->convertToPHPValue($value, $this->_platform);
223 224 225 226 227 228 229

            if ( ! isset($nonemptyComponents[$dqlAlias]) && $value !== null) {
                $nonemptyComponents[$dqlAlias] = true;
            }
        }

        return $rowData;
230
    }
231

zYne's avatar
zYne committed
232
    /**
233 234
     * Processes a row of the result set.
     * Used for HYDRATE_SCALAR. This is a variant of _gatherRowData() that
romanb's avatar
romanb committed
235 236 237
     * simply converts column names to field names and properly converts the
     * values according to their types. The resulting row has the same number
     * of elements as before.
zYne's avatar
zYne committed
238
     *
239 240 241
     * @param array $data
     * @param array $cache
     * @return array The processed row.
zYne's avatar
zYne committed
242
     */
243
    protected function _gatherScalarRowData(&$data, &$cache)
zYne's avatar
zYne committed
244
    {
245 246 247 248 249
        $rowData = array();

        foreach ($data as $key => $value) {
            // Parse each column name only once. Cache the results.
            if ( ! isset($cache[$key])) {
250
                if (isset($this->_rsm->scalarMappings[$key])) {
251
                    $cache[$key]['fieldName'] = $this->_rsm->scalarMappings[$key];
252
                    $cache[$key]['isScalar'] = true;
romanb's avatar
romanb committed
253
                } else if (isset($this->_rsm->fieldMappings[$key])) {
254
                    $fieldName = $this->_rsm->fieldMappings[$key];
romanb's avatar
romanb committed
255
                    $classMetadata = $this->_em->getClassMetadata($this->_rsm->declaringClasses[$key]);
256
                    $cache[$key]['fieldName'] = $fieldName;
257
                    $cache[$key]['type'] = Type::getType($classMetadata->getTypeOfField($fieldName));
258
                    $cache[$key]['dqlAlias'] = $this->_rsm->columnOwnerMap[$key];
romanb's avatar
romanb committed
259 260 261 262 263
                } else {
                    // Meta column (has meaning in relational schema only, i.e. foreign keys or discriminator columns).
                    $cache[$key]['isMetaColumn'] = true;
                    $cache[$key]['fieldName'] = $this->_rsm->metaMappings[$key];
                    $cache[$key]['dqlAlias'] = $this->_rsm->columnOwnerMap[$key];
264 265
                }
            }
266
            
267 268
            $fieldName = $cache[$key]['fieldName'];

romanb's avatar
romanb committed
269 270 271 272
            if (isset($cache[$key]['isScalar'])) {
                $rowData[$fieldName] = $value;
            } else if (isset($cache[$key]['isMetaColumn'])) {
                $rowData[$cache[$key]['dqlAlias'] . '_' . $fieldName] = $value;
273
            } else {
romanb's avatar
romanb committed
274 275
                $rowData[$cache[$key]['dqlAlias'] . '_' . $fieldName] = $cache[$key]['type']
                        ->convertToPHPValue($value, $this->_platform);
276 277 278 279
            }
        }

        return $rowData;
zYne's avatar
zYne committed
280
    }
281
}