GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

drush_df_tools_config_df_cex()   D
last analyzed

Complexity

Conditions 23
Paths 13

Size

Total Lines 106
Code Lines 67

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 67
dl 0
loc 106
rs 4.1666
c 0
b 0
f 0
cc 23
nc 13
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @file
5
 * Contains df_tools_config.drush.inc.
6
 */
7
8
use Drupal\Core\Config\StorageComparer;
9
use Drupal\Core\Config\FileStorage;
10
use Drush\Config\StorageWrapper;
0 ignored issues
show
Bug introduced by
The type Drush\Config\StorageWrapper was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Drush\Log\LogLevel;
12
13
/**
14
 * Implements hook_drush_command().
15
 */
16
function df_tools_config_drush_command() {
17
  $items = [];
18
19
  $items['df-cex'] = [
20
    'description' => 'Runs the normal Drush "config-export" command with default args/options, with added magic to auto-update existing .yml files.',
21
    'aliases' => ['dcex'],
22
  ];
23
24
  return $items;
25
}
26
27
/**
28
 * Runs the "config-export" command with added options for what to do with
29
 * newly updated config.
30
 *
31
 * @return bool
32
 */
33
function drush_df_tools_config_df_cex() {
34
  global $config_directories;
35
36
  // Allow user to choose the destination.
37
  $choices = drush_map_assoc(array_keys($config_directories));
38
  unset($choices[CONFIG_ACTIVE_DIRECTORY]);
0 ignored issues
show
introduced by
The constant CONFIG_ACTIVE_DIRECTORY has been deprecated: in Drupal 8.0.x and will be removed before 9.0.0. Drupal core no longer creates an active directory. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

38
  unset($choices[/** @scrutinizer ignore-deprecated */ CONFIG_ACTIVE_DIRECTORY]);
Loading history...
39
  if (count($choices) >= 2) {
0 ignored issues
show
Bug introduced by
It seems like $choices can also be of type false; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

39
  if (count(/** @scrutinizer ignore-type */ $choices) >= 2) {
Loading history...
40
    $destination = drush_choice($choices, dt('Choose a destination.'));
0 ignored issues
show
Bug introduced by
The function drush_choice was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

40
    $destination = /** @scrutinizer ignore-call */ drush_choice($choices, dt('Choose a destination.'));
Loading history...
41
    if (empty($destination)) {
42
      return drush_user_abort();
0 ignored issues
show
Bug introduced by
The function drush_user_abort was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

42
      return /** @scrutinizer ignore-call */ drush_user_abort();
Loading history...
43
    }
44
  }
45
  elseif (!isset($destination)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $destination does not exist. Did you maybe mean $destination_storage?
Loading history...
46
    $destination = CONFIG_SYNC_DIRECTORY;
47
  }
48
  $destination_dir = config_get_config_directory($destination);
49
50
  $change_list = _df_tools_config_get_change_list($destination_dir);
51
  // Return early if there are no pending changes.
52
  if (empty($change_list)) {
53
    return TRUE;
54
  }
55
56
  // Initiate the normal export routines.
57
  $result = _drush_config_export(NULL, $destination_dir, NULL);
0 ignored issues
show
Bug introduced by
The function _drush_config_export was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

57
  $result = /** @scrutinizer ignore-call */ _drush_config_export(NULL, $destination_dir, NULL);
Loading history...
58
59
  // If config was exported by _drush_config_export(), cycle through the config
60
  // CRUD operations and attempt to automatically update config.
61
  if ($result) {
62
    $storage_filters = drush_config_get_storage_filters();
0 ignored issues
show
Bug introduced by
The function drush_config_get_storage_filters was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

62
    $storage_filters = /** @scrutinizer ignore-call */ drush_config_get_storage_filters();
Loading history...
63
    $destination_storage = new FileStorage($destination_dir);
64
    // If there are any filters, then attach them to the destination storage
65
    if (!empty($storage_filters)) {
66
      $destination_storage = new StorageWrapper($destination_storage, $storage_filters);
67
    }
68
69
    foreach ($change_list as $type => $list) {
70
      switch ($type) {
71
        case 'create':
72
          foreach ($list as $config) {
73
            $input = drush_prompt(dt('Enter destination module for new config @config, or "none" to skip', ['@config' => $config]));
0 ignored issues
show
Bug introduced by
The function drush_prompt was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

73
            $input = /** @scrutinizer ignore-call */ drush_prompt(dt('Enter destination module for new config @config, or "none" to skip', ['@config' => $config]));
Loading history...
74
            if ($input == 'none') {
75
              continue;
76
            }
77
            try {
78
              $module_info = \Drupal::moduleHandler()->getModule($input);
79
              $destination_dir = DRUPAL_ROOT . '/' . $module_info->getPath() . '/config/install/';
80
              $source = DRUPAL_ROOT . '/' . $destination_storage->getFilePath($config);
81
              // Create /config/install directory if it does not exist.
82
              if (!file_exists($destination_dir)) {
83
                mkdir($destination_dir, 0755, true);
84
              }
85
              $destination = $destination_dir . basename($source);
86
              if (!copy($source, $destination)) {
87
                drush_log(dt('New copy from @source to @destination failed.', ['@source' => $source, '@destination' => $destination]), LogLevel::ERROR);
0 ignored issues
show
Deprecated Code introduced by
The function drush_log() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

87
                /** @scrutinizer ignore-deprecated */ drush_log(dt('New copy from @source to @destination failed.', ['@source' => $source, '@destination' => $destination]), LogLevel::ERROR);
Loading history...
88
              }
89
              else {
90
                _df_tools_config_strip_uuid($destination);
91
                drush_log(dt('Successfully created @config.', ['@config' => $config]), LogLevel::OK);
0 ignored issues
show
Deprecated Code introduced by
The function drush_log() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

91
                /** @scrutinizer ignore-deprecated */ drush_log(dt('Successfully created @config.', ['@config' => $config]), LogLevel::OK);
Loading history...
92
              }
93
            }
94
            catch (InvalidArgumentException $e) {
95
              drush_log(dt('Module @input does not exist or is not enabled.', ['@input' => $input]), LogLevel::ERROR);
0 ignored issues
show
Deprecated Code introduced by
The function drush_log() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

95
              /** @scrutinizer ignore-deprecated */ drush_log(dt('Module @input does not exist or is not enabled.', ['@input' => $input]), LogLevel::ERROR);
Loading history...
96
            }
97
          }
98
          break;
99
        case 'update':
100
          foreach ($list as $config) {
101
            $source = DRUPAL_ROOT . '/' . $destination_storage->getFilePath($config);
102
103
            $instances = _df_tools_config_find_config_instances($destination_storage, $config);
104
            $choice = drush_choice($instances, dt('Choose update destination for @config.', ['@config' => $config]));
105
            if ($choice !== FALSE) {
106
              $destination = $instances[$choice];
107
              if (!copy($source, $destination)) {
108
                drush_log(dt('Copy from @source to @destination failed.', ['@source' => $source, '@destination' => $destination]), LogLevel::ERROR);
0 ignored issues
show
Deprecated Code introduced by
The function drush_log() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

108
                /** @scrutinizer ignore-deprecated */ drush_log(dt('Copy from @source to @destination failed.', ['@source' => $source, '@destination' => $destination]), LogLevel::ERROR);
Loading history...
109
              }
110
              else {
111
                _df_tools_config_strip_uuid($destination);
112
                drush_log(dt('Successfully copied @config.', ['@config' => $config]), LogLevel::OK);
0 ignored issues
show
Deprecated Code introduced by
The function drush_log() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

112
                /** @scrutinizer ignore-deprecated */ drush_log(dt('Successfully copied @config.', ['@config' => $config]), LogLevel::OK);
Loading history...
113
              }
114
            }
115
          }
116
          break;
117
        case 'delete':
118
          foreach ($list as $config) {
119
            $instances = _df_tools_config_find_config_instances($destination_storage, $config);
120
            $choice = drush_choice($instances, dt('Choose delete destination for @config.', ['@config' => $config]));
121
            if ($choice !== FALSE) {
122
              if (!unlink($instances[$choice])) {
123
                drush_log(dt('Deletion of @path failed.', ['@path' => $instances[$choice]]), LogLevel::ERROR);
0 ignored issues
show
Deprecated Code introduced by
The function drush_log() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

123
                /** @scrutinizer ignore-deprecated */ drush_log(dt('Deletion of @path failed.', ['@path' => $instances[$choice]]), LogLevel::ERROR);
Loading history...
124
              }
125
              else {
126
                drush_log(dt('Successfully deleted @config.', ['@config' => $config]), LogLevel::OK);
0 ignored issues
show
Deprecated Code introduced by
The function drush_log() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

126
                /** @scrutinizer ignore-deprecated */ drush_log(dt('Successfully deleted @config.', ['@config' => $config]), LogLevel::OK);
Loading history...
127
              }
128
            }
129
          }
130
          break;
131
        case 'rename':
132
          // Never seen this in practice, but we can add support if needed.
133
          break;
134
      }
135
    }
136
  }
137
138
  return TRUE;
139
}
140
141
/**
142
 * Finds instances of the given config in current Drupal modules and themes.
143
 *
144
 * @param \Drupal\Core\Config\FileStorage $storage
145
 * @param string $config
146
 *
147
 * @return array
148
 */
149
function _df_tools_config_find_config_instances($storage, $config) {
150
  $file_path = $storage->getFilePath($config);
151
  $filename = basename($file_path);
152
153
  $iterator = new RecursiveDirectoryIterator(DRUPAL_ROOT, FilesystemIterator::FOLLOW_SYMLINKS);
154
  $files = [];
155
  foreach(new RecursiveIteratorIterator($iterator) as $file){
156
    if(strpos($file, $filename) !== FALSE && strpos($file, DRUPAL_ROOT . '/sites/') === FALSE){
157
      $files[] = (string) $file;
158
    }
159
  }
160
161
  return $files;
162
}
163
164
/**
165
 * Retrieve a list of differences between the active and target configuration.
166
 *
167
 * @param string $destination_dir
168
 *   A directory path to use for reading and writing of configuration files.
169
 *
170
 * @return array
171
 *   An associative array of changes keyed by the change type.
172
 */
173
function _df_tools_config_get_change_list($destination_dir) {
174
  // Get the change list.
175
  $storage_filters = drush_config_get_storage_filters();
0 ignored issues
show
Bug introduced by
The function drush_config_get_storage_filters was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

175
  $storage_filters = /** @scrutinizer ignore-call */ drush_config_get_storage_filters();
Loading history...
176
  // Retrieve a list of differences between the active and target configuration (if any).
177
  $target_storage = new FileStorage($destination_dir);
178
  /** @var \Drupal\Core\Config\StorageInterface $active_storage */
179
  $active_storage = Drupal::service('config.storage');
180
  $comparison_source = $active_storage;
181
182
  // If the output is being filtered, then write a temporary copy before doing
183
  // any comparison.
184
  if (!empty($storage_filters)) {
185
    $tmpdir = drush_tempdir();
186
    drush_copy_dir($destination_dir, $tmpdir, FILE_EXISTS_OVERWRITE);
0 ignored issues
show
Deprecated Code introduced by
The function drush_copy_dir() has been deprecated: Use \Symfony\Component\Filesystem\Filesystem::copy. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

186
    /** @scrutinizer ignore-deprecated */ drush_copy_dir($destination_dir, $tmpdir, FILE_EXISTS_OVERWRITE);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
187
    $comparison_source = new FileStorage($tmpdir);
188
    $comparison_source_filtered = new StorageWrapper($comparison_source, $storage_filters);
189
    foreach ($active_storage->listAll() as $name) {
190
      // Copy active storage to our temporary active store.
191
      if ($existing = $active_storage->read($name)) {
192
        $comparison_source_filtered->write($name, $existing);
193
      }
194
    }
195
  }
196
197
  $config_comparer = new StorageComparer($comparison_source, $target_storage, \Drupal::service('config.manager'));
198
  if (!$config_comparer->createChangelist()->hasChanges()) {
199
    drush_log(dt('The active configuration is identical to the configuration in the export directory (!target).', ['!target' => $destination_dir]), LogLevel::OK);
0 ignored issues
show
Deprecated Code introduced by
The function drush_log() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

199
    /** @scrutinizer ignore-deprecated */ drush_log(dt('The active configuration is identical to the configuration in the export directory (!target).', ['!target' => $destination_dir]), LogLevel::OK);
Loading history...
200
    return [];
201
  }
202
203
  // Collect the changelist. Only the default language is currently supported.
204
  $change_list = $config_comparer->getChangelist();
205
206
  return $change_list;
207
}
208
209
/**
210
 * Strips UUID from a config file, if the file exists and has a UUID.
211
 *
212
 * @param string $filepath
213
 *   The full path to the file.
214
 *
215
 * @return bool
216
 *   Whether or not the operation was successful.
217
 */
218
function _df_tools_config_strip_uuid($filepath) {
219
  if ($file = file($filepath)) {
220
    if (strpos($file[0], 'uuid:') === 0) {
221
      array_shift($file);
222
      file_put_contents($filepath, implode($file));
223
    }
224
    return TRUE;
225
  }
226
  else {
227
    return FALSE;
228
  }
229
}
230