You are here

class FlowControllerPerBundle in CMS Content Sync 2.1.x

Hierarchy

Expanded class hierarchy of FlowControllerPerBundle

1 file declares its use of FlowControllerPerBundle
Flow.php in src/Entity/Flow.php

File

src/Controller/FlowControllerPerBundle.php, line 10

Namespace

Drupal\cms_content_sync\Controller
View source
class FlowControllerPerBundle extends FlowControllerBase implements IFlowController {

  /**
   * @inheritDoc
   */
  public function getEntityTypeConfig($entity_type = null, $entity_bundle = null, $used_only = false, $include_new_versions = false) {
    $entity_types = $this->flow->per_bundle_settings;
    $result = [];
    if (empty($entity_types)) {
      return $result;
    }
    foreach ($entity_types as $entity_type_name => &$type_bundles) {
      foreach ($type_bundles as $bundle_name => &$bundle) {
        $settings =& $bundle['settings'];
        if ($used_only && Flow::HANDLER_IGNORE == $settings['handler']) {
          continue;
        }
        if ($entity_type && $entity_type_name != $entity_type) {
          continue;
        }
        if ($entity_bundle && $bundle_name != $entity_bundle) {
          continue;
        }

        // If this is called before being saved, we want to have version etc.
        // available still.
        if (empty($settings['version']) || $include_new_versions) {
          $settings['version'] = Flow::getEntityTypeVersion($entity_type_name, $bundle_name);
        }
        if ($entity_type && $entity_bundle) {
          return $settings;
        }
        $result[$entity_type_name][$bundle_name] = $settings;
      }
    }
    return $result;
  }

  /**
   * Create a flow configuration programmatically.
   *
   * @param $flow_name
   * @param string $flow_id
   * @param bool   $status
   * @param array  $dependencies
   * @param $configurations
   * @param bool $force_update
   *
   * @return mixed|string
   */
  public static function createFlow($flow_name, $flow_id = '', $status = true, $dependencies = [], $configurations, $force_update = false) {
    $flows = Flow::getAll(true);

    // If no flow_id is given, create one.
    if (empty($flow_id)) {
      $flow_id = strtolower($flow_name);
      $flow_id = preg_replace('@[^a-z0-9_]+@', '_', $flow_id);
    }
    if (!$force_update && array_key_exists($flow_id, $flows)) {
      \Drupal::messenger()
        ->addMessage('A flow with the machine name ' . $flow_id . ' already exists. Creation has been skipped.', 'warning');
      return $flow_id;
    }
    $uuid_service = \Drupal::service('uuid');
    $language_manager = \Drupal::service('language_manager');
    $default_language = $language_manager
      ->getDefaultLanguage();
    $config = [
      'dependencies' => $dependencies,
    ];
    $flow_config = \Drupal::service('config.factory')
      ->getEditable('cms_content_sync.flow.' . $flow_id);

    // Setup base configurations.
    $flow_config
      ->set('uuid', $uuid_service
      ->generate())
      ->set('langcode', $default_language
      ->getId())
      ->set('status', $status)
      ->set('id', $flow_id)
      ->set('name', $flow_name)
      ->set('type', Flow::TYPE_PUSH)
      ->set('variant', Flow::VARIANT_PER_BUNDLE)
      ->set('config', $config)
      ->set('per_bundle_settings', []);

    // Configure entity types.
    foreach ($configurations as $entity_type_key => $bundles) {
      foreach ($bundles as $bundle_key => $bundle) {
        $entityPluginManager = \Drupal::service('plugin.manager.cms_content_sync_entity_handler');
        $entity_handler = $entityPluginManager
          ->getHandlerOptions($entity_type_key, $bundle_key);
        $entity_handler = reset($entity_handler);

        // Set configurations.
        $flow_config
          ->set('per_bundle_settings.' . $entity_type_key . '.' . $bundle_key . '.settings', [
          'handler' => $entity_handler['id'],
          'version' => Flow::getEntityTypeVersion($entity_type_key, $bundle_key),
          'export' => $bundle['push_configuration']['behavior'] ?? PushIntent::PUSH_DISABLED,
          'export_deletion_settings' => [
            'export_deletion' => $bundle['push_configuration']['export_deletion_settings'] ?? '',
          ],
          'export_pools' => $bundle['push_configuration']['export_pools'] ?? [],
          'import' => $bundle['import_configuration']['behavior'] ?? PullIntent::PULL_DISABLED,
          'import_deletion_settings' => [
            'import_deletion' => $bundle['import_configuration']['import_deletion'] ?? 0,
            'allow_local_deletion_of_import' => $bundle['import_configuration']['allow_local_deletion_of_import'] ?? 0,
          ],
          'import_updates' => $bundle['import_configuration']['import_updates'] ?? PullIntent::PULL_UPDATE_FORCE,
          'import_pools' => $bundle['import_configuration']['import_pools'] ?? [],
          'pool_export_widget_type' => 'checkboxes',
          'preview' => 'table',
        ]);

        /**
         * @var \Drupal\Core\Entity\EntityFieldManagerInterface $entityFieldManager
         */
        $entityFieldManager = \Drupal::service('entity_field.manager');
        $fields = $entityFieldManager
          ->getFieldDefinitions($entity_type_key, $bundle_key);
        foreach (Flow::getDefaultFieldConfigForEntityType($entity_type_key, $bundle_key) as $field_id => $field_config) {
          if (!empty($bundle['tags'])) {
            list(, , $field_name) = explode('-', $field_id);
            $field = $fields[$field_name];
            if ($field && 'entity_reference' == $field
              ->getType() && 'taxonomy_term' == $field
              ->getSetting('target_type')) {
              $bundles = $field
                ->getSetting('target_bundles');
              if (!$bundles) {
                $field_settings = $field
                  ->getSettings();
                $bundles = $field_settings['handler_settings']['target_bundles'];
              }
              if (is_array($bundles)) {
                foreach ($bundle['tags'] as $tag) {
                  if (in_array($tag
                    ->bundle(), $bundles)) {
                    $field_config['handler_settings']['subscribe_only_to'][] = [
                      'type' => 'taxonomy_term',
                      'bundle' => $tag
                        ->bundle(),
                      'uuid' => $tag
                        ->uuid(),
                    ];
                  }
                }
              }
            }
          }
          $flow_config
            ->set('per_bundle_settings.' . $entity_type_key . '.' . $bundle_key . '.properties.' . $field_id, $field_config);
        }
      }
    }
    $flow_config
      ->save();
    return $flow_id;
  }

