cforge-2.0.x-dev/src/Plugin/CsvParser/Transactions.php
src/Plugin/CsvParser/Transactions.php
<?php
namespace Drupal\cforge\Plugin\CsvParser;
use Drupal\user\Entity\User;
use Drupal\cforge_import\Plugin\CsvParser\Transactions as TransactionsBase;
use Drupal\mcapi\Entity\Storage\WalletStorage;
use Drupal\mcapi\Entity\Wallet;
/**
* Plugin to import transactions.
*
* @Plugin(
* id = "transactions",
* label = @Translation("Transactions"),
* entity_type = "mcapi_transaction"
* )
*/
class Transactions extends TransactionsBase {
protected $entityTypeId = 'mcapi_transaction';
protected $bundle = 'mcapi_transaction';
private $allWallets = [];
/**
* {@inheritdoc}
*/
public function columns() {
$cols = parent::columns();
$cols['payer'] = t('The wallet id or email of the payer user');
$cols['payee'] = t('The wallet_id or email of the payee user');
$cols['category'] = t('One category ID');
return $cols;
}
/**
* {@inheritdoc}
*/
protected function payeeProcess($val) {
$this->entity->payee->target_id = static::getWallet($val);
}
protected function payerProcess($val) {
$this->entity->payer->target_id = static::getWallet($val);
}
/**
* Get the first wallet of the given user, identified by email or wallet ID.
*
* @param string $val
* Email address or wallet id of the user.
*/
private function getWallet($val) {
static $wallets_by_mail;
$val = trim(strtoLower($val));
if (!isset($wids[$val])) {
if (filter_var($val, FILTER_VALIDATE_EMAIL)) {
$uids = \Drupal::entityQuery('user')->condition('mail', $val)->execute();
if (!$uids) {
throw new \Exception('no user with mail ' . $val);
}
$user = User::load(reset($uids));
if ($wallet_ids = WalletStorage::walletsOf($user, FALSE)) {
$wallets_by_mail[strtolower($user->getEmail())] = reset($wallet_ids);
}
else { // Create a new wallet
$new_wallet = Wallet::create(['holder' => $user]);
$new_wallet->save();
$wallets_by_mail[$val] = $new_wallet->id();
}
}
elseif (is_int($val)) {
return $val;
}
}
return $wallets_by_mail[$val];
}
}
