BatchProvider.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Indexer;
  7. use \Magento\Framework\DB\Adapter\AdapterInterface;
  8. /**
  9. * Generator of consecutive entity ID ranges that must be handled as a batch.
  10. *
  11. * Some ranges may contain non existent entity IDs.
  12. * So the code that uses the generator must check if any entities were loaded during batch load.
  13. */
  14. class BatchProvider implements BatchProviderInterface
  15. {
  16. /**
  17. * @inheritdoc
  18. */
  19. public function getBatches(AdapterInterface $adapter, $tableName, $linkField, $batchSize)
  20. {
  21. $maxLinkFieldValue = $adapter->fetchOne(
  22. $adapter->select()->from(
  23. ['entity' => $tableName],
  24. [
  25. 'max_value' => new \Zend_Db_Expr('MAX(entity.' . $linkField . ')')
  26. ]
  27. )
  28. );
  29. /** @var int $truncatedBatchSize size of the last batch that is smaller than expected batch size */
  30. $truncatedBatchSize = $maxLinkFieldValue % $batchSize;
  31. /** @var int $fullBatchCount count of the batches that have expected batch size */
  32. $fullBatchCount = ($maxLinkFieldValue - $truncatedBatchSize) / $batchSize;
  33. for ($batchIndex = 0; $batchIndex < $fullBatchCount; $batchIndex ++) {
  34. yield ['from' => $batchIndex * $batchSize + 1, 'to' => ($batchIndex + 1) * $batchSize];
  35. }
  36. // return the last batch if it has smaller size
  37. if ($truncatedBatchSize > 0) {
  38. yield ['from' => $fullBatchCount * $batchSize + 1, 'to' => $maxLinkFieldValue];
  39. }
  40. }
  41. /**
  42. * @inheritdoc
  43. */
  44. public function getBatchIds(
  45. \Magento\Framework\DB\Adapter\AdapterInterface $connection,
  46. \Magento\Framework\DB\Select $select,
  47. array $batch
  48. ) {
  49. $betweenCondition = sprintf(
  50. '(%s BETWEEN %s AND %s)',
  51. 'entity_id',
  52. $connection->quote($batch['from']),
  53. $connection->quote($batch['to'])
  54. );
  55. $ids = $connection->fetchCol($select->where($betweenCondition));
  56. return array_map('intval', $ids);
  57. }
  58. }