AbstractHydrator.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. namespace Doctrine\ORM\Internal\Hydration;
  20. use PDO,
  21. Doctrine\DBAL\Connection,
  22. Doctrine\DBAL\Types\Type,
  23. Doctrine\ORM\EntityManager,
  24. Doctrine\ORM\Events,
  25. Doctrine\ORM\Mapping\ClassMetadata;
  26. /**
  27. * Base class for all hydrators. A hydrator is a class that provides some form
  28. * of transformation of an SQL result set into another structure.
  29. *
  30. * @since 2.0
  31. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  32. * @author Roman Borschel <roman@code-factory.org>
  33. * @author Guilherme Blanco <guilhermeblanoc@hotmail.com>
  34. */
  35. abstract class AbstractHydrator
  36. {
  37. /** @var ResultSetMapping The ResultSetMapping. */
  38. protected $_rsm;
  39. /** @var EntityManager The EntityManager instance. */
  40. protected $_em;
  41. /** @var AbstractPlatform The dbms Platform instance */
  42. protected $_platform;
  43. /** @var UnitOfWork The UnitOfWork of the associated EntityManager. */
  44. protected $_uow;
  45. /** @var array The cache used during row-by-row hydration. */
  46. protected $_cache = array();
  47. /** @var Statement The statement that provides the data to hydrate. */
  48. protected $_stmt;
  49. /** @var array The query hints. */
  50. protected $_hints;
  51. /**
  52. * Initializes a new instance of a class derived from <tt>AbstractHydrator</tt>.
  53. *
  54. * @param \Doctrine\ORM\EntityManager $em The EntityManager to use.
  55. */
  56. public function __construct(EntityManager $em)
  57. {
  58. $this->_em = $em;
  59. $this->_platform = $em->getConnection()->getDatabasePlatform();
  60. $this->_uow = $em->getUnitOfWork();
  61. }
  62. /**
  63. * Initiates a row-by-row hydration.
  64. *
  65. * @param object $stmt
  66. * @param object $resultSetMapping
  67. *
  68. * @return IterableResult
  69. */
  70. public function iterate($stmt, $resultSetMapping, array $hints = array())
  71. {
  72. $this->_stmt = $stmt;
  73. $this->_rsm = $resultSetMapping;
  74. $this->_hints = $hints;
  75. $evm = $this->_em->getEventManager();
  76. $evm->addEventListener(array(Events::onClear), $this);
  77. $this->prepare();
  78. return new IterableResult($this);
  79. }
  80. /**
  81. * Hydrates all rows returned by the passed statement instance at once.
  82. *
  83. * @param object $stmt
  84. * @param object $resultSetMapping
  85. * @return mixed
  86. */
  87. public function hydrateAll($stmt, $resultSetMapping, array $hints = array())
  88. {
  89. $this->_stmt = $stmt;
  90. $this->_rsm = $resultSetMapping;
  91. $this->_hints = $hints;
  92. $this->prepare();
  93. $result = $this->hydrateAllData();
  94. $this->cleanup();
  95. return $result;
  96. }
  97. /**
  98. * Hydrates a single row returned by the current statement instance during
  99. * row-by-row hydration with {@link iterate()}.
  100. *
  101. * @return mixed
  102. */
  103. public function hydrateRow()
  104. {
  105. $row = $this->_stmt->fetch(PDO::FETCH_ASSOC);
  106. if ( ! $row) {
  107. $this->cleanup();
  108. return false;
  109. }
  110. $result = array();
  111. $this->hydrateRowData($row, $this->_cache, $result);
  112. return $result;
  113. }
  114. /**
  115. * Excutes one-time preparation tasks, once each time hydration is started
  116. * through {@link hydrateAll} or {@link iterate()}.
  117. */
  118. protected function prepare()
  119. {}
  120. /**
  121. * Excutes one-time cleanup tasks at the end of a hydration that was initiated
  122. * through {@link hydrateAll} or {@link iterate()}.
  123. */
  124. protected function cleanup()
  125. {
  126. $this->_rsm = null;
  127. $this->_stmt->closeCursor();
  128. $this->_stmt = null;
  129. }
  130. /**
  131. * Hydrates a single row from the current statement instance.
  132. *
  133. * Template method.
  134. *
  135. * @param array $data The row data.
  136. * @param array $cache The cache to use.
  137. * @param mixed $result The result to fill.
  138. */
  139. protected function hydrateRowData(array $data, array &$cache, array &$result)
  140. {
  141. throw new HydrationException("hydrateRowData() not implemented by this hydrator.");
  142. }
  143. /**
  144. * Hydrates all rows from the current statement instance at once.
  145. */
  146. abstract protected function hydrateAllData();
  147. /**
  148. * Processes a row of the result set.
  149. *
  150. * Used for identity-based hydration (HYDRATE_OBJECT and HYDRATE_ARRAY).
  151. * Puts the elements of a result row into a new array, grouped by the dql alias
  152. * they belong to. The column names in the result set are mapped to their
  153. * field names during this procedure as well as any necessary conversions on
  154. * the values applied. Scalar values are kept in a specfic key 'scalars'.
  155. *
  156. * @param array $data SQL Result Row
  157. * @param array &$cache Cache for column to field result information
  158. * @param array &$id Dql-Alias => ID-Hash
  159. * @param array &$nonemptyComponents Does this DQL-Alias has at least one non NULL value?
  160. *
  161. * @return array An array with all the fields (name => value) of the data row,
  162. * grouped by their component alias.
  163. */
  164. protected function gatherRowData(array $data, array &$cache, array &$id, array &$nonemptyComponents)
  165. {
  166. $rowData = array();
  167. foreach ($data as $key => $value) {
  168. // Parse each column name only once. Cache the results.
  169. if ( ! isset($cache[$key])) {
  170. switch (true) {
  171. // NOTE: Most of the times it's a field mapping, so keep it first!!!
  172. case (isset($this->_rsm->fieldMappings[$key])):
  173. $fieldName = $this->_rsm->fieldMappings[$key];
  174. $classMetadata = $this->_em->getClassMetadata($this->_rsm->declaringClasses[$key]);
  175. $cache[$key]['fieldName'] = $fieldName;
  176. $cache[$key]['type'] = Type::getType($classMetadata->fieldMappings[$fieldName]['type']);
  177. $cache[$key]['isIdentifier'] = $classMetadata->isIdentifier($fieldName);
  178. $cache[$key]['dqlAlias'] = $this->_rsm->columnOwnerMap[$key];
  179. break;
  180. case (isset($this->_rsm->scalarMappings[$key])):
  181. $cache[$key]['fieldName'] = $this->_rsm->scalarMappings[$key];
  182. $cache[$key]['type'] = Type::getType($this->_rsm->typeMappings[$key]);
  183. $cache[$key]['isScalar'] = true;
  184. break;
  185. case (isset($this->_rsm->metaMappings[$key])):
  186. // Meta column (has meaning in relational schema only, i.e. foreign keys or discriminator columns).
  187. $fieldName = $this->_rsm->metaMappings[$key];
  188. $classMetadata = $this->_em->getClassMetadata($this->_rsm->aliasMap[$this->_rsm->columnOwnerMap[$key]]);
  189. $cache[$key]['isMetaColumn'] = true;
  190. $cache[$key]['fieldName'] = $fieldName;
  191. $cache[$key]['dqlAlias'] = $this->_rsm->columnOwnerMap[$key];
  192. $cache[$key]['isIdentifier'] = isset($this->_rsm->isIdentifierColumn[$cache[$key]['dqlAlias']][$key]);
  193. break;
  194. default:
  195. // this column is a left over, maybe from a LIMIT query hack for example in Oracle or DB2
  196. // maybe from an additional column that has not been defined in a NativeQuery ResultSetMapping.
  197. continue 2;
  198. }
  199. }
  200. if (isset($cache[$key]['isScalar'])) {
  201. $value = $cache[$key]['type']->convertToPHPValue($value, $this->_platform);
  202. $rowData['scalars'][$cache[$key]['fieldName']] = $value;
  203. continue;
  204. }
  205. $dqlAlias = $cache[$key]['dqlAlias'];
  206. if ($cache[$key]['isIdentifier']) {
  207. $id[$dqlAlias] .= '|' . $value;
  208. }
  209. if (isset($cache[$key]['isMetaColumn'])) {
  210. if ( ! isset($rowData[$dqlAlias][$cache[$key]['fieldName']]) && $value !== null) {
  211. $rowData[$dqlAlias][$cache[$key]['fieldName']] = $value;
  212. if ($cache[$key]['isIdentifier']) {
  213. $nonemptyComponents[$dqlAlias] = true;
  214. }
  215. }
  216. continue;
  217. }
  218. // in an inheritance hierarchy the same field could be defined several times.
  219. // We overwrite this value so long we dont have a non-null value, that value we keep.
  220. // Per definition it cannot be that a field is defined several times and has several values.
  221. if (isset($rowData[$dqlAlias][$cache[$key]['fieldName']]) && $value === null) {
  222. continue;
  223. }
  224. $rowData[$dqlAlias][$cache[$key]['fieldName']] = $cache[$key]['type']->convertToPHPValue($value, $this->_platform);
  225. if ( ! isset($nonemptyComponents[$dqlAlias]) && $value !== null) {
  226. $nonemptyComponents[$dqlAlias] = true;
  227. }
  228. }
  229. return $rowData;
  230. }
  231. /**
  232. * Processes a row of the result set.
  233. *
  234. * Used for HYDRATE_SCALAR. This is a variant of _gatherRowData() that
  235. * simply converts column names to field names and properly converts the
  236. * values according to their types. The resulting row has the same number
  237. * of elements as before.
  238. *
  239. * @param array $data
  240. * @param array $cache
  241. *
  242. * @return array The processed row.
  243. */
  244. protected function gatherScalarRowData(&$data, &$cache)
  245. {
  246. $rowData = array();
  247. foreach ($data as $key => $value) {
  248. // Parse each column name only once. Cache the results.
  249. if ( ! isset($cache[$key])) {
  250. switch (true) {
  251. // NOTE: During scalar hydration, most of the times it's a scalar mapping, keep it first!!!
  252. case (isset($this->_rsm->scalarMappings[$key])):
  253. $cache[$key]['fieldName'] = $this->_rsm->scalarMappings[$key];
  254. $cache[$key]['isScalar'] = true;
  255. break;
  256. case (isset($this->_rsm->fieldMappings[$key])):
  257. $fieldName = $this->_rsm->fieldMappings[$key];
  258. $classMetadata = $this->_em->getClassMetadata($this->_rsm->declaringClasses[$key]);
  259. $cache[$key]['fieldName'] = $fieldName;
  260. $cache[$key]['type'] = Type::getType($classMetadata->fieldMappings[$fieldName]['type']);
  261. $cache[$key]['dqlAlias'] = $this->_rsm->columnOwnerMap[$key];
  262. break;
  263. case (isset($this->_rsm->metaMappings[$key])):
  264. // Meta column (has meaning in relational schema only, i.e. foreign keys or discriminator columns).
  265. $cache[$key]['isMetaColumn'] = true;
  266. $cache[$key]['fieldName'] = $this->_rsm->metaMappings[$key];
  267. $cache[$key]['dqlAlias'] = $this->_rsm->columnOwnerMap[$key];
  268. break;
  269. default:
  270. // this column is a left over, maybe from a LIMIT query hack for example in Oracle or DB2
  271. // maybe from an additional column that has not been defined in a NativeQuery ResultSetMapping.
  272. continue 2;
  273. }
  274. }
  275. $fieldName = $cache[$key]['fieldName'];
  276. switch (true) {
  277. case (isset($cache[$key]['isScalar'])):
  278. $rowData[$fieldName] = $value;
  279. break;
  280. case (isset($cache[$key]['isMetaColumn'])):
  281. $rowData[$cache[$key]['dqlAlias'] . '_' . $fieldName] = $value;
  282. break;
  283. default:
  284. $value = $cache[$key]['type']->convertToPHPValue($value, $this->_platform);
  285. $rowData[$cache[$key]['dqlAlias'] . '_' . $fieldName] = $value;
  286. }
  287. }
  288. return $rowData;
  289. }
  290. /**
  291. * Register entity as managed in UnitOfWork.
  292. *
  293. * @param \Doctrine\ORM\Mapping\ClassMetadata $class
  294. * @param object $entity
  295. * @param array $data
  296. *
  297. * @todo The "$id" generation is the same of UnitOfWork#createEntity. Remove this duplication somehow
  298. */
  299. protected function registerManaged(ClassMetadata $class, $entity, array $data)
  300. {
  301. if ($class->isIdentifierComposite) {
  302. $id = array();
  303. foreach ($class->identifier as $fieldName) {
  304. if (isset($class->associationMappings[$fieldName])) {
  305. $id[$fieldName] = $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']];
  306. } else {
  307. $id[$fieldName] = $data[$fieldName];
  308. }
  309. }
  310. } else {
  311. if (isset($class->associationMappings[$class->identifier[0]])) {
  312. $id = array($class->identifier[0] => $data[$class->associationMappings[$class->identifier[0]]['joinColumns'][0]['name']]);
  313. } else {
  314. $id = array($class->identifier[0] => $data[$class->identifier[0]]);
  315. }
  316. }
  317. $this->_em->getUnitOfWork()->registerManaged($entity, $id, $data);
  318. }
  319. /**
  320. * When executed in a hydrate() loop we have to clear internal state to
  321. * decrease memory consumption.
  322. */
  323. public function onClear($eventArgs)
  324. {
  325. }
  326. }