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.

df_tools_color_color_scheme_form_submit()   F
last analyzed

Complexity

Conditions 20
Paths 2636

Size

Total Lines 134
Code Lines 72

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 72
dl 0
loc 134
rs 0
c 0
b 0
f 0
cc 20
nc 2636
nop 2

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_color.module.
6
 */
7
8
use Drupal\Core\Asset\CssOptimizer;
9
use Drupal\Component\Utility\Bytes;
10
use Drupal\Component\Utility\Environment;
11
use Drupal\Component\Utility\Html;
12
use Drupal\Component\Utility\Unicode;
13
use Drupal\Core\Form\FormStateInterface;
14
15
/**
16
 * Implements hook_form_FORM_ID_alter().
17
 */
18
function df_tools_color_form_system_theme_settings_alter(&$form, FormStateInterface $form_state) {
19
  $build_info = $form_state->getBuildInfo();
20
  if (isset($build_info['args'][0]) && ($theme = $build_info['args'][0]) && color_get_info($theme) && function_exists('gd_info')) {
21
    // Replace the default color.module form submit handler with one that
22
    // handles variable replacement.
23
    // Note that color.module requires that its submission function run first so
24
    // we replace the submit handler in place.
25
    if (($key = array_search('color_scheme_form_submit', $form['#submit'])) !== FALSE) {
26
      $form['#submit'][$key] = 'df_tools_color_color_scheme_form_submit';
27
    }
28
  }
29
}
30
31
/**
32
 * Form submission handler for color_scheme_form().
33
 *
34
 * Copied from color.module and modified to add variable replacement support.
35
 *
36
 * @see color_scheme_form_submit()
37
 */
38
function df_tools_color_color_scheme_form_submit($form, FormStateInterface $form_state) {
0 ignored issues
show
Unused Code introduced by
The parameter $form is not used and could be removed. ( Ignorable by Annotation )

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

38
function df_tools_color_color_scheme_form_submit(/** @scrutinizer ignore-unused */ $form, FormStateInterface $form_state) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
39
40
  // Avoid color settings spilling over to theme settings.
41
  $color_settings = array('theme', 'palette', 'scheme');
42
  if ($form_state->hasValue('info')) {
43
    $color_settings[] = 'info';
44
  }
45
  foreach ($color_settings as $setting_name) {
46
    ${$setting_name} = $form_state->getValue($setting_name);
47
    $form_state->unsetValue($setting_name);
48
  }
49
  if (!isset($info)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $info seems to never exist and therefore isset should always be false.
Loading history...
50
    return;
51
  }
52
53
  $config = \Drupal::configFactory()->getEditable('color.theme.' . $theme);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $theme seems to be never defined.
Loading history...
54
55
  // Resolve palette.
56
  if ($scheme != '') {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $scheme seems to be never defined.
Loading history...
57
    foreach ($palette as $key => $color) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $palette seems to be never defined.
Loading history...
58
      if (isset($info['schemes'][$scheme]['colors'][$key])) {
59
        $palette[$key] = $info['schemes'][$scheme]['colors'][$key];
60
      }
61
    }
62
    $palette += $info['schemes']['default']['colors'];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $info seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $palette does not seem to be defined for all execution paths leading up to this point.
Loading history...
63
  }
64
65
  // Make sure enough memory is available.
