Iterator.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. /**
  7. * Active record implementation
  8. */
  9. namespace Magento\Framework\Model\ResourceModel;
  10. use Magento\Framework\DB\Adapter\AdapterInterface;
  11. use Magento\Framework\Exception\LocalizedException;
  12. use Magento\Framework\Phrase;
  13. class Iterator extends \Magento\Framework\DataObject
  14. {
  15. /**
  16. * Walk over records fetched from query one by one using callback function
  17. *
  18. * @param \Zend_Db_Statement_Interface|\Magento\Framework\DB\Select|string $query
  19. * @param array|string $callbacks
  20. * @param array $args
  21. * @param AdapterInterface $connection
  22. * @return \Magento\Framework\Model\ResourceModel\Iterator
  23. */
  24. public function walk($query, array $callbacks, array $args = [], $connection = null)
  25. {
  26. $stmt = $this->_getStatement($query, $connection);
  27. $args['idx'] = 0;
  28. while ($row = $stmt->fetch()) {
  29. $args['row'] = $row;
  30. foreach ($callbacks as $callback) {
  31. $result = call_user_func($callback, $args);
  32. if (!empty($result)) {
  33. $args = array_merge($args, (array)$result);
  34. }
  35. }
  36. $args['idx']++;
  37. }
  38. return $this;
  39. }
  40. /**
  41. * Fetch Zend statement instance
  42. *
  43. * @param \Zend_Db_Statement_Interface|\Magento\Framework\DB\Select|string $query
  44. * @param AdapterInterface $connection
  45. * @return \Zend_Db_Statement_Interface
  46. * @throws LocalizedException
  47. */
  48. protected function _getStatement($query, AdapterInterface $connection = null)
  49. {
  50. if ($query instanceof \Zend_Db_Statement_Interface) {
  51. return $query;
  52. }
  53. if ($query instanceof \Zend_Db_Select) {
  54. return $query->query();
  55. }
  56. if (is_string($query)) {
  57. if (!$connection instanceof AdapterInterface) {
  58. throw new LocalizedException(
  59. new Phrase('The connection is invalid. Verify the connection and try again.')
  60. );
  61. }
  62. return $connection->query($query);
  63. }
  64. throw new LocalizedException(new Phrase('The query is invalid. Verify the query and try again.'));
  65. }
  66. }