Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
FieldDataConverter.php
Go to the documentation of this file.
1 <?php
6 namespace Magento\Framework\DB;
7 
13 
18 {
22  const BATCH_SIZE_VARIABLE_NAME = 'DATA_CONVERTER_BATCH_SIZE';
23 
27  const DEFAULT_BATCH_SIZE = 50000;
28 
32  private $queryGenerator;
33 
37  private $dataConverter;
38 
42  private $selectFactory;
43 
47  private $envBatchSize;
48 
57  public function __construct(
58  Generator $queryGenerator,
59  DataConverterInterface $dataConverter,
60  SelectFactory $selectFactory,
61  $envBatchSize = null
62  ) {
63  $this->queryGenerator = $queryGenerator;
64  $this->dataConverter = $dataConverter;
65  $this->selectFactory = $selectFactory;
66  $this->envBatchSize = $envBatchSize;
67  }
68 
80  public function convert(
82  $table,
83  $identifier,
84  $field,
85  QueryModifierInterface $queryModifier = null
86  ) {
87  $select = $this->selectFactory->create($connection)
88  ->from($table, [$identifier, $field])
89  ->where($field . ' IS NOT NULL');
90  if ($queryModifier) {
91  $queryModifier->modify($select);
92  }
93  $iterator = $this->queryGenerator->generate($identifier, $select, $this->getBatchSize());
94  foreach ($iterator as $selectByRange) {
95  $rows = $connection->fetchPairs($selectByRange);
96  $uniqueFieldDataArray = array_unique($rows);
97  foreach ($uniqueFieldDataArray as $uniqueFieldData) {
98  $ids = array_keys($rows, $uniqueFieldData);
99  try {
100  $convertedValue = $this->dataConverter->convert($uniqueFieldData);
101  if ($uniqueFieldData === $convertedValue) {
102  // Skip for data rows that have been already converted
103  continue;
104  }
105  $bind = [$field => $convertedValue];
106  $where = [$identifier . ' IN (?)' => $ids];
107  $connection->update($table, $bind, $where);
108  } catch (DataConversionException $e) {
109  throw new \Magento\Framework\DB\FieldDataConversionException(
110  sprintf(
112  $field,
113  $table,
114  $identifier,
115  implode(', ', $ids),
116  get_class($this->dataConverter),
117  $e->getMessage()
118  )
119  );
120  }
121  }
122  }
123  }
124 
130  private function getBatchSize()
131  {
132  if (null !== $this->envBatchSize) {
133  $batchSize = (int) $this->envBatchSize;
134  if (bccomp($this->envBatchSize, PHP_INT_MAX, 0) === 1 || $batchSize < 1) {
135  throw new \InvalidArgumentException(
136  'Invalid value for environment variable ' . self::BATCH_SIZE_VARIABLE_NAME . '. '
137  . 'Should be integer, >= 1 and < value of PHP_INT_MAX'
138  );
139  }
140  return $batchSize;
141  }
143  }
144 }
__construct(Generator $queryGenerator, DataConverterInterface $dataConverter, SelectFactory $selectFactory, $envBatchSize=null)
$connection
Definition: bulk.php:13
$table
Definition: trigger.php:14
convert(AdapterInterface $connection, $table, $identifier, $field, QueryModifierInterface $queryModifier=null)