commerce_funds-8.x-1.7/src/Plugin/Validation/Constraint/NetAmountBelowBalanceConstraintValidator.php
src/Plugin/Validation/Constraint/NetAmountBelowBalanceConstraintValidator.php
<?php
namespace Drupal\commerce_funds\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\commerce_funds\FeesManagerInterface;
use Drupal\commerce_funds\TransactionManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the NetAmountBelowBalance Constraint.
*
* @package commerce_funds
*/
class NetAmountBelowBalanceConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected $currentUser;
/**
* The fees manager.
*
* @var \Drupal\commerce_funds\FeesManagerInterface
*/
protected $feesManager;
/**
* The transaction manager.
*
* @var \Drupal\commerce_funds\TransactionManagerInterface
*/
protected $transactionManager;
/**
* Class constructor.
*/
public function __construct(AccountProxyInterface $current_user, FeesManagerInterface $fees_manager, TransactionManagerInterface $transaction_manager) {
$this->currentUser = $current_user;
$this->feesManager = $fees_manager;
$this->transactionManager = $transaction_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('current_user'),
$container->get('commerce_funds.fees_manager'),
$container->get('commerce_funds.transaction_manager')
);
}
/**
* {@inheritdoc}
*/
public function validate($items, Constraint $constraint) {
$amount = $items->getValue()[0]['number'];
$currency = $items->getValue()[0]['currency_code'];
$issuer = $this->currentUser;
$fee_applied = $this->feesManager->calculateTransactionFee($amount, $currency, 'transfer');
$issuer_balance = $this->transactionManager->loadAccountBalance($issuer->getAccount(), $currency);
$currency_balance = $issuer_balance[$currency] ?? 0;
// Error if the user doesn't have enough money to cover the transfer + fee.
if ($currency_balance < $fee_applied['net_amount']) {
if (!$fee_applied['fee']) {
$this->context->addViolation($constraint->message);
}
if ($fee_applied['fee']) {
$this->context->addViolation($constraint->messageWithFee, [
'%total' => $fee_applied['net_amount'],
'@currency' => $currency,
]);
}
}
}
}