66
  if (isset($info['base_image'])) {
67
    // Fetch source image dimensions.
68
    $source = drupal_get_path('theme', $theme) . '/' . $info['base_image'];
69
    list($width, $height) = getimagesize($source);
70
71
    // We need at least a copy of the source and a target buffer of the same
72
    // size (both at 32bpp).
73
    $required = $width * $height * 8;
74
    // We intend to prevent color scheme changes if there isn't enough memory
75
    // available.  memory_get_usage(TRUE) returns a more accurate number than
76
    // memory_get_usage(), therefore we won't inadvertently reject a color
77
    // scheme change based on a faulty memory calculation.
78
    $usage = memory_get_usage(TRUE);
79
    $memory_limit = ini_get('memory_limit');
80
    $size = Bytes::toInt($memory_limit);
81
    if (!Environment::checkMemoryLimit($usage + $required, $memory_limit)) {
82
      drupal_set_message(t('There is not enough memory available to PHP to change this theme\'s color scheme. You need at least %size more. Check the <a href="http://php.net/manual/ini.core.php#ini.sect.resource-limits">PHP documentation</a> for more information.', array('%size' => format_size($usage + $required - $size))), 'error');
0 ignored issues
show
Deprecated Code introduced by
The function drupal_set_message() has been deprecated: in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Messenger\MessengerInterface::addMessage() instead. ( Ignorable by Annotation )

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

82
      /** @scrutinizer ignore-deprecated */ drupal_set_message(t('There is not enough memory available to PHP to change this theme\'s color scheme. You need at least %size more. Check the <a href="http://php.net/manual/ini.core.php#ini.sect.resource-limits">PHP documentation</a> for more information.', array('%size' => format_size($usage + $required - $size))), 'error');

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...
83
      return;
84
    }
85
  }
86
87
  // Delete old files.
88
  $files = $config->get('files');
