Preview:
<?php

namespace Drupal\bacademy_core\Plugin\Block;

use Drupal\bacademy_core\Controller\SubscribeController;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
 * Provides a 'Subscribe' block.
 *
 * @Block(
 *   id = "subscribe_block",
 *   admin_label= @Translation("Subscribe"),
 *   category= @Translation("Subscribe"),
 * )
 */
class SubscribeBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Entity type manager.
   *
   * @var EntityTypeManager
   */
  protected $entityTypeManager;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $current_user, EntityTypeManager $entityTypeManager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition){
    return new static (
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user'),
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritDoc}
   */
  public function build() {
    // Check if current user is subscribed.
    $user = $this->entityTypeManager
      ->getStorage('user')
      ->loadByProperties([
        'uid' => $this->currentUser->id(),
      ]);
    $user = reset($user);
    $subscribed = 0;
    if ($user->hasField('field_mailchimp_subscription')) {
      $subscribed = $user->get('field_mailchimp_subscription')[0]->get('subscribe')->getValue();
    }
    if ($subscribed == "1") {
      return [];
    } else {
      return [
        '#type' => 'inline_template',
        '#template' => "<div>
                        <p>Opt in and don't miss out on the latest from the Academy.</p>
                        <a href='{{ controller_link }}'>YES PLEASE</a>
                        <a href='#'>NO THANKS</a>
                      </div>",
        '#context' => [
          'controller_link' => Url::fromRoute('bacademy_core.subscription', ['id' => $this->currentUser->id()])->toString(),
        ],
      ];
    }
  }
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter