Skip to content
Snippets Groups Projects
mobile_device_detection.install 2.79 KiB
<?php

/**
 * @file
 * Default install and uninstall functions which set up default data.
 */

/**
 * Implements hook_install().
 */
function mobile_device_detection_install()
{
  // Enable mobile_device_detection plugin.
  $config = \Drupal::service('config.factory')->getEditable('views.settings');
  $display_extenders = $config->get('display_extenders') ?: [];
  $display_extenders[] = 'mobile_device_detection';
  $config->set('display_extenders', $display_extenders);
  $config->save();
}

/**
 * Implements hook_uninstall().
 */
function mobile_device_detection_uninstall()
{
  // Load config factory service
  $config_factory = \Drupal::configFactory();

  // Disable mobile_device_detection plugin.
  $views_config = $config_factory->getEditable('views.settings');
  $display_extenders = $views_config->get('display_extenders') ?: [];
  $plugin_key = array_search('mobile_device_detection', $display_extenders);

  if ($plugin_key !== FALSE) {
    unset($display_extenders[$plugin_key]);
    $views_config->set('display_extenders', $display_extenders);
    $views_config->save();
  }

  // Initialize an array to track modified blocks
  $modified_blocks = [];

  // Iterate through all blocks and remove dependencies and visibility conditions
  foreach ($config_factory->listAll('block.block.') as $config_name) {
    $config = $config_factory->getEditable($config_name);
    $block_modified = FALSE;

    // Check and update module dependencies
    $dependencies = $config->get('dependencies');
    if (isset($dependencies['module'])) {
      $module_key = array_search('mobile_device_detection', $dependencies['module']);
      if ($module_key !== FALSE) {
        unset($dependencies['module'][$module_key]);
        $dependencies['module'] = array_values($dependencies['module']);
        $config->set('dependencies', $dependencies);
        $block_modified = TRUE;
      }
    }

    // Check and remove visibility conditions
    $visibility = $config->get('visibility');
    if (isset($visibility['mobile_device_detection_condition_plugin'])) {
      unset($visibility['mobile_device_detection_condition_plugin']);
      $config->set('visibility', $visibility);
      $block_modified = TRUE;
    }

    // Save config if it was modified
    if ($block_modified) {
      $config->save();
      $modified_blocks[] = $config_name;
    }
  }

  // Log a message if any blocks were modified
  if (!empty($modified_blocks)) {
    \Drupal::logger('mobile_device_detection')->notice('The mobile_device_detection module was uninstalled and modified the following blocks: @blocks. Please check that these blocks are behaving correctly.', ['@blocks' => implode(', ', $modified_blocks)]);
  } else {
    \Drupal::logger('mobile_device_detection')->notice('The mobile_device_detection module was uninstalled successfully without modifying any blocks.');
  }
}