Completed
Push — master ( 26b7c2...a85eaa )
by Jonathan
13s
created

DrushDriver::isLegacyDrush()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 3
nop 0
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 = unserialize($this->drush('version', [], ['format' => 'php']));
139
      return version_compare($version['drush-version'], '9', '<=');
140
    }
141
    catch (\RuntimeException $e) {
142
      return TRUE;
143
    }
144
  }
145
146
  /**
147
   * {@inheritdoc}
148
   */
149
  public function isBootstrapped() {
150
    return $this->bootstrapped;
151
  }
152
153
  /**
154
   * {@inheritdoc}
155
   */
156
  public function userCreate(\stdClass $user) {
157
    $arguments = array(
158
      sprintf('"%s"', $user->name),
159
    );
160
    $options = array(
161
      'password' => $user->pass,
162
      'mail' => $user->mail,
163
    );
164
    $this->drush('user-create', $arguments, $options);
165
    if (isset($user->roles) && is_array($user->roles)) {
166
      foreach ($user->roles as $role) {
167
        $this->userAddRole($user, $role);
168
      }
169
    }
170
  }
171
172
  /**
173
   * {@inheritdoc}
174
   */
175
  public function userDelete(\stdClass $user) {
176
    $arguments = array(sprintf('"%s"', $user->name));
177
    $options = array(
178
      'yes' => NULL,
179
      'delete-content' => NULL,
180
    );
181
    $this->drush('user-cancel', $arguments, $options);
182
  }
183
184
  /**
185
   * {@inheritdoc}
186
   */
187
  public function userAddRole(\stdClass $user, $role) {
188
    $arguments = array(
189
      sprintf('"%s"', $role),
190
      sprintf('"%s"', $user->name),
191
    );
192
    $this->drush('user-add-role', $arguments);
193
  }
194
195
  /**
196
   * {@inheritdoc}
197
   */
198
  public function fetchWatchdog($count = 10, $type = NULL, $severity = NULL) {
199
    $options = array(
200
      'count' => $count,
201
      'type' => $type,
202
      'severity' => $severity,
203
    );
204
    return $this->drush('watchdog-show', array(), $options);
205
  }
206
207
  /**
208
   * {@inheritdoc}
209
   */
210
  public function clearCache($type = 'all') {
211
    $type = array($type);
212
    return $this->drush('cache-clear', $type, array());
213
  }
214
215
  /**
216
   * {@inheritdoc}
217
   */
218
  public function clearStaticCaches() {
219
    // The drush driver does each operation as a separate request;
220
    // therefore, 'clearStaticCaches' can be a no-op.
221
  }
222
223
  /**
224
   * Decodes JSON object returned by Drush.
225
   *
226
   * It will clean up any junk that may have appeared before or after the
227
   * JSON object. This can happen with remote Drush aliases.
228
   *
229
   * @param string $output
230
   *   The output from Drush.
231
   *
232
   * @return object
233
   *   The decoded JSON object.
234
   */
235
  protected function decodeJsonObject($output) {
236
    // Remove anything before the first '{'.
237
    $output = preg_replace('/^[^\{]*/', '', $output);
238
    // Remove anything after the last '}'.
239
    $output = preg_replace('/[^\}]*$/s', '', $output);
240
    return json_decode($output);
241
  }
242
243
  /**
244
   * {@inheritdoc}
245
   */
246
  public function createNode($node) {
247
    $result = $this->drush('behat', array('create-node', escapeshellarg(json_encode($node))), array());
248
    return $this->decodeJsonObject($result);
249
  }
250
251
  /**
252
   * {@inheritdoc}
253
   */
254
  public function nodeDelete($node) {
255
    $this->drush('behat', array('delete-node', escapeshellarg(json_encode($node))), array());
256
  }
257
258
  /**
259
   * {@inheritdoc}
260
   */
261
  public function createTerm(\stdClass $term) {
262
    $result = $this->drush('behat', array('create-term', escapeshellarg(json_encode($term))), array());
263
    return $this->decodeJsonObject($result);
264
  }
