You are here

class Embed in CMS Content Sync 2.0.x

Same name and namespace in other branches
  1. 2.1.x src/Controller/Embed.php \Drupal\cms_content_sync\Controller\Embed

Class Embed provides helpers to embed Sync Core functionality into the site.

Hierarchy

Expanded class hierarchy of Embed

File

src/Controller/Embed.php, line 22

Namespace

Drupal\cms_content_sync\Controller
View source
class Embed extends ControllerBase {
  protected $core;
  protected $settings;
  protected $params;
  protected $embedService;
  public function syndicationDashboard() {
    $this
      ->init();
    $embed = $this->embedService
      ->syndicationDashboard($this->params + [
      'selectedFlowMachineName' => \Drupal::request()->request
        ->get('flow'),
    ]);
    return $this
      ->run($embed, DrupalApplication::get()
      ->getSiteUuid() ? [
      'form' => \Drupal::formBuilder()
        ->getForm(MigrationForm::class),
    ] : []);
  }
  public function migrate() {
    $this
      ->init();
    $all_pools = Pool::getAll();
    $pools = [];
    foreach ($all_pools as $id => $pool) {
      $pools[] = [
        'machineName' => $pool
          ->id(),
        'name' => $pool
          ->label(),
        'exported' => $pool
          ->v2Ready(),
      ];
    }
    $all_flows = Flow::getAll();
    $flows = [];
    $pushes = false;
    foreach ($all_flows as $id => $flow) {
      if (Flow::TYPE_PULL !== $flow
        ->getType()) {
        $pushes = true;
      }
      $flows[] = [
        'machineName' => $flow
          ->id(),
        'name' => $flow
          ->label(),
        'exported' => $flow
          ->v2Ready(),
      ] + Migration::getFullFlowStatus($flow);
    }
    $health_module_enabled = \Drupal::moduleHandler()
      ->moduleExists('cms_content_sync_health');
    $embed = $this->embedService
      ->migrate($this->params + [
      'pools' => $pools,
      'flows' => $flows,
      'migrated' => false,
      'settings' => [
        'mustEnableHealthSubmodule' => $pushes && !$health_module_enabled,
        'pushToV2Url' => Url::fromRoute('view.content_sync_entity_status.entity_status_overview', [], [
          'query' => [
            'v2' => 'yes',
          ],
          'absolute' => true,
        ])
          ->toString(),
        'pullManuallyFromV2Url' => $health_module_enabled ? Url::fromRoute('entity.cms_content_sync.content', [], [
          'query' => [
            'v2' => 'yes',
          ],
          'absolute' => true,
        ])
          ->toString() : null,
        'switched' => Migration::alwaysUseV2(),
      ],
    ]);
    return $this
      ->run($embed, DrupalApplication::get()
      ->getSiteUuid() ? [
      'form' => \Drupal::formBuilder()
        ->getForm(MigrationForm::class),
    ] : []);
  }
  public function site() {
    $this
      ->init(true);

    // Already registered if this exists.
    $uuid = $this->settings
      ->getSiteUuid();
    $force = empty($this->params['force']) ? null : $this->params['force'];
    if (IEmbedService::MIGRATE === $force || !Migration::useV2() && empty($force)) {
      return $this
        ->migrate();
    }
    $this->params['migrated'] = Migration::didMigrate();
    $embed = $uuid && (empty($this->params['force']) || IEmbedService::REGISTER_SITE !== $this->params['force']) ? $this->embedService
      ->siteRegistered($this->params) : $this->embedService
      ->registerSite($this->params);
    if ($uuid && empty($this->params)) {
      $step = Migration::getActiveStep();
      if (Migration::STEP_DONE !== $step) {
        $link = \Drupal::l(t('migrate now'), \Drupal\Core\Url::fromRoute('cms_content_sync_flow.migration'));
        \Drupal::messenger()
          ->addMessage(t('You have Sync Cores from our old v1 release. Support for this Sync Core will end on December 31st, 2021. Please @link.', [
          '@link' => $link,
        ]), 'warning');
      }
    }
    try {
      return $this
        ->run($embed);
    } catch (UnauthorizedException $e) {
      \Drupal::messenger()
        ->addMessage('Your registration token expired. Please try again.', 'warning');
      $url = \Drupal::request()
        ->getRequestUri();

      // Remove invalid query params so the user can try again.
      $url = explode('?', $url)[0];
      return RedirectResponse::create($url);
    }
  }
  public function pullDashboard() {
    $this
      ->init();
    $embed = $this->embedService
      ->pullDashboard([]);
    return $this
      ->run($embed);
  }
  public function nodeStatus(NodeInterface $node) {
    $this
      ->init();
    $user = \Drupal::currentUser();
    $params = [
      'configurationAccess' => $user
        ->hasPermission('administer cms content sync'),
    ];
    if (EntityHandlerPluginManager::isEntityTypeConfiguration($node
      ->getEntityTypeId())) {
      $params['remoteUniqueId'] = $node
        ->id();
    }
    else {
      $params['remoteUuid'] = $node
        ->uuid();
    }

    // TODO: Show warning if not using Sync Core v2 yet, so users understand why it's empty.
    $embed = $this->embedService
      ->entityStatus($params);
    return $this
      ->run($embed);
  }
  protected function init($expectJwtWithSyncCoreUrl = false) {
    $this->params = \Drupal::request()->query
      ->all();
    if ($expectJwtWithSyncCoreUrl) {
      if (isset($this->params['uuid'], $this->params['jwt'])) {
        $tks = explode('.', $this->params['jwt']);
        list(, $bodyb64) = $tks;
        $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
        if (!empty($payload->syncCoreBaseUrl)) {
          DrupalApplication::get()
            ->setSyncCoreUrl($payload->syncCoreBaseUrl);
        }
      }
    }
    $this->core = SyncCoreFactory::getDummySyncCoreV2();
    $this->settings = ContentSyncSettings::getInstance();
    $this->embedService = $this->core
      ->getEmbedService();
  }
  protected function run($embed, $extras = []) {
    $result = $embed
      ->run();
    $redirect = $result
      ->getRedirectUrl();
    if ($redirect) {
      return RedirectResponse::create($redirect);
    }
    $html = $result
      ->getRenderedHtml();

    // TODO: Put this in a theme file.
    return [
      '#type' => 'inline_template',
      '#template' => '<div className="content-sync-embed-wrapper" style="margin-top: 20px;">{{ html|raw }}</div>',
      '#context' => [
        'html' => $html,
      ],
    ] + $extras;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 46
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage service.
Embed::$core protected property
Embed::$embedService protected property
Embed::$params protected property
Embed::$settings protected property
Embed::init protected function
Embed::migrate public function
Embed::nodeStatus public function
Embed::pullDashboard public function
Embed::run protected function
Embed::site public function
Embed::syndicationDashboard public function
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.