mutual_credit-5.0.x-dev/src/Plugin/views/field/RunningBalance.php
src/Plugin/views/field/RunningBalance.php
<?php namespace Drupal\mcapi\Plugin\views\field; use Drupal\mcapi\Entity\TransactionInterface; use Drupal\mcapi\Element\WorthsView; use Drupal\views\ResultRow; use Drupal\Core\Entity\EntityTypeManager; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Field handler to provide running balance for a given transaction. * * @note reads from the transaction index table * * @ingroup views_field_handlers * * @ViewsField("transaction_running_balance") */ class RunningBalance extends Worth { private $txStorage; private $fAlias; /** * Constructs a Handler object. * * @param array $configuration * A configuration array containing information about the plugin instance. * @param string $plugin_id * The plugin_id for the plugin instance. * @param mixed $plugin_definition * The plugin implementation definition. * @param EntityTypeManager $entity_type_manager * The EntityTypeManager. */ public function __construct(array $configuration, $plugin_id, $plugin_definition, $entity_type_manager) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->txStorage = $entity_type_manager->getStorage('mcapi_transaction'); } public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $configuration, $plugin_id, $plugin_definition, $container->get('entity_type.manager') ); } function query() { $this->addAdditionalFields(); } /** * {@inheritdoc} */ public function render(ResultRow $values) { $transaction = $this->getEntity($values); if (!$transaction) { //something wrong here throw new \Exception('No entity in views result'); } $vals = $this->getBalance( $transaction, // See Drupal\mcapi\Entity\Views\TransactionViewsData $values->{$this->aliases['wallet_id']}, $values->{$this->aliases['created']} ); $transaction->worth->setValue($vals); $options = [ 'label' => 'hidden', 'context' => WorthsView::MODE_TRANSACTION, 'settings' => [], ]; return $transaction->worth->view($options); } /** * Add up all the balances until the current transactions. * * @param TransactionInterface $transaction * The current transaction * @param int $wallet_id * The alias of the field name to use * @param int $before * The date before which to count the transactions. */ private function getBalance(TransactionInterface $transaction, int $wallet_id, int $before) : array { $vals = []; foreach ($transaction->worth->currencies() as $curr_id) { // @todo running balance means sorting by the same field the view is sorted by. $vals[] = [ 'curr_id' => $curr_id, 'value' => $this->txStorage->runningBalance($wallet_id, $curr_id, 'created', $before) ]; } return $vals; } }