cforge-2.0.x-dev/src/Plugin/CsvParser/Users.php

src/Plugin/CsvParser/Users.php
<?php

namespace Drupal\cforge\Plugin\CsvParser;
use Drupal\cforge_address\Entity\Neighbourhood;
use Drupal\cforge\Plugin\Field\FieldType\ContactMeItem;
use Drupal\Core\File\FileSystemInterface;
use GuzzleHttp\Client;
use Drupal\field\Entity\FieldConfig;

/**
 * Plugin to import users.
 *
 * @Plugin(
 *   id = "users",
 *   label = "Users"
 * )
 */
class Users extends \Drupal\cforge_import\Plugin\CsvParser\Users {

  /**
   * {@inheritDoc}
   */
  public function columns() {
    $fields = parent::columns() + [
      'present' => t('TRUE if the user is currently participating, defaults to TRUE'),
      'user_picture' => t('absolute url of image file'),
      'notes' => t("'about me' text in html"),
      'notes_admin' => t('plaintext notes visible only to committee'),
      'firstname' => t('first name*'),
      'lastname' => t('last name'),
      'address.address_line1' => t('address line 1'),
      'address.address_line2' => t('address line 2'),
      'address.dependent_locality' => t('Neighbourhood name (N.B references node type.*'),
      'address.locality' => t('City/town'),
      'address.administrative_area' => t('Region/Province'),
      // 'address.postal_code', we have  no way to force these to be valid.
      'address.country_code' => t('2 digit country code (default is @default)', ['@default' => \Drupal::config('system.date')->get('country.default')]),
      'show_phone' => t('0 or 1 to reveal phone number(s) to other members'),
      'show_address' => t('0 or 1 to reveal address to other members'),
      'show_email' => t('0 or 1 to reveal definitive email to other members'),
      // 'grossincome' => t('gross income (instead of transaction import)'),
      // 'balance' => t('current balance (instead of transaction import)')
    ];
    if (\Drupal::moduleHandler()->moduleExists('cforge_broadcast')){
      $fields['broadcast_optout'] = t('0 or 1 to NOT receive broadcasts');
    }
    if (\Drupal::moduleHandler()->moduleExists('cforge_network')){
      $fields['lat'] = 'float';
      $fields['lon'] = 'float';
      $fields['coordinates'] = 'string lat,lon';
    }
    foreach (ContactMeItem::CHANNELS as $sm => $info) {
      $fields['contactme.'.$sm] = t($info['title']);
    }
    return $fields;
  }

  public static function deleteAll() {
    parent::deleteAll();
    $user_data = \Drupal::service('user.data');
    $user_data->delete('cforge_broadcast', NULL, 'optout');
    $user_data->delete('cforge', NULL, 'show_phone');
    $user_data->delete('cforge', NULL, 'show_email');
    $user_data->delete('cforge', NULL, 'show_address');
    if (class_exists('Drupal\cforge_address\Entity\Neighbourhood')) {
      foreach (Neighbourhood::loadMultiple() as $n) {
        $n->delete();
      }
    }
  }

  protected function broadcast_optoutPostProcess($val) {
    // need the uid
    if ($val) {
      \Drupal::service('user.data')->set('cforge_broadcast', $this->entity->id(), 'optout', TRUE);
    }
  }

  protected function latProcess($val) {
    $this->entity->coordinates->lat = (float)$val;
  }
  protected function lonProcess($val) {
    $this->entity->coordinates->lon = (float)$val;
  }

  protected function coordinatesProcess($val) {
    [$lat, $lon] = explode(',', $val);
    $this->latProcess($lat);
    $this->lonProcess($lon);
  }

  /**
   * Preprocessing for csv field 'address_dependent_locality'.
   *
   * @note Eventually this field will be a group and thus the address will
   * reference it.
   */
  protected function address_dependent_localityProcess($val) {
    if ($val) {
      if (\Drupal::moduleHandler()->moduleExists('cforge_address')) {
        if (!\Drupal::entityQuery('neighbourhood')->condition('label', $val)->execute()) {
          Neighbourhood::Create(['label' => $val])->save();
        }
        else {
          \Drupal::messenger()->addWarning('Address_dependent_locality is a required field for user '.reset($this->fields));
        }
      }
      $this->entity->address->dependent_locality = $val;
    }
  }

  /**
   * Preprocessing for csv field 'firstname'.
   */
  protected function firstnameProcess($val) {
    if ($val) {
      $this->entity->address->given_name = $val;
    }
  }

  /**
   * Preprocessing for csv field 'firstname'.
   */
  protected function lastnameProcess($val) {
    if ($val) {
      $this->entity->address->family_name = $val;
    }
  }

  /**
   * Preprocessing for csv field 'notes'.
   */
  protected function notesProcess($val) {
    if ($val) {
      $val = str_replace('<br />', '\n', $val);
      $this->entity->set('notes', $val);
    }
  }

  /**
   * Preprocessing for csv field 'user_picture'.
   */
  protected function user_picturePostProcess($val) {
    if ($val) {
      $client = new Client(['allow_redirects' => ['max' => 5]]);
      $headers = get_headers($val, 1)['Location'];
      $pic_url = is_array($headers) ? end($headers) : $headers;
      $pic_dir = FieldConfig::load('user.user.user_picture')->getSetting('file_directory');
      $uri = "private://$pic_dir/". basename($pic_url);
      $file = \Drupal::service('file.repository')->writeData(
        $client->get($val)->getBody()->getContents(), $uri, FileSystemInterface::EXISTS_REPLACE
      );
      $this->entity->save();// save the user
      $file->set('uid', $this->entity->id());
      $this->entity->user_picture->entity = $file;
      $file->save();
      // This has to be saved before validation entity reference refuses access
      // before file_usage is written
      // Drupal\Core\Field\EntityReferenceFieldItemList/FileFieldItemList::postsave()
    }
  }

  protected function show_phonePostProcess($val) {
    if ($val) {
      \Drupal::service('user.data')->set('cforge', $this->entity->id(), 'show_phones', TRUE);
    }
  }
  protected function show_addressPostProcess($val) {
    if ($val) {
      \Drupal::service('user.data')->set('cforge', $this->entity->id(), 'show_address', TRUE);
    }
  }
  protected function show_emailPostProcess($val) {
    if ($val) {
      \Drupal::service('user.data')->set('cforge', $this->entity->id(), 'show_email', TRUE);
    }
  }

  /**
   * {@inheritDoc}
   */
  public function ready() : bool {
    // There must be more than category
    $cats = \Drupal::entityQuery('taxonomy_term')
      ->condition('vid', 'categories')
      ->execute();
    return count($cats) > 1;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc