Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
BatchInsert.php
Go to the documentation of this file.
1 <?php
7 namespace Magento\Setup\Model;
8 
13 {
17  private $resourceConnection;
18 
22  private $dbConnection;
23 
27  private $insertIntoTable;
28 
32  private $batchSize;
33 
37  private $dataStorage;
38 
42  private $currentStorageIndex = 0;
43 
49  public function __construct(
50  \Magento\Framework\App\ResourceConnection $resourceConnection,
51  $insertIntoTable,
52  $batchSize
53  ) {
54  $this->resourceConnection = $resourceConnection;
55  $this->insertIntoTable = $insertIntoTable;
56  $this->batchSize = $batchSize;
57  $this->dataStorage = new \SplFixedArray($batchSize);
58  }
59 
67  public function insert(array $dataToInsert)
68  {
69  $this->dataStorage[$this->currentStorageIndex] = $dataToInsert;
70  $this->currentStorageIndex++;
71 
72  if ($this->currentStorageIndex >= $this->batchSize) {
73  $this->flush();
74  }
75  }
76 
82  public function flush()
83  {
84  if ($this->currentStorageIndex > 0) {
85  if ($this->currentStorageIndex < $this->batchSize) {
86  $this->dataStorage->setSize($this->currentStorageIndex);
87  }
88 
89  $this->getDbConnection()
90  ->insertArray(
91  $this->insertIntoTable,
92  array_keys(reset($this->dataStorage)),
93  $this->dataStorage->toArray()
94  );
95 
96  $this->dataStorage = new \SplFixedArray($this->batchSize);
97  $this->currentStorageIndex = 0;
98  }
99  }
100 
108  private function getDbConnection()
109  {
110  if ($this->dbConnection === null) {
111  $this->dbConnection = $this->resourceConnection->getConnection();
112  }
113 
114  return $this->dbConnection;
115  }
116 }
__construct(\Magento\Framework\App\ResourceConnection $resourceConnection, $insertIntoTable, $batchSize)
Definition: BatchInsert.php:49
insert(array $dataToInsert)
Definition: BatchInsert.php:67