mutual_credit-5.0.x-dev/src/Plugin/Block/HeldWallets.php

src/Plugin/Block/HeldWallets.php
<?php

namespace Drupal\mcapi\Plugin\Block;

use Drupal\mcapi\Entity\Currency;
use Drupal\mcapi\Entity\Wallet;
use Drupal\mcapi\Mcapi;
use Drupal\Core\Config;
use Drupal\Core\Url;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ImmutableConfig;

/**
 * Displays all the wallets of an entity.
 *
 * Entity being either the current user OR the entity being viewed. Shows the
 * wallet view mode 'mini'.
 *
 * @Block(
 *   id = "held_wallets",
 *   admin_label = @Translation("Held wallet(s)"),
 *   category = @Translation("Community Accounting")
 * )
 */
class HeldWallets extends WalletContextBlockBase{

  /**
   * @var EntityDisplayRepositoryInterface
   */
  protected EntityDisplayRepositoryInterface $entityDisplayRepository;

  /**
   * @var EntityFieldManagerInterface
   */
  protected EntityFieldManagerInterface $entityFieldManager;

  /**
   * @var Config
   */
  protected ImmutableConfig $mcapiSettings;

  /**
   * Constructor
   *
   * @param array $configuration
   * @param type $plugin_id
   * @param array $plugin_definition
   * @param EntityTypeManagerInterface $entity_type_manager
   * @param AccountInterface $currentUser
   * @param Request $request
   */
  public function __construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $current_user, $request, ConfigFactoryInterface $config_factory, EntityDisplayRepositoryInterface $entity_display_repository, EntityFieldManagerInterface $entity_field_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $current_user, $request);
    $this->entityDisplayRepository = $entity_display_repository;
    $this->entityFieldManager = $entity_field_manager;
    $this->mcapiSettings = $config_factory->get('mcapi.settings');
  }

  /**
   * Injection.
   */
  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'),
      $container->get('current_user'),
      $container->get('request_stack')->getCurrentRequest(),
      $container->get('config.factory'),
      $container->get('entity_display.repository'),
      $container->get('entity_field.manager'),
    );
  }

  /**
   * {@inheritDoc}
   */
  public function defaultConfiguration() {
    $conf = parent::defaultConfiguration();
    $conf += [
      'curr_ids' => [],
      'holder_source' => SELF::HOLDER_CURRENT_USER,
      'item' => 'viewdisplay:mini',// if this doesn't exist, it'll fall back I'm sure
      'first_only' => 0
    ];
    return $conf;
  }

  /**
   * {@inheritDoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    foreach ($this->entityDisplayRepository->getViewModeOptions('mcapi_wallet') as $mode => $label) {
      if ($mode == 'token') continue;
      $options['viewdisplay:'.$mode] = $this->t('Display: @mode', ['@mode' => $label]);
    }
    foreach ($this->entityFieldManager->getExtraFields('mcapi_wallet', 'mcapi_wallet')['display'] as $key => $info) {
      $options['extrafield:'.$key] = $this->t('Component: @mode', ['@mode' => $info['label']]);
    }

    $form['item'] = [
      '#title' => $this->t('Component'),
      '#description' => $this->t(
        'Displays are presets containing many components. See <a href=":url">wallet view displays</a>.',
        [':url' => Url::fromRoute("entity.entity_view_display.mcapi_wallet.default")->toString()]
      ),
      '#type' => 'radios',
      '#options' => $options,
      '#default_value' => $this->configuration['item'],
      '#weight' => 2,
      '#required' => TRUE
    ];

    $form['first_only'] = [
      '#title' => $this->t('Which wallets'),
      '#description' => $this->t('Some entities may hold more than one wallet.'),
      '#type' => 'radios',
      '#options' => [
        0 => $this->t('All wallets'),
        1 => $this->t('First wallet only'),
      ],
      '#default_value' => $this->configuration['first_only'],
      '#weight' => 3
    ];
    if ($this->entityTypeManager->getStorage('mcapi_currency')->getQuery()->count()->execute() > 1) {
      $form['curr_ids'] = [
        '#title' => t('Currencies'),
        '#description' => t("Select none to select all. Also see the setting 'Show unused currencies.' on admin/accounting/misc"),
        '#title_display' => 'before',
        '#type' => 'mcapi_currency_select',
        '#default_value' => $this->configuration['curr_ids'],
        '#options' => Mcapi::entityOptions('mcapi_currency'),
        '#multiple' => TRUE,
        '#weight' => 4
      ];
    }
    return $form;
  }

  /**
   * {@inheritDoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    parent::blockSubmit($form, $form_state);
    $this->configuration['curr_ids'] = array_filter((array)$this->configuration['curr_ids']);
  }

  /**
   * {@inheritDoc}
   */
  public function build() {
    $renderable = [];
    if ($this->configuration['first_only']) {
      $this->wids = array_slice($this->wids, 0, 1);
    }
    $currencies  = $this->configuration['curr_ids'] ? Currency::loadMultiple($this->configuration['curr_ids']) : Currency::loadMultiple();
    [$type, $name] = explode(':', $this->configuration['item']);
    $w = 0;

    foreach ($this->wids as $wid) {
      $wallet = Wallet::load($wid);
      if ($type == 'viewdisplay') {// normal drupal display
        $renderable[$wid] = $this->entityTypeManager
          ->getViewBuilder('mcapi_wallet')
          ->viewMultiple([$wallet], $name);
        $renderable[$wid]['#weight'] = $w++;
      }
      elseif ($type == 'extrafield') {// wallet display callback
        foreach ($currencies as $currency) {
          //$key = 'wallet_'.$wid.'_'.$currency->id();
          $func = 'mcapi_wallet_view_'.$name;
          $renderable[$wid][$currency->id()] = $func($wallet, $currency);
          $renderable[$wid][$currency->id()]['#weight'] = $w++;
          unset($renderable[$wid][$currency->id()]['#theme_wrappers']);
        }
        $renderable[$wid]['links'] = mcapi_wallet_links($wallet);
      }
    }
    $renderable['#cache']['contexts'][] = $this->configuration['holder_source'] == SELF::HOLDER_CURRENT_USER ? 'user' : 'url';
    $renderable['#cache']['tags'] = array_map(
      function ($w){return 'mcapi_wallet:'.$w;},
      $this->wids
    );
    return $renderable;// cachetags
  }

}

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

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