function import_real_estate in Styled Google Map 8.2
Imports real estate data from csv data.
Parameters
\Drupal\taxonomy\TermInterface[] $terms:
$context:
1 string reference to 'import_real_estate'
- styled_google_map_data_install in modules/
data/ styled_google_map_data.install - Implements hook_install().
File
- modules/
data/ demo.batch.inc, line 9
Code
function import_real_estate($terms, &$context) {
// Read real estate data.
$demo_file = \Drupal::service('file_system')
->realpath(drupal_get_path('module', 'styled_google_map_data') . '/csv/demo.csv');
$file = new SplFileObject($demo_file, 'r');
$file
->setFlags(SplFileObject::READ_CSV);
if (empty($context['sandbox'])) {
$context['sandbox']['progress'] = 0;
// Check for the number of lines in the file.
$file
->seek(PHP_INT_MAX);
$context['sandbox']['max'] = $file
->key() + 1;
$file
->rewind();
$context['results']['max'] = $context['sandbox']['max'];
}
$data_storage = \Drupal::entityTypeManager()
->getStorage('real_estate');
$geo_wkt = \Drupal::service('geofield.wkt_generator');
$offset = $context['sandbox']['progress'] + 1;
foreach (new \LimitIterator($file, $offset, 100) as $row) {
if (empty($row[0])) {
continue;
}
$category = array_search($row[7], $terms);
$context['results']['created'][] = $row[0];
$item = $data_storage
->create([
'name' => $row[0],
'price' => $row[9],
'location' => $geo_wkt
->WktBuildPoint([
$row[11],
$row[10],
]),
'category' => $category,
]);
try {
$item
->save();
} catch (\Drupal\Core\Entity\EntityStorageException $e) {
\Drupal::logger('real_estate')
->error($e
->getMessage());
}
}
// Update our progress information.
$context['sandbox']['progress'] += 100;
if ($context['sandbox']['progress'] <= $context['sandbox']['max']) {
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
}
else {
$context['finished'] = 1;
}
$context['message'] = t('Running Batch, finished @percent%', [
'@percent' => round($context['sandbox']['progress'] / $context['sandbox']['max'] * 100, 2),
]);
}