265
266
  /**
267
   * {@inheritdoc}
268
   */
269
  public function termDelete(\stdClass $term) {
270
    $this->drush('behat', array('delete-term', escapeshellarg(json_encode($term))), array());
271
  }
272
273
  /**
274
   * {@inheritdoc}
275
   */
276
  public function isField($entity_type, $field_name) {
277
    // If the Behat Drush Endpoint is not installed on the site-under-test,
278
    // then the drush() method will throw an exception. In this instance, we
279
    // want to treat all potential fields as non-fields.  This allows the
280
    // Drush Driver to work with certain built-in Drush capabilities (e.g.
281
    // creating users) even if the Behat Drush Endpoint is not available.
282
    try {
283
      $value = array($entity_type, $field_name);
284
      $arguments = array('is-field', escapeshellarg(json_encode($value)));
285
      $result = $this->drush('behat', $arguments, array());
286
      return strpos($result, "true\n") !== FALSE;
287
    }
288
    catch (\Exception $e) {
289
      return FALSE;
290
    }
291
  }
292
293
  /**
294
   * Sets common drush arguments or options.
295
   *
296
   * @param string $arguments
297
   *   Global arguments to add to every drush command.
298
   */
299
  public function setArguments($arguments) {
300
    $this->arguments = $arguments;
301
  }
302
303
  /**
304
   * Get common drush arguments.
305
   */
306
  public function getArguments() {
307
    return $this->arguments;
308
  }
309
310
  /**
311
   * Parse arguments into a string.
312
   *
313
   * @param array $arguments
314
   *   An array of argument/option names to values.
315
   *
316
   * @return string
317
   *   The parsed arguments.
318
   */
319
  protected static function parseArguments(array $arguments) {
320
    $string = '';
321
    foreach ($arguments as $name => $value) {
322
      if (is_null($value)) {
323
        $string .= ' --' . $name;
324
      }
325
      else {
326
        $string .= ' --' . $name . '=' . $value;
327
      }
328
    }
329
    return $string;
330
  }
331
332
  /**
333
   * Execute a drush command.
334
   */
335
  public function drush($command, array $arguments = array(), array $options = array()) {
336
    $arguments = implode(' ', $arguments);
337
338
    // Disable colored output from drush.
339
    if (isset(static::$isLegacyDrush) && static::$isLegacyDrush) {
340
      $options['nocolor'] = TRUE;
341
    }
342
    else {
343
      $options['no-ansi'] = NULL;
344
    }
345
    $string_options = $this->parseArguments($options);
346
347
    $alias = isset($this->alias) ? "@{$this->alias}" : '--root=' . $this->root;
348
349
    // Add any global arguments.
350
    $global = $this->getArguments();
351
352
    $process = new Process("{$this->binary} {$alias} {$string_options} {$global} {$command} {$arguments}");
353
    $process->setTimeout(3600);
354
    $process->run();
355
356
    if (!$process->isSuccessful()) {
357
      throw new \RuntimeException($process->getErrorOutput());
358
    }
359
360
    // Some drush commands write to standard error output (for example enable
361
    // use drush_log which default to _drush_print_log) instead of returning a
362
    // string (drush status use drush_print_pipe).
363
    if (!$process->getOutput()) {
364
      return $process->getErrorOutput();
365
    }
366
    else {
367
      return $process->getOutput();
368
    }
369
370
  }
371
372
  /**
373
   * {@inheritdoc}
374
   */
375
  public function processBatch() {
376
    // Do nothing. Drush should internally handle any needs for processing
377
    // batch ops.
378
  }
379
380
  /**
381
   * {@inheritdoc}
382
   */
383
  public function runCron() {
384
    $this->drush('cron');
385
  }
386
387
  /**
388
   * Run Drush commands dynamically from a DrupalContext.
389
   */
390
  public function __call($name, $arguments) {
391
    return $this->drush($name, $arguments);
392
  }
393
394
}
395