cforge-2.0.x-dev/modules/cforge_import/src/Plugin/CsvParser/Smallads.php
modules/cforge_import/src/Plugin/CsvParser/Smallads.php
<?php
namespace Drupal\cforge_import\Plugin\CsvParser;
use Drupal\smallads\Entity\Smallad;
use Drupal\file\Entity\File;
use Drupal\taxonomy\Entity\Term;
use Drupal\field\Entity\FieldConfig;
/**
* Base class for importing smallads from csv file.
*/
abstract class Smallads extends ImportBase {
/**
* {@inheritDoc}
*/
public static function deleteAll() {
$entities = \Drupal::entityTypeManager()
->getStorage('smallad')
->loadByProperties(['type' => static::BUNDLE]);
foreach ($entities as $entity) {
$entity->delete();
}
}
/**
* {@inheritDoc}
*/
public function ready() : bool {
// Can only import if there is more than one user and more than one category
$users = \Drupal::entityQuery('user')->count()->execute();
if (count($users) > 1) return FALSE;
// There must be more than category
$cats = \Drupal::entityQuery('taxonomy_term')
->condition('vid', 'categories')
->execute();
return count($cats) > 1;
}
/**
* {@inheritDoc}
*/
public function columns() {
return [
'name' => t('unique login name of owner user'),
'title' => t('title of ad'),
'body' => t('body of ad, in html'),
'created' => t('item created date, format: "2016-01-15 19:10:33'),
'changed' => t('last changed date, format: "2016-01-15 19:10:33"'),
'scope' => t('0 means just the owner, 2 means every authenticated user can see it'),
'expires' => t('Expiry date in any format known to php date()')
];
}
/**
* {@inheritDoc}
*/
public function makeBatch($rows, $delete = FALSE, $test = TRUE) {
foreach (FieldConfig::loadMultiple() as $field) {
if ($field->getTargetEntityTypeId() == 'smallad' && $field->getName() == 'image') {
$dir = 'public://' . $field->getSetting('file_directory');
if (!file_exists($dir)) {
\Drupal\Core\File\FileSystem::mkdir($dir, 509, 8);
\Drupal::messenger()->addStatus("Created directory $dir");
}
}
}
$batch = parent::makeBatch($rows, $delete, $test);
$batch['title'] = 'Importing ' . $this->getPluginDefinition()['label'];
return $batch;
}
public function buildEntity(array $fields) {
parent::buildEntity($fields);
if (!isset($fields['expires'])) {
$unixtime = strtotime($fields['changed']??$fields['created']);
$default_expiry = \Drupal::config('smallads.settings')->get('default_expiry');
$this->entity->expires = strtotime($default_expiry, $unixtime);
}
elseif ($unixtime = strtotime($fields['expires'])) {
if ($unixtime < \Drupal::time()->getCurrentTime()) {
$this->entity->scope = 0;
}
}
}
/**
* Preprocessing for csv field 'body'.
*/
public function bodyProcess($val) {
$this->entity->body->value = $val;
$this->entity->body->format = 'basic_html';
}
/**
* Preprocessing for csv field 'uid'.
*/
public function uidProcess($val) {
$this->entity->setOwnerId($val);
}
/**
* Preprocessing for csv field 'categories'.
*/
public function categoriesProcess($val) {
if ($vals = array_filter(explode(';', $val))) {
$existing_terms = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadByProperties(['name' => $vals, 'vid' => SMALLAD_CATEGORIES_VID]);
// Key the existing terms by name so we can look them up.
foreach ($existing_terms as $term) {
$terms[$term->label()] = $term;
}
$categories = [];
foreach ($vals as $term_name) {
$term_name = trim($term_name);
if (!isset($terms[$term_name])) {
$term = Term::Create(['name' => $term_name, 'vid' => SMALLAD_CATEGORIES_VID]);
$term->save();
\Drupal::messenger()->addStatus('Created new term ' . $term_name);
$terms[$term_name] = $term;
}
$categories[]['target_id'] = $terms[$term_name]->id();
}
$this->entity->categories->setvalue($categories);
}
}
/**
* Preprocessing for csv field 'picture'.
*/
public function pictureProcess($val) {
if ($val) {
$field = FieldConfig::load('smallad.' . static::BUNDLE . '.image');
$newpath = 'public://'
. $field->getSetting('file_directory') . '/'
. pathinfo($val)['basename'];
if (!file_exists($newpath)) {
if (!copy($val, $newpath)) {
\Drupal::messenger()->addStatus('Small ad not presaved. Unable to copy image to ' . $newpath);
return;
}
}
$file = File::create(['uri' => $newpath]);
$file->save();
$this->entity->set('image', $file);
$this->entity->save();
}
}
/**
* Preprocessing for csv field 'name'.
*/
public function nameProcess($val) {
$uids = \Drupal::entityQuery('user')->condition('name', $val)->execute();
if (!$uids) {
\Drupal::messenger()->addStatus('User not identified for name ' . $val);
return;
}
$this->entity->setOwnerId(reset($uids));
}
/**
* Preprocessing for csv field 'scope'.
*/
public function scopeProcess($val) {
$this->entity->scope->value = $val ? Smallad::SCOPE_SITE : Smallad::SCOPE_PRIVATE;
}
/**
* Preprocessing for csv field 'expires'.
*/
public function expiresProcess($val) {
if (empty($val)) {
$val = \Drupal::config('smallads.settings')->get('expires');
}
$unixtime = strtotime($val);
$date = date('Y-m-d', $unixtime);
$this->entity->expires->setValue($date);
}
}
