Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
BatchRangeIterator.php
Go to the documentation of this file.
1 <?php
8 
11 
25 {
29  private $currentSelect;
30 
34  private $rangeField;
35 
40  private $rangeFieldAlias;
41 
45  private $batchSize;
46 
50  private $connection;
51 
55  private $currentOffset = 0;
56 
60  private $totalItemCount;
61 
65  private $iteration = 0;
66 
70  private $select;
71 
75  private $correlationName;
76 
80  private $isValid = true;
81 
91  public function __construct(
92  Select $select,
93  $batchSize,
94  $correlationName,
95  $rangeField,
96  $rangeFieldAlias
97  ) {
98  $this->batchSize = $batchSize;
99  $this->select = $select;
100  $this->correlationName = $correlationName;
101  $this->rangeField = $rangeField;
102  $this->rangeFieldAlias = $rangeFieldAlias;
103  $this->connection = $select->getConnection();
104  }
105 
113  public function current()
114  {
115  if (null === $this->currentSelect) {
116  $this->isValid = $this->currentOffset < $this->totalItemCount;
117  $this->currentSelect = $this->initSelectObject();
118  }
119  return $this->currentSelect;
120  }
121 
129  public function key()
130  {
131  return $this->iteration;
132  }
133 
142  public function next()
143  {
144  if (null === $this->currentSelect) {
145  $this->current();
146  }
147  $this->isValid = $this->currentOffset < $this->totalItemCount;
148  $select = $this->initSelectObject();
149  if ($this->isValid) {
150  $this->iteration++;
151  $this->currentSelect = $select;
152  } else {
153  $this->currentSelect = null;
154  }
155  return $this->currentSelect;
156  }
157 
165  public function rewind()
166  {
167  $this->currentSelect = null;
168  $this->iteration = 0;
169  $this->isValid = true;
170  $this->totalItemCount = 0;
171  }
172 
178  public function valid()
179  {
180  return $this->isValid;
181  }
182 
190  private function initSelectObject()
191  {
192  $object = clone $this->select;
193 
194  if (!$this->totalItemCount) {
195  $wrapperSelect = $this->connection->select();
196  $wrapperSelect->from(
197  $object,
198  [
199  new \Zend_Db_Expr('COUNT(*) as cnt')
200  ]
201  );
202  $row = $this->connection->fetchRow($wrapperSelect);
203 
204  $this->totalItemCount = intval($row['cnt']);
205  }
206 
207  $rangeField = is_array($this->rangeField) ? $this->rangeField : [$this->rangeField];
208 
212  foreach ($rangeField as $field) {
213  $object->order($this->correlationName . '.' . $field . ' ' . \Magento\Framework\DB\Select::SQL_ASC);
214  }
215  $object->limit($this->batchSize, $this->currentOffset);
216  $this->currentOffset += $this->batchSize;
217 
218  return $object;
219  }
220 }
__construct(Select $select, $batchSize, $correlationName, $rangeField, $rangeFieldAlias)
const SQL_ASC
Definition: Select.php:81