BeerUser.php 2.46 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\migrate_example\Plugin\migrate\source;

5
use Drupal\migrate\Plugin\migrate\source\SqlBase;
6 7 8
use Drupal\migrate\Row;

/**
9
 * Source plugin for beer user accounts.
10 11 12 13 14
 *
 * @MigrateSource(
 *   id = "beer_user"
 * )
 */
15
class BeerUser extends SqlBase {
16 17 18 19 20 21

  /**
   * {@inheritdoc}
   */
  public function query() {
    return $this->select('migrate_example_beer_account', 'mea')
22 23
      ->fields('mea', ['aid', 'status', 'registered', 'username', 'nickname',
                            'password', 'email', 'sex', 'beers']);
24 25 26 27 28 29
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
30
    $fields = [
31 32
      'aid' => $this->t('Account ID'),
      'status' => $this->t('Blocked/Allowed'),
33 34
      'registered' => $this->t('Registered date'),
      'username' => $this->t('Account name (for login)'),
35 36
      'nickname' => $this->t('Account name (for display)'),
      'password' => $this->t('Account password (raw)'),
37
      'email' => $this->t('Account email'),
38 39
      'sex' => $this->t('Gender'),
      'beers' => $this->t('Favorite beers, pipe-separated'),
40
    ];
41 42 43 44 45 46 47 48

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
49 50
    return [
      'aid' => [
51 52
        'type' => 'integer',
        'alias' => 'mea',
53 54
      ],
    ];
55 56
  }

57 58 59
  /**
   * {@inheritdoc}
   */
60
  public function prepareRow(Row $row) {
61 62 63 64 65 66 67 68 69 70 71 72
    /**
     * prepareRow() is the most common place to perform custom run-time
     * processing that isn't handled by an existing process plugin. It is called
     * when the raw data has been pulled from the source, and provides the
     * opportunity to modify or add to that data, creating the canonical set of
     * source data that will be fed into the processing pipeline.
     *
     * In our particular case, the list of a user's favorite beers is a pipe-
     * separated list of beer IDs. The processing pipeline deals with arrays
     * representing multi-value fields naturally, so we want to explode that
     * string to an array of individual beer IDs.
     */
73 74 75
    if ($value = $row->getSourceProperty('beers')) {
      $row->setSourceProperty('beers', explode('|', $value));
    }
76 77 78 79 80 81
    /**
     * Always call your parent! Essential processing is performed in the base
     * class. Be mindful that prepareRow() returns a boolean status - if FALSE
     * that indicates that the item being processed should be skipped. Unless
     * we're deciding to skip an item ourselves, let the parent class decide.
     */
82 83 84 85
    return parent::prepareRow($row);
  }

}