  /**
   * @inheritDoc
   */
  public function needsEntityTypeUpdate() {

    // Show version mismatch warning.
    $entity_type_configs = $this
      ->getEntityTypeConfig(null, null, true);

    // Get version from config.
    $flow_config = \Drupal::config('cms_content_sync.flow.' . $this->flow
      ->id());
    foreach ($entity_type_configs as $entity_type => $bundles) {
      foreach ($bundles as $bundle => $entity_type_config) {

        // Get active version.
        $active_version = Flow::getEntityTypeVersion($entity_type, $bundle);

        // Get config version.
        $config_version = $flow_config
          ->get('per_bundle_settings.' . $entity_type . '.' . $bundle . '.settings.version');
        if ($active_version != $config_version) {
          return true;
        }
      }
    }
    return false;
  }

  /**
   * @inheritDoc
   */
  public function getPropertyConfig(string $entity_type, string $entity_bundle, string $property) {
    $entity_types = $this->flow->per_bundle_settings;
    if (empty($entity_types[$entity_type][$entity_bundle]['properties'][$property])) {
      return NULL;
    }
    return $entity_types[$entity_type][$entity_bundle]['properties'][$property];
  }

  /**
   * Update the Pool usage type across all bundles for the given pool.
   *
   * **This will not save the Flow.**
   *
   * @param string $entity_type_name
   * @param string $bundle_name
   * @param string $pool_id
   * @param string $assignment
   *
   * @return void
   */
  public function setPool($entity_type_name, $bundle_name, $pool_id, $assignment) {
    $this->flow->per_bundle_settings[$entity_type_name][$bundle_name]['settings'][Flow::TYPE_PUSH === $this->flow->type ? 'export_pools' : 'import_pools'][$pool_id] = $assignment;
  }