89
  if (isset($files)) {
90
    foreach ($files as $file) {
91
      @drupal_unlink($file);
0 ignored issues
show
Deprecated Code introduced by
The function drupal_unlink() has been deprecated: in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystem::unlink(). ( 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 */ drupal_unlink($file);

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...
Security Best Practice introduced by
It seems like you do not handle an error condition for drupal_unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

91
      /** @scrutinizer ignore-unhandled */ @drupal_unlink($file);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
92
    }
93
  }
94
  if (isset($file) && $file = dirname($file)) {
95
    @drupal_rmdir($file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for drupal_rmdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

95
    /** @scrutinizer ignore-unhandled */ @drupal_rmdir($file);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
Deprecated Code introduced by
The function drupal_rmdir() has been deprecated: in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystem::rmdir(). ( 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 */ drupal_rmdir($file);

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...
96
  }
97
98
  // No change in color config, use the standard theme from color.inc.
99
  if (implode(',', color_get_palette($theme, TRUE)) == implode(',', $palette)) {
100
    $config->delete();
101
    return;
102
  }
103
104
  // Prepare target locations for generated files.
105
  $id = $theme . '-' . substr(hash('sha256', serialize($palette) . microtime()), 0, 8);
106
  $paths['color'] = 'public://color';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$paths was never initialized. Although not strictly required by PHP, it is generally a good practice to add $paths = array(); before regardless.
Loading history...
107
  $paths['target'] = $paths['color'] . '/' . $id;
108
  foreach ($paths as $path) {
109
    file_prepare_directory($path, FILE_CREATE_DIRECTORY);
0 ignored issues
show
Deprecated Code introduced by
The function file_prepare_directory() has been deprecated: in Drupal 8.7.0, will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::prepareDirectory(). ( Ignorable by Annotation )

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

109
    /** @scrutinizer ignore-deprecated */ file_prepare_directory($path, FILE_CREATE_DIRECTORY);

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...
introduced by
The constant FILE_CREATE_DIRECTORY has been deprecated: in Drupal 8.7.0, will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::CREATE_DIRECTORY. ( Ignorable by Annotation )

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

109
    file_prepare_directory($path, /** @scrutinizer ignore-deprecated */ FILE_CREATE_DIRECTORY);
Loading history...
110
  }
111
  $paths['target'] = $paths['target'] . '/';
112
  $paths['id'] = $id;
113
  $paths['source'] = drupal_get_path('theme', $theme) . '/';
114
  $paths['files'] = $paths['map'] = array();
115
116
  // Save palette and logo location.
117
  $config
118
    ->set('palette', $palette)
119
    ->set('logo', $paths['target'] . 'logo.svg')
120
    ->save();
121
122
  // Copy over neutral images.
123
  foreach ($info['copy'] as $file) {
124
    $base = drupal_basename($file);
0 ignored issues
show
Deprecated Code introduced by
The function drupal_basename() has been deprecated: in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystem::basename(). ( Ignorable by Annotation )

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

124
    $base = /** @scrutinizer ignore-deprecated */ drupal_basename($file);

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...
125
    $source = $paths['source'] . $file;
126
    $filepath = file_unmanaged_copy($source, $paths['target'] . $base);
0 ignored issues
show
Deprecated Code introduced by
The function file_unmanaged_copy() has been deprecated: in Drupal 8.7.0, will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystemInterface::copy(). ( Ignorable by Annotation )

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

126
    $filepath = /** @scrutinizer ignore-deprecated */ file_unmanaged_copy($source, $paths['target'] . $base);

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...
127
    $paths['map'][$file] = $base;
128
    $paths['files'][] = $filepath;
129
  }
130
131
  // Render new images, if image has been provided.
132
  if (isset($info['base_image'])) {
133
    _color_render_images($theme, $info, $paths, $palette);
134
  }
135
136
  // Rewrite theme stylesheets.
137
  $css = array();
138
  foreach ($info['css'] as $stylesheet) {
139
    // Build a temporary array with CSS files.
140
    $files = array();
141
    if (file_exists($paths['source'] . $stylesheet)) {
142
      $files[] = $stylesheet;
143
    }
144
145
    foreach ($files as $file) {
146
      $css_optimizer = new CssOptimizer();
147
      // Aggregate @imports recursively for each configured top level CSS file
148
      // without optimization. Aggregation and optimization will be
149
      // handled by drupal_build_css_cache() only.
150
      $style = $css_optimizer->loadFile($paths['source'] . $file, FALSE);
151
152
      // Return the path to where this CSS file originated from, stripping
153
      // off the name of the file at the end of the path.
154
      $css_optimizer->rewriteFileURIBasePath = base_path() . dirname($paths['source'] . $file) . '/';
155
156
      // Prefix all paths within this CSS file, ignoring absolute paths.
157
      $style = preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', array($css_optimizer, 'rewriteFileURI'), $style);
158
159
      // Rewrite stylesheet with new colors.
160
      $style = _df_tools_color_color_rewrite_stylesheet($theme, $info, $paths, $palette, $style);
161
      $base_file = drupal_basename($file);
0 ignored issues
show
Deprecated Code introduced by
The function drupal_basename() has been deprecated: in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystem::basename(). ( Ignorable by Annotation )

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

161
      $base_file = /** @scrutinizer ignore-deprecated */ drupal_basename($file);

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...
162
      $css[] = $paths['target'] . $base_file;
163
      _color_save_stylesheet($paths['target'] . $base_file, $style, $paths);
164
    }
165
  }
166
167
  // Maintain list of files.
168
  $config
169
    ->set('stylesheets', $css)
170
    ->set('files', $paths['files'])
171
    ->save();
172
}
173
174
/**
175
 * Retrieves color value template ids.
176
 *
177
 * The returned ids should't have to be real color values. If the theme uses
178
 * placeholder strings in it's CSS file, those template strings would be
179
 * returned.
180
 *
181
 * This approach made themes use the same HTML color for multiple contexts.
182
 */
183
function color_get_color_value_templates($theme) {
184
  // Fetch and expand default palette.
185
  $info = color_get_info($theme);
186
187
  $default_palette = $info['schemes']['default']['colors'];
188
189
  // If colors are handled trough placeholders, we first generate them based on
190
  // color keys, and apply the defined placeholder overrides.
191
  if (isset($info['color_placeholders']) && $info['color_placeholders'] !== FALSE) {
192
    $palette_template = [];
193
194
    // Creating the default placeholders for every defined color.
195
    foreach (array_keys($default_palette) as $color_id) {
196
      $palette_template[$color_id] = $color_id;
197
    }
198
199
    // Update the generated placeholder strings with the defined overrides.
200
    if (!empty($info['color_placeholders']) && is_array($info['color_placeholders'])) {
201
      foreach ($info['color_placeholders'] as $color_id => $custom_placeholder) {
202
        if (!empty($palette_template[$color_id])) {
203
          $palette_template[$color_id] = $custom_placeholder;
204
        }
205
      }
206
    }
207
208
    $filter = [
209
      '__' => '--',
210
      ' ' => '-',
211
      '_' => '_',
212
      '/' => '-',
213
      '[' => '-',
214
      ']' => '',
215
    ];
216
217
    // Convert placeholder ids to the format we handle.
218
    foreach ($palette_template as $color_id => $color_placeholder) {
219
      $palette_template[$color_id] = '#__' . Html::cleanCssIdentifier((string) $color_placeholder, $filter) . '__';
220
    }
221
222
    return $palette_template;
223
  }
224
225
  return $default_palette;
226
}
227
228
/**
229
 * Rewrites the stylesheet to match the colors in the palette.
230
 *
231
 * Copied from color.module and modified to add variable replacement support.
232
 *
233
 * @see _color_rewrite_stylesheet
234
 */
235
function _df_tools_color_color_rewrite_stylesheet($theme, &$info, &$paths, $palette, $style) {
236
  // Prepare color conversion table.
237
  $conversion = $palette;
238
  foreach ($conversion as $k => $v) {
239
    $conversion[$k] = Unicode::strtolower($v);
0 ignored issues
show
Deprecated Code introduced by
The function Drupal\Component\Utility\Unicode::strtolower() has been deprecated: in Drupal 8.6.0, will be removed before Drupal 9.0.0. Use mb_strtolower() instead. ( Ignorable by Annotation )

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

239
    $conversion[$k] = /** @scrutinizer ignore-deprecated */ Unicode::strtolower($v);

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...
240
  }
241
  $default_color_mapping = color_get_color_value_templates($theme);
242
243
  // Split off the "Don't touch" section of the stylesheet.
244
  $split = "Color Module: Don't touch";
245
  if (strpos($style, $split) !== FALSE) {
246
    list($style, $fixed) = explode($split, $style);
247
  }
248
249
  // Find all colors in the stylesheet and the chunks in between.
250
  $style = preg_split('/(#[0-9a-f]{6}|#[0-9a-f]{3}|#__.*?__)/i', $style, -1, PREG_SPLIT_DELIM_CAPTURE);
251
  $is_color = FALSE;
252
  $output = '';
253
  $base = 'base';
254
255
  // Iterate over all the parts.
256
  foreach ($style as $chunk) {
257
    if ($is_color) {
258
      $chunk = Unicode::strtolower($chunk);
0 ignored issues
show
Deprecated Code introduced by
The function Drupal\Component\Utility\Unicode::strtolower() has been deprecated: in Drupal 8.6.0, will be removed before Drupal 9.0.0. Use mb_strtolower() instead. ( Ignorable by Annotation )

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

258
      $chunk = /** @scrutinizer ignore-deprecated */ Unicode::strtolower($chunk);

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...
259
      // Check if this is one of the colors in the default palette.
260
      if ($key = array_search($chunk, $default_color_mapping)) {
261
        $chunk = $conversion[$key];
262
      }
263
      // Not a pre-set color. Extrapolate from the base.
264
      else {
265
        $chunk = _color_shift($palette[$base], $default_color_mapping[$base], $chunk, $info['blend_target']);
266
      }
267
    }
268
    else {
269
      // Determine the most suitable base color for the next color.
270
271
      // 'a' declarations. Use link.
272
      if (preg_match('@[^a-z0-9_-](a)[^a-z0-9_-][^/{]*{[^{]+$@i', $chunk)) {
273
        $base = 'link';
274
      }
275
      // 'color:' styles. Use text.
276
      elseif (preg_match('/(?<!-)color[^{:]*:[^{#]*$/i', $chunk)) {
277
        $base = 'text';
278
      }
279
      // Reset back to base.
280
      else {
281
        $base = 'base';
282
      }
283
    }
284
    $output .= $chunk;
285
    $is_color = !$is_color;
0 ignored issues
show
introduced by
$is_color is of type mixed, thus it always evaluated to false.
Loading history...
286
  }
287
  // Append fixed colors segment.
288
  if (isset($fixed)) {
289
    $output .= $fixed;
290
  }
291
292
  // Replace paths to images.
293
  foreach ($paths['map'] as $before => $after) {
294
    $before = base_path() . $paths['source'] . $before;
295
    $before = preg_replace('`(^|/)(?!../)([^/]+)/../`', '$1', $before);
296
    $output = str_replace($before, $after, $output);
297
  }
298
299
  return $output;
300
}
301