User Tools

Site Tools


urapidflow:v3:data_preprocess

Pre-process data before import

The example is simplified, without handling of errors for events like file open or write.

bootstrap.php
<?php
// initialize Magento environment
 
try {
//    if you move this file, adjust bootstrap.php path
    require __DIR__ . '/../../../../../app/bootstrap.php';
} catch (\Exception $e) {
    echo <<<HTML
{$e->getMessage()}
</div>
HTML;
    exit(1);
}
 
$params = $_SERVER;
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = 'admin'; // change this to appropriate store if needed.
$params[\Magento\Store\Model\Store::CUSTOM_ENTRY_POINT_PARAM] = true;
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params); // bootstrap
 
/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('Magento\Framework\App\Http');
 
// configure environment
$om = $bootstrap->getObjectManager();
$areaList = $om->get('Magento\Framework\App\AreaList');
$areaCode = $areaList->getCodeByFrontName('admin');
/** @var \Magento\Framework\App\State $state */
$state = $om->get('Magento\Framework\App\State');
$state->setAreaCode($areaCode);
/** @var \Magento\Framework\ObjectManager\ConfigLoaderInterface $configLoader */
$configLoader = $om->get('Magento\Framework\ObjectManager\ConfigLoaderInterface');
$om->configure($configLoader->load($areaCode));
// end initialize Magento environment
urapidflow.php
<?php
// load Magento libraries
include __DIR__ . '/bootstrap.php';
 
// open original file for reading
$fs = @fopen('var/urapidflow/import/source_file.csv', 'r');
if(!$fs){
    echo 'Source file not found', PHP_EOL;
    return;
}
 
// open file to be imported for writing
$fd = @fopen('var/urapidflow/import/products.csv', 'w');
if (!$fd) {
    echo 'Destination file not found', PHP_EOL;
    return;
}
 
// retrieve column names
$fieldColumns = fgetcsv($fs);
$first = true;
 
// iterate through file
while ($r = fgetcsv($fs)) {
    // get a row as associated array
    $row = array_combine($fieldColumns, $r);
 
    // perform your data modifications here
    // change existing columns
    $row['price'] *= 1.2;
 
    // or add new columns,
    // make sure that the new columns are always available
    // and order of columns is always the same
    $row['new_attribute'] = 'Static value';
 
    // output header
    if ($first) {
        fputcsv($fd, array_keys($row));
        $first = false;
    }
 
    // write the product row
    fputcsv($fd, $row);
}
// close files
fclose($fd);
fclose($fs);
 
// run the profile, which should be associated with final import file
$om->get('\Unirgy\RapidFlow\Helper\Data')->run('Your Import Profile');
urapidflow/v3/data_preprocess.txt · (external edit)