You are here

function drush_domain_generate_domains in Domain Access 8

Same name and namespace in other branches
  1. 7.3 domain.drush.inc \drush_domain_generate_domains()

Generates a list of domains for testing.

In my environment, I name hostnames one.* two.* up to ten. I also use foo.* bar.* and baz.*. We also want a non-hostname here and use myexample.com.

The script may also add test1, test2, test3 up to any number to test a large number of domains. This test is mostly for UI testing.

Parameters

string $primary: The root domain to use for domain creation.

File

domain/domain.drush.inc, line 216
Drush commands for Domain Access.

Code

function drush_domain_generate_domains($primary = 'example.com') {

  // Check the number of domains to create.
  $count = drush_get_option('count');
  $domains = \Drupal::entityTypeManager()
    ->getStorage('domain')
    ->loadMultiple(NULL, TRUE);
  if (empty($count)) {
    $count = 15;
  }

  // Ensure we don't duplicate any domains.
  $existing = [];
  if (!empty($domains)) {
    foreach ($domains as $domain) {
      $existing[] = $domain
        ->getHostname();
    }
  }

  // Set up one.* and so on.
  $names = [
    'one',
    'two',
    'three',
    'four',
    'five',
    'six',
    'seven',
    'eight',
    'nine',
    'ten',
    'foo',
    'bar',
    'baz',
  ];

  // Set the creation array.
  $new = [
    $primary,
  ];
  foreach ($names as $name) {
    $new[] = $name . '.' . $primary;
  }

  // Include a non hostname.
  $new[] = 'my' . $primary;

  // Filter against existing so we can count correctly.
  $prepared = [];
  foreach ($new as $key => $value) {
    if (!in_array($value, $existing)) {
      $prepared[] = $value;
    }
  }

  // Add any test domains that have numeric prefixes. We don't expect these URLs
  // to work, and mainly use these for testing the user interface.
  $needed = $count - count($prepared);
  for ($i = 1; $i <= $needed; $i++) {
    $prepared[] = 'test' . $i . '.' . $primary;
  }

  // Get the initial item weight for sorting.
  $start_weight = count($domains);
  $prepared = array_slice($prepared, 0, $count);

  // Create the domains.
  foreach ($prepared as $key => $item) {
    $hostname = mb_strtolower($item);
    $values = [
      'name' => $item != $primary ? ucwords(str_replace(".{$primary}", '', $item)) : \Drupal::config('system.site')
        ->get('name'),
      'hostname' => $hostname,
      'scheme' => 'http',
      'status' => 1,
      'weight' => $item != $primary ? $key + $start_weight + 1 : -1,
      'is_default' => 0,
      'id' => \Drupal::entityTypeManager()
        ->getStorage('domain')
        ->createMachineName($hostname),
    ];
    $domain = \Drupal::entityTypeManager()
      ->getStorage('domain')
      ->create($values);
    domain_drush_create($domain);
  }

  // If nothing created, say so.
  if (empty($new)) {
    drush_print(dt('No new domains were created.'));
  }
}