Completed
Pull Request — master (#136)
by
unknown
01:37
created

DrushDriver   B

Complexity

Total Complexity 42

Size/Duplication

Total Lines 384
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 42
lcom 1
cbo 4
dl 0
loc 384
rs 8.295
c 0
b 0
f 0

24 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 21 4
A getRandom() 0 3 1
A bootstrap() 0 15 4
A isLegacyDrush() 0 12 2
A isBootstrapped() 0 3 1
A userCreate() 0 15 4
A userDelete() 0 8 1
A userAddRole() 0 7 1
A fetchWatchdog() 0 8 1
A clearCache() 0 4 1
A clearStaticCaches() 0 4 1
A decodeJsonObject() 0 7 1
A createNode() 0 4 1
A nodeDelete() 0 3 1
A createTerm() 0 4 1
A termDelete() 0 3 1
A isField() 0 16 2
A setArguments() 0 3 1
A getArguments() 0 3 1
A parseArguments() 0 12 3
B drush() 0 36 6
A processBatch() 0 4 1
A runCron() 0 3 1
A __call() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like DrushDriver often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DrushDriver, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Drupal\Driver;
4
5
use Drupal\Component\Utility\Random;
6
use Drupal\Driver\Exception\BootstrapException;
7
8
use Symfony\Component\Process\Process;
9
10
/**
11
 * Implements DriverInterface.
12
 */
13
class DrushDriver extends BaseDriver {
14
  /**
15
   * Store a drush alias for tests requiring shell access.
16
   *
17
   * @var string
18
   */
19
  public $alias;
20
21
  /**
22
   * Stores the root path to a Drupal installation.
23
   *
24
   * This is an alternative to using drush aliases.
25
   *
26
   * @var string
27
   */
28
  public $root;
29
30
  /**
31
   * Store the path to drush binary.
32
   *
33
   * @var string
34
   */
35
  public $binary;
36
37
  /**
38
   * Track bootstrapping.
39
   *
40
   * @var bool
41
   */
42
  private $bootstrapped = FALSE;
43
44
  /**
45
   * Random generator.
46
   *
47
   * @var \Drupal\Component\Utility\Random
48
   */
49
  private $random;
50
51
  /**
52
   * Global arguments or options for drush commands.
53
   *
54
   * @var string
55
   */
56
  private $arguments = '';
57
58
  /**
59
   * Tracks legacy drush.
60
   *
61
   * @var bool
62
   */
63
  protected static $isLegacyDrush;
64
65
  /**
66
   * Set drush alias or root path.
67
   *
68
   * @param string $alias
69
   *   A drush alias.
70
   * @param string $root_path
71
   *   The root path of the Drupal install. This is an alternative to using
72
   *   aliases.
73
   * @param string $binary
74
   *   The path to the drush binary.
75
   * @param \Drupal\Component\Utility\Random $random
76
   *   Random generator.
77
   *
78
   * @throws \Drupal\Driver\Exception\BootstrapException
79
   *   Thrown when a required parameter is missing.
80
   */
81
  public function __construct($alias = NULL, $root_path = NULL, $binary = 'drush', Random $random = NULL) {
82
    if (!empty($alias)) {
83
      // Trim off the '@' symbol if it has been added.
84
      $alias = ltrim($alias, '@');
85
86
      $this->alias = $alias;
87
    }
88
    elseif (!empty($root_path)) {
89
      $this->root = realpath($root_path);
90
    }
91
    else {
92
      throw new BootstrapException('A drush alias or root path is required.');
93
    }
94
95
    $this->binary = $binary;
96
97
    if (!isset($random)) {
98
      $random = new Random();
99
    }
100
    $this->random = $random;
101
  }
102
103
  /**
104
   * {@inheritdoc}
105
   */
106
  public function getRandom() {
107
    return $this->random;
108
  }
109
110
  /**
111
   * {@inheritdoc}
112
   */
113
  public function bootstrap() {
114
    // Check that the given alias works.
115
    // @todo check that this is a functioning alias.
116
    // See http://drupal.org/node/1615450
117
    if (!isset($this->alias) && !isset($this->root)) {
118
      throw new BootstrapException('A drush alias or root path is required.');
119
    }
120
121
    // Determine if drush version is legacy.
122
    if (!isset(self::$isLegacyDrush)) {
123
      self::$isLegacyDrush = $this->isLegacyDrush();
124
    }
125
126
    $this->bootstrapped = TRUE;
127
  }
128
129
  /**
130
   * Determine if drush is a legacy version.
131
   *
132
   * @return bool
133
   *   Returns TRUE if drush is older than drush 9.
134
   */
135
  protected function isLegacyDrush() {
136
    try {
137
      // Try for a drush 9 version.
138
      $version = trim($this->drush('version', [], ['format' => 'string']));
139
      return version_compare($version, '9', '<=');
140
    }
141
    catch (\RuntimeException $e) {
142
      // The version of drush is old enough that only `--version` was available,
143
      // so this is a legacy version.
144
      return TRUE;
145
    }
146
  }
147
148
  /**
149
   * {@inheritdoc}
150
   */
151
  public function isBootstrapped() {
152
    return $this->bootstrapped;
153
  }
154
155
  /**
156
   * {@inheritdoc}
157
   */
158
  public function userCreate(\stdClass $user) {
159
    $arguments = array(
160
      sprintf('"%s"', $user->name),
161
    );
162
    $options = array(
163
      'password' => $user->pass,
164
      'mail' => $user->mail,
165
    );
166
    $this->drush('user-create', $arguments, $options);
167
    if (isset($user->roles) && is_array($user->roles)) {
168
      foreach ($user->roles as $role) {
169
        $this->userAddRole($user, $role);
170
      }
171
    }
172
  }
173
174
  /**
175
   * {@inheritdoc}
176
   */
177
  public function userDelete(\stdClass $user) {
178
    $arguments = array(sprintf('"%s"', $user->name));
179
    $options = array(
180
      'yes' => NULL,
181
      'delete-content' => NULL,
182
    );
183
    $this->drush('user-cancel', $arguments, $options);
184
  }
185
186
  /**
187
   * {@inheritdoc}
188
   */
189
  public function userAddRole(\stdClass $user, $role) {
190
    $arguments = array(
191
      sprintf('"%s"', $role),
192
      sprintf('"%s"', $user->name),
193
    );
194
    $this->drush('user-add-role', $arguments);
195
  }
196
197
  /**
198
   * {@inheritdoc}
199
   */
200
  public function fetchWatchdog($count = 10, $type = NULL, $severity = NULL) {
201
    $options = array(
202
      'count' => $count,
203
      'type' => $type,
204
      'severity' => $severity,
205
    );
206
    return $this->drush('watchdog-show', array(), $options);
207
  }
208
209
  /**
210
   * {@inheritdoc}
211
   */
212
  public function clearCache($type = 'all') {
213
    $type = array($type);
214
    return $this->drush('cache-clear', $type, array());
215
  }
216
217
  /**
218
   * {@inheritdoc}
219
   */
220
  public function clearStaticCaches() {
221
    // The drush driver does each operation as a separate request;
222
    // therefore, 'clearStaticCaches' can be a no-op.
223
  }
224
225
  /**
226
   * Decodes JSON object returned by Drush.
227
   *
228
   * It will clean up any junk that may have appeared before or after the
229
   * JSON object. This can happen with remote Drush aliases.
230
   *
231
   * @param string $output
232
   *   The output from Drush.
233
   *
234
   * @return object
235
   *   The decoded JSON object.
236
   */
237
  protected function decodeJsonObject($output) {
238
    // Remove anything before the first '{'.
239
    $output = preg_replace('/^[^\{]*/', '', $output);
240
    // Remove anything after the last '}'.
241
    $output = preg_replace('/[^\}]*$/s', '', $output);
242
    return json_decode($output);
243
  }
244
245
  /**
246
   * {@inheritdoc}
247
   */
248
  public function createNode($node) {
249
    $result = $this->drush('behat', array('create-node', escapeshellarg(json_encode($node))), array());
250
    return $this->decodeJsonObject($result);
251
  }
252
253
  /**
254
   * {@inheritdoc}
255
   */
256
  public function nodeDelete($node) {
257
    $this->drush('behat', array('delete-node', escapeshellarg(json_encode($node))), array());
258
  }
259
260
  /**
261
   * {@inheritdoc}
262
   */
263
  public function createTerm(\stdClass $term) {
264
    $result = $this->drush('behat', array('create-term', escapeshellarg(json_encode($term))), array());
265
    return $this->decodeJsonObject($result);
266
  }
267
268
  /**
269
   * {@inheritdoc}
270
   */
271
  public function termDelete(\stdClass $term) {
272
    $this->drush('behat', array('delete-term', escapeshellarg(json_encode($term))), array());
273
  }
274
275
  /**
276
   * {@inheritdoc}
277
   */
278
  public function isField($entity_type, $field_name) {
279
    // If the Behat Drush Endpoint is not installed on the site-under-test,
280
    // then the drush() method will throw an exception. In this instance, we
281
    // want to treat all potential fields as non-fields.  This allows the
282
    // Drush Driver to work with certain built-in Drush capabilities (e.g.
283
    // creating users) even if the Behat Drush Endpoint is not available.
284
    try {
285
      $value = array($entity_type, $field_name);
286
      $arguments = array('is-field', escapeshellarg(json_encode($value)));
287
      $result = $this->drush('behat', $arguments, array());
288
      return strpos($result, "true\n") !== FALSE;
289
    }
290
    catch (\Exception $e) {
291
      return FALSE;
292
    }
293
  }
294
295
  /**
296
   * Sets common drush arguments or options.
297
   *
298
   * @param string $arguments
299
   *   Global arguments to add to every drush command.
300
   */
301
  public function setArguments($arguments) {
302
    $this->arguments = $arguments;
303
  }
304
305
  /**
306
   * Get common drush arguments.
307
   */
308
  public function getArguments() {
309
    return $this->arguments;
310
  }
311
312
  /**
313
   * Parse arguments into a string.
314
   *
315
   * @param array $arguments
316
   *   An array of argument/option names to values.
317
   *
318
   * @return string
319
   *   The parsed arguments.
320
   */
321
  protected static function parseArguments(array $arguments) {
322
    $string = '';
323
    foreach ($arguments as $name => $value) {
324
      if (is_null($value)) {
325
        $string .= ' --' . $name;
326
      }
327
      else {
328
        $string .= ' --' . $name . '=' . $value;
329
      }
330
    }
331
    return $string;
332
  }
333
334
  /**
335
   * Execute a drush command.
336
   */
337
  public function drush($command, array $arguments = array(), array $options = array()) {
338
    $arguments = implode(' ', $arguments);
339
340
    // Disable colored output from drush.
341
    if (isset(static::$isLegacyDrush) && static::$isLegacyDrush) {
342
      $options['nocolor'] = TRUE;
343
    }
344
    else {
345
      $options['no-ansi'] = NULL;
346
    }
347
    $string_options = $this->parseArguments($options);
348
349
    $alias = isset($this->alias) ? "@{$this->alias}" : '--root=' . $this->root;
350
351
    // Add any global arguments.
352
    $global = $this->getArguments();
353
354
    $process = new Process("{$this->binary} {$alias} {$string_options} {$global} {$command} {$arguments}");
355
    $process->setTimeout(3600);
356
    $process->run();
357
358
    if (!$process->isSuccessful()) {
359
      throw new \RuntimeException($process->getErrorOutput());
360
    }
361
362
    // Some drush commands write to standard error output (for example enable
363
    // use drush_log which default to _drush_print_log) instead of returning a
364
    // string (drush status use drush_print_pipe).
365
    if (!$process->getOutput()) {
366
      return $process->getErrorOutput();
367
    }
368
    else {
369
      return $process->getOutput();
370
    }
371
372
  }
373
374
  /**
375
   * {@inheritdoc}
376
   */
377
  public function processBatch() {
378
    // Do nothing. Drush should internally handle any needs for processing
379
    // batch ops.
380
  }
381
382
  /**
383
   * {@inheritdoc}
384
   */
385
  public function runCron() {
386
    $this->drush('cron');
387
  }
388
389
  /**
390
   * Run Drush commands dynamically from a DrupalContext.
391
   */
392
  public function __call($name, $arguments) {
393
    return $this->drush($name, $arguments);
394
  }
395
396
}
397