  /**
   * @return null|string
   */
  public function getType() {
    static $has_push = null;
    static $has_pull = null;
    if (null === $has_push || null === $has_pull) {
      foreach ($this
        ->getEntityTypeConfig() as $bundles) {
        foreach ($bundles as $config) {
          if (PushIntent::PUSH_DISABLED != $config['export']) {
            $has_push = true;
            if ($has_pull) {
              break;
            }
          }
          if (PullIntent::PULL_DISABLED != $config['import']) {
            $has_pull = true;
            if ($has_push) {
              break;
            }
          }
        }
      }
    }
    if ($has_push) {
      if ($has_pull) {
        return Flow::TYPE_BOTH;
      }
      return Flow::TYPE_PUSH;
    }
    if ($has_pull) {
      return Flow::TYPE_PULL;
    }
    return null;
  }
  public function updateEntityTypeVersions() {

    // Get all entity type configurations.
    $entity_type_bundle_configs = $this
      ->getEntityTypeConfig(NULL, NULL, TRUE);
    $updated = false;

    // Update versions.
    foreach ($entity_type_bundle_configs as $entity_type_name => $bundles) {
      foreach ($bundles as $bundle_name => $config) {
        $updated |= $this
          ->updateEntityTypeBundleVersion($entity_type_name, $bundle_name);
      }
    }
    if ($updated) {
      $this->flow
        ->save();
    }
  }

  /**
   * Update the version of an entity type bundle within a flow configuration.
   *
   * @param $entity_type
   * @param $bundle
   *
   * @throws \Exception
   *
   * @return bool
   */
  public function updateEntityTypeBundleVersion($entity_type, $bundle) {

    // Get active version.
    $active_version = Flow::getEntityTypeVersion($entity_type, $bundle);

    // Get version from config.
    $flow_config = \Drupal::service('config.factory')
      ->getEditable('cms_content_sync.flow.' . $this->flow
      ->id());
    $config_version = $flow_config
      ->get('per_bundle_settings.' . $entity_type . '.' . $bundle . '.settings.version');

    // Only update if required.
    if ($active_version != $config_version) {
      $default = Flow::getDefaultFieldConfigForEntityType($entity_type, $bundle, $this);
      $flow_config
        ->set('per_bundle_settings.' . $entity_type . '.' . $bundle . '.properties', $default);
      $flow_config
        ->set('per_bundle_settings.' . $entity_type . '.' . $bundle . '.settings.version', $active_version);
      $flow_config
        ->save();
      \Drupal::messenger()
        ->addMessage('Content Sync - Flow: ' . $this->flow
        ->label() . ' has been updated.');
      return true;
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
FlowControllerBase::$flow protected property
FlowControllerBase::canPullEntity public function Ask this Flow whether or not it can push the provided entity.
FlowControllerBase::canPushEntity public function @inheritDoc
FlowControllerBase::canPushEntityType public function @inheritDoc
FlowControllerBase::getEntityTypeHandler public function The the entity type handler for the given config.
FlowControllerBase::getEntityTypesToPull public function @inheritDoc
FlowControllerBase::getFieldHandler public function Get the correct field handler instance for this entity type and field config.
FlowControllerBase::getPoolsToPushTo public function Get a list of all pools that are used for pushing this entity, either automatically or manually selected.
FlowControllerBase::getPreviewType public function Get the preview type.
FlowControllerBase::getUsedPools public function Get a list of all pools this Flow is using.
FlowControllerBase::getUsedPoolsForPulling public function Get a list of all pools that are used for pushing this entity, either automatically or manually selected.
FlowControllerBase::supportsEntity public function Ask this synchronization whether it supports the provided entity. Returns false if either the entity type is not known or the config handler is set to {
FlowControllerBase::usesPool public function Check if the given pool is used by this Flow. If any handler set the flow as FORCE or ALLOW, this will return TRUE. 1
FlowControllerBase::__construct public function
FlowControllerPerBundle::createFlow public static function Create a flow configuration programmatically.
FlowControllerPerBundle::getEntityTypeConfig public function @inheritDoc Overrides IFlowController::getEntityTypeConfig
FlowControllerPerBundle::getPropertyConfig public function @inheritDoc Overrides IFlowController::getPropertyConfig
FlowControllerPerBundle::getType public function Overrides IFlowController::getType
FlowControllerPerBundle::needsEntityTypeUpdate public function @inheritDoc Overrides IFlowController::needsEntityTypeUpdate
FlowControllerPerBundle::setPool public function Update the Pool usage type across all bundles for the given pool.
FlowControllerPerBundle::updateEntityTypeBundleVersion public function Update the version of an entity type bundle within a flow configuration.
FlowControllerPerBundle::updateEntityTypeVersions public function Cache the current version per entity type. Overrides IFlowController::updateEntityTypeVersions