AbstractHydrator.php 14 KB

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