qs_article-1.0.2/src/Plugin/Block/ArtBlock.php

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

namespace Drupal\qs_articles\Plugin\Block;

use Drupal;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\block\Entity\Block;

/**
 * Provides a 'Article block' block.
 *
 * @Block(
 *   id = "Art_block",
 *   admin_label = @Translation("Embed block in Article Node"),
 *   category = @Translation("Embed block in Article Node")
 * )
 */
class ArtBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();

    $query = \Drupal::database()->select('block_content_field_data', 'n');
    $query->leftJoin('block_content', 'b', 'n.id = b.id');
    $query->fields('n', ['id'])
          ->fields('n', ['info'])
          ->fields('b', ['uuid'])
          ->condition('b.type', ['webinar' , 'test_preparations'] , 'in');
    $result = $query->execute()->fetchAll();
    // Get list of all custom blocks, excluding few.
    $blockManager = \Drupal::service('plugin.manager.block');
    $contextRepository = \Drupal::service('context.repository');
    // Get blocks definition
    $definitions = $blockManager->getFilteredDefinitions('block_ui', $contextRepository->getAvailableContexts());

    foreach ($definitions as $key => $value) {
       $blocklist[''] = $this->t('- None -');
      if(strpos($key, "dfp_ad:") === 0 || $key == 'block_content:d5db902c-f544-4c52-a86c-0698c0de78ff' || $key == 'block_content:df710696-939c-415b-862e-4b7f504c9ade' || $key == 'block_content:13a5cdae-74c3-4989-ad0a-24be9053a4b2') {
         if($key != 'dfp_ad:07db1a2d-aea8-4679-82e6-3b61b5b19f63' && $key != 'dfp_ad:9a996462-038f-4b02-ba07-6a407525e94d' && $key != 'dfp_ad:47082ba0-74f2-4887-9290-017eaf643164' && $key != 'dfp_ad:f36080cf-3c3c-4c4b-a621-9a945a2ddd42' && $key != 'dfp_ad:d147740e-e986-440c-abac-d6b6b4e3b924' && $key != 'dfp_ad:7a31abd0-a155-4da3-bf1c-197b66b5d11f' && $key != 'dfp_ad:2c5a05bf-567b-4d58-ac2f-01d246dd6dea' && $key != 'dfp_ad:4b163f9a-47a2-4ab1-84f5-6c62eebbd975') {
          if(is_object($value['admin_label'])){
            $blocklist[$key] = $value['admin_label']->__toString();
          }else{
            $blocklist[$key] = $value['admin_label'];
          }
        }
      }
    }
     if(!empty($result)){
           foreach($result as $r ){
            $unid = $r->uuid;
            $key = 'block_content:'.$unid.'';
            $info = $r->info;
            $blocklist[$key] = $info ;
           }
    }
    // Remove Article Advertisement 1, 2 as its already in layout.
    unset($blocklist['dfp_ad:02e6d642-560b-4c8e-8a49-6695822d3186']);
    unset($blocklist['dfp_ad:cab7867e-d18c-403f-b7b6-37b9fc470492']);
    unset($blocklist['dfp_ad:d147740e-e986-440c-abac-d6b6b4e3b924']);
    unset($blocklist['dfp_ad:a10e9fb8-5202-498b-a438-9cb2350e676d']);

    $form['custom_blocks'] = [
      '#type' => 'select',
      '#options' => $blocklist,
      '#title' => $this->t('Block to embed in paragraph'),
      '#multiple' => TRUE,
      '#size' => 6,
      '#default_value' =>  isset($config['custom_blocks']) ? $config['custom_blocks'] : '',
      '#attributes' => [
        'class' => ['chosen_select_max_3'],
      ],
    ];

    $form['paragraph_no'] = [
      '#type' => 'select',
      '#title' => $this->t('Select paragraph number after which block will be embeded'),
      '#options' => [
        '' => $this->t('-Select-'),
        '1' => '1',
        '2' => '2',
        '3' => '3',
        '4' => '4',
        '5' => '5',
        '6' => '6',
        '7' => '7',
        '8' => '8',
        '9' => '9',
        '10' => '10',
      ],
      '#default_value' =>  isset($config['paragraph_no']) ? $config['paragraph_no'] : '',
    ];

    return $form;
  }


  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    parent::blockSubmit($form, $form_state);
    $values = $form_state->getValues();
    $this->configuration['custom_blocks']=array_values($values['custom_blocks']);
    $this->configuration['paragraph_no'] = $values['paragraph_no'] ;
    $custom_blocks = array_values( array_filter($form_state->getValue('custom_blocks')) );
    $paragraph_number = $form_state->getValue('paragraph_no') ? $form_state->getValue('paragraph_no') : '1';
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $current_path = \Drupal::service('path.current')->getPath();
    $current_url = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
    $dfp_config = \Drupal::config('dfp.settings');
    $dfp_netword_id = $dfp_config->get('network_id');
    $dfp_adunit_pattern = $dfp_config->get('adunit_pattern');
    $dfp_adunit_pattern = explode('[', $dfp_adunit_pattern);
    $dfp_adunit = $dfp_netword_id. "/" .$dfp_adunit_pattern[0] . $current_url;
    $config = $this->getConfiguration();
    $tag = '';
    if (isset($config['custom_blocks']) && !empty($config['custom_blocks'])) {
      foreach($config['custom_blocks']  as $b){
        if( strpos($b, "dfp_ad:")!== 0 ){
          $logged_in = \Drupal::currentUser()->isAuthenticated();
          $uuid = str_replace('block_content:', '', $b);
          $blockld = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', $uuid);
          if ($blockld) {
            if($blockld->bundle() =='webinar'){
              $tag = $blockld->get('field_tag')->getValue()[0]['value'];
            }
          }
          if($tag =='join_us'  && $logged_in){
            $data['addclass']= 'no_embed_dfp join_us_type';
             break;
          }else{
            $data['addclass']= 'no_embed_dfp';
             break;
          }
        }
      }
      foreach($config['custom_blocks']  as $k => $b) {
        $data['custom_blocks'][$k]['block_uuid'] = $b;
      }
    }

    if (isset($config['paragraph_no']) && !empty($config['paragraph_no'])) {
      $data['paragraph_no'] = $config['paragraph_no'];
    }
    foreach($data['custom_blocks'] as $key => $value) {
      $dfp = explode(':', $value['block_uuid']);
      if($dfp[0] == 'dfp_ad') {
        $dfp_tag = \Drupal::service('entity.repository')->loadEntityByUuid('dfp_tag', $dfp[1]);
        $data['custom_blocks'][$key]['block_uuid'] = 'js-dfp-tag-' .$dfp_tag->id();
        $data['custom_blocks'][$key]['breakpoints'] = $this->customgetBreakpoints($dfp_tag->breakpoints());
        $data['custom_blocks'][$key]['id'] = $dfp_tag->id();
        $data['custom_blocks'][$key]['adUnit'] = $dfp_adunit;
        $data['custom_blocks'][$key]['target_url'] = $current_url;
        $data['custom_blocks'][$key]['size'] = self::formatSize($dfp_tag->size());
        $data['custom_blocks'][$key]['clickUrl'] = $dfp_config->get('click_url');
      }
    }
    return [
      '#theme' => 'qs_art_block',
      '#data' => $data,
    ];
  }

  public function customgetBreakpoints($break) {
    $breaks = array_map(function ($breakpoint) {
    return [
        'browser_size' => self::formatSize($breakpoint['browser_size']),
        'ad_sizes' => self::formatSize($breakpoint['ad_sizes']),
      ];
    }, $break);
    return $breaks;
  }

 public static function formatSize($size) {
    $formatted_sizes = [];

    $sizes = explode(',', $size);
    foreach ($sizes as $size) {
      if ($size == '<none>') {
        // If the ad sizes string contains the special keyword "<none>," use an
        // empty size list in order to suppress slot display.
        $formatted_sizes[] = '[]';
      }
      else {
        $formatted_size = explode('x', trim($size));
        $formatted_sizes[] = '[' . implode(', ', $formatted_size) . ']';
      }
    }

    return count($formatted_sizes) == 1 ? $formatted_sizes[0] : '[' . implode(', ', $formatted_sizes) . ']';
  }


}
//promo , mba carrier service

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

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