Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
BatchIterator.php
Go to the documentation of this file.
1 <?php
7 
10 
15 {
19  private $batchSize;
20 
24  private $select;
25 
29  private $minValue = 0;
30 
34  private $correlationName;
35 
39  private $rangeField;
40 
44  private $currentSelect;
45 
49  private $connection;
50 
54  private $iteration = 0;
55 
59  private $rangeFieldAlias;
60 
64  private $isValid = true;
65 
75  public function __construct(
76  Select $select,
77  $batchSize,
78  $correlationName,
79  $rangeField,
80  $rangeFieldAlias
81  ) {
82  $this->batchSize = $batchSize;
83  $this->select = $select;
84  $this->correlationName = $correlationName;
85  $this->rangeField = $rangeField;
86  $this->rangeFieldAlias = $rangeFieldAlias;
87  $this->connection = $select->getConnection();
88  }
89 
93  public function current()
94  {
95  if (null == $this->currentSelect) {
96  $this->currentSelect = $this->initSelectObject();
97  $itemsCount = $this->calculateBatchSize($this->currentSelect);
98  $this->isValid = $itemsCount > 0;
99  }
100  return $this->currentSelect;
101  }
102 
106  public function next()
107  {
108  if (null == $this->currentSelect) {
109  $this->current();
110  }
111  $select = $this->initSelectObject();
112  $itemsCountInSelect = $this->calculateBatchSize($select);
113  $this->isValid = $itemsCountInSelect > 0;
114  if ($this->isValid) {
115  $this->iteration++;
116  $this->currentSelect = $select;
117  } else {
118  $this->currentSelect = null;
119  }
120  return $this->currentSelect;
121  }
122 
126  public function key()
127  {
128  return $this->iteration;
129  }
130 
134  public function valid()
135  {
136  return $this->isValid;
137  }
138 
142  public function rewind()
143  {
144  $this->minValue = 0;
145  $this->currentSelect = null;
146  $this->iteration = 0;
147  $this->isValid = true;
148  }
149 
156  private function calculateBatchSize(Select $select)
157  {
158  $wrapperSelect = $this->connection->select();
159  $wrapperSelect->from(
160  $select,
161  [
162  new \Zend_Db_Expr('MAX(' . $this->rangeFieldAlias . ') as max'),
163  new \Zend_Db_Expr('COUNT(*) as cnt')
164  ]
165  );
166  $row = $this->connection->fetchRow($wrapperSelect);
167  $this->minValue = $row['max'];
168  return intval($row['cnt']);
169  }
170 
176  private function initSelectObject()
177  {
178  $object = clone $this->select;
179  $object->where(
180  $this->connection->quoteIdentifier($this->correlationName)
181  . '.' . $this->connection->quoteIdentifier($this->rangeField)
182  . ' > ?',
183  $this->minValue
184  );
185  $object->limit($this->batchSize);
189  $object->order($this->correlationName . '.' . $this->rangeField . ' ' . \Magento\Framework\DB\Select::SQL_ASC);
190  return $object;
191  }
192 }
__construct(Select $select, $batchSize, $correlationName, $rangeField, $rangeFieldAlias)
const SQL_ASC
Definition: Select.php:81