remp-8.x-1.x-dev/src/Controller/RempContentController.php

src/Controller/RempContentController.php
<?php

namespace Drupal\remp\Controller;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AppendCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\SettingsCommand;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Url;
use Drupal\remp\Form\RempLoginForm;
use Drupal\remp\RempService;
use GuzzleHttp\ClientInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * RempContentController implementation.
 */
class RempContentController extends ControllerBase {

  /**
   * Request.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * EntityTypeManager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManager|EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Renderer.
   *
   * @var \Drupal\Core\Render\Renderer|RendererInterface
   */
  protected $renderer;

  /**
   * Guzzle Http Client.
   *
   * @var \GuzzleHttp\Client|ClientInterface
   */
  protected $httpClient;

  /**
   * Form builder.
   *
   * @var \Drupal\Core\Form\FormBuilder|FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * Remp Service.
   *
   * @var \Drupal\remp\RempService
   */
  protected $rempService;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('request_stack'),
      $container->get('entity_type.manager'),
      $container->get('renderer'),
      $container->get('http_client'),
      $container->get('form_builder'),
      $container->get('remp')
    );
  }

  /**
   * {@inheritdoc}
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   Request Stack.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   Entity Type manager.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   Renderer.
   * @param \GuzzleHttp\ClientInterface $http_client
   *   HTTP Client.
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
   *   Form Builder.
   * @param \Drupal\remp\RempService $remp_service
   *   Remp Service.
   */
  public function __construct(RequestStack $request_stack, EntityTypeManagerInterface $entity_type_manager, RendererInterface $renderer, ClientInterface $http_client, FormBuilderInterface $form_builder, RempService $remp_service) {
    $this->request = $request_stack->getCurrentRequest();
    $this->entityTypeManager = $entity_type_manager;
    $this->renderer = $renderer;
    $this->httpClient = $http_client;
    $this->formBuilder = $form_builder;
    $this->rempService = $remp_service;
  }

  /**
   * Returns restricted content.
   */
  public function content($entity_type, $entity_id) {
    $definitions = $this->entityTypeManager->getDefinitions();
    $entityStorage = $this->entityTypeManager->getStorage($entity_type);

    if (!$this->rempService->hasValidToken()) {
      if ($entity = $entityStorage->load($entity_id)) {
        return $this->loginFormResponse($entity, $entity_type, $entity_id);
      }
      else {
        throw new NotFoundHttpException();
      }
    }

    if (isset($definitions[$entity_type])) {

      if ($entity = $entityStorage->load($entity_id)) {
        return $this->contentResponse($entity);
      }
      else {
        throw new NotFoundHttpException();
      }
    }
    else {
      throw new NotFoundHttpException();
    }
  }

  /**
   * Returns remp user block.
   */
  public function rempConponents() {
    $config = $this->config('remp.config');

    $links = [];
    $logged_in = FALSE;

    $response = new AjaxResponse();

    if ($host = $config->get('host')) {
      if ($this->rempService->hasValidToken()) {
        $logged_in = TRUE;

        $subscriptions = [];
        $limited_sub = FALSE;
        $remaining = 0;
        foreach ($this->rempService->getSubscriptions() as $sub) {
          if ($sub['method'] == 'article_count') {
            $limited_sub = TRUE;
            $remaining = $sub['remaining_articles'];
          }
          else {
            $subscriptions[] = $sub;
          }
        }

        if ($limited_sub && empty($subscriptions) && $paid_funnel = $config->get('paid_funnel')) {
          $url = Url::fromUri($config->get('host') . '/sales-funnel/sales-funnel-frontend/show?funnel=' . $paid_funnel);
          $footer = [
            '#theme' => 'remp_footer',
            '#remaining_articles' => $remaining,
            '#subscribe' => $url->toString(),
          ];

          // Add footer content.
          $footer_selector = '#remp-footer-container';
          $response->addCommand(new HtmlCommand($footer_selector, ''));
          $response->addCommand(new AppendCommand($footer_selector, $this->renderer->render($footer)));
        }

        if (empty($subscriptions) && $paid_funnel = $config->get('paid_funnel')) {
          $links['subscribe'] = [
            '#type' => 'link',
            '#url' => Url::fromUri($host . '/sales-funnel/sales-funnel-frontend/show?funnel=' . $paid_funnel),
            '#title' => $this->t('Subscribe'),
            '#attributes' => [
              'target' => '_blank',
            ],
          ];
        }

        $links['my_profile'] = [
          '#type' => 'link',
          '#url' => Url::fromUri($host),
          '#title' => $this->t('My Profile'),
          '#attributes' => [
            'target' => '_blank',
          ],
        ];
        $links['sign_out'] = [
          '#type' => 'link',
          '#url' => Url::fromUri($host . '/users/sign/out'),
          '#title' => $this->t('Sign out'),
          '#attributes' => [
            'target' => '_blank',
          ],
        ];

      }
      else {
        $links['sign_in'] = [
          '#type' => 'link',
          '#url' => Url::fromUri($host . '/sign/in'),
          '#title' => $this->t('Sign in'),
          '#attributes' => [
            'target' => '_blank',
          ],
        ];
        if ($free_funnel = $config->get('funnel')) {
          $links['register'] = [
            '#type' => 'link',
            '#url' => Url::fromUri($host . '/sales-funnel/sales-funnel-frontend/show?funnel=' . $free_funnel),
            '#title' => $this->t('Register'),
            '#attributes' => [
              'target' => '_blank',
            ],
          ];
        }
      }

      $build = [
        '#theme' => 'remp_user_links',
        '#links' => $links,
        '#loggedIn' => $logged_in,
      ];

      $selector = '#remp-user-block';
      $response->addCommand(new HtmlCommand($selector, ''));
      $response->addCommand(new AppendCommand($selector, $this->renderer->render($build)));
    }

    return $response;
  }

  /**
   * Renders REMP Login form.
   */
  protected function loginFormResponse($entity, $entity_type, $entity_id) {
    $drupalSettings = [];
    $drupalSettings['remp']['beam']['wait'] = FALSE;
    $drupalSettings['remp']['beam']['userSubscribed'] = FALSE;
    $drupalSettings['remp']['beam']['article'] = [
      'id' => $entity->uuid(),
      'author' => $entity->getOwner()->id(),
      'locked' => TRUE,
    ];
    $response = new AjaxResponse();
    $selector = '#remp-anonym';

    $login_form = $this->formBuilder->getForm(
      RempLoginForm::class,
      "entity.$entity_type.canonical",
      [$entity_type => $entity_id],
      $entity->uuid()
    );

    $response->addCommand(new AppendCommand($selector, $this->renderer->render($login_form)));
    $response->addCommand(new SettingsCommand($drupalSettings, TRUE));

    return $response;
  }

  /**
   * Renders REMP Login form.
   */
  protected function contentResponse($entity) {
    $paid_url = '';
    $config = $this->config('remp.config');
    $entity_type = $entity->getEntityTypeId();

    $result = $this->rempService->viewContent($entity);
    $drupalSettings = [];

    $drupalSettings['remp']['beam']['wait'] = FALSE;
    $drupalSettings['remp']['beam']['userSubscribed'] = FALSE;
    $drupalSettings['remp']['beam']['userId'] = (string) $this->rempService->getUser()['id'];
    $drupalSettings['remp']['beam']['article'] = [
      'id' => $entity->uuid(),
      'author' => $entity->getOwner()->id(),
      'locked' => TRUE,
    ];

    $response = new AjaxResponse();
    $selector = '#remp-member';

    if ($result['available']) {
      $viewBuilder = $this->entityTypeManager
        ->getViewBuilder($entity_type);

      $view = $viewBuilder->view($entity, 'member');

      $view[] = [
        '#prefix' => '<div class="remp-watermark">',
        '#suffix' => '</div>',
        '#markup' => $this->t('Premium content'),
        '#weight' => 999,
      ];

      $drupalSettings['remp']['beam']['userSubscribed'] = TRUE;
      $drupalSettings['remp']['beam']['article']['locked'] = FALSE;

      $response->addCommand(new HtmlCommand($selector, ''));
      $response->addCommand(new AppendCommand($selector, $this->renderer->render($view)));
    }
    else {
      if ($paid_funnel = $config->get('paid_funnel')) {
        $paid_url = $config->get('host') . '/sales-funnel/sales-funnel-frontend/show?funnel=' . $paid_funnel;
        $paid_url .= '&referer=' . $entity->uuid();
      }

      $output = [
        '#type' => 'link',
        '#title' => $this->t('Subscribe for premium membership'),
        '#url' => Url::fromUri($paid_url),
      ];

      $response->addCommand(new HtmlCommand($selector, ''));
      $response->addCommand(new AppendCommand($selector, $this->renderer->render($output)));
    }

    $response->addCommand(new SettingsCommand($drupalSettings, TRUE));

    return $response;
  }

}

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

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