Yaffs site version 1.1
[yaffs-website] / vendor / drush / drush / commands / core / views.d8.drush.inc
1 <?php
2
3 /**
4  * @file
5  * Drush integration for views.
6  */
7
8 use Drush\Log\LogLevel;
9 use Drupal\views\Analyzer;
10 use Drupal\views\Entity\View;
11 use Drupal\views\Views;
12 use Drupal\Component\Utility\MapArray;
13
14 /**
15  * Implements hook_drush_help().
16  */
17 function views_drush_help($section) {
18   switch ($section) {
19     case 'meta:views:title':
20       return dt('Views commands');
21     case 'meta:views:summary':
22       return dt('Views drush commands.');
23   }
24 }
25
26 /**
27  * Implements hook_drush_command().
28  */
29 function views_drush_command() {
30   $items = array();
31
32   $base = array(
33     'core' => array('8+'),
34     'drupal dependencies' => array('views'),
35   );
36
37   $items['views-dev'] = array(
38     'description' => 'Set the Views settings to more developer-oriented values.',
39     'aliases' => array('vd'),
40   ) + $base;
41
42   $items['views-list'] = array(
43     'description' => 'Get a list of all views in the system.',
44     'aliases' => array('vl'),
45     'options' => array(
46       'name' => array(
47         'description' => 'A string contained in the view\'s name to filter the results with.',
48         'example-value' => 'node',
49         'value' => 'required',
50       ),
51       'tags' => array(
52         'description' => 'A comma-separated list of views tags by which to filter the results.',
53         'example-value' => 'default',
54         'value' => 'required',
55       ),
56       'status' => array(
57         'description' => 'Status of the views by which to filter the results. Choices: enabled, disabled.',
58         'example-value' => 'enabled',
59         'value' => 'required',
60       ),
61     ),
62     'examples' => array(
63       'drush vl' => 'Show a list of all available views.',
64       'drush vl --name=blog' => 'Show a list of views which names contain "blog".',
65       'drush vl --tags=tag1,tag2' => 'Show a list of views tagged with "tag1" or "tag2".',
66       'drush vl --status=enabled' => 'Show a list of enabled views.',
67     ),
68     'outputformat' => array(
69       'default' => 'table',
70       'pipe-format' => 'list',
71       'field-default' => array('name', 'label', 'description', 'status', 'tag'),
72       'field-labels' => array('name' => 'Machine Name', 'label' => 'Name', 'description' => 'Description', 'status' => 'Status', 'tag' => 'Tag'),
73       'output-data-type' => 'format-table',
74     ),
75   ) + $base;
76
77   $items['views-execute'] = array(
78     'description' => 'Execute a view and get the results.',
79     'aliases' => array('vex'),
80     'arguments' => array(
81       'view' => 'The name of the view to execute.',
82       'display' => 'The display ID to execute. If none specified, the default display will be used.',
83     ),
84     'required-arguments' => 1,
85     'options' => array(
86       'count' => array(
87         'description' => 'Display a count of the results instead of each row.',
88       ),
89       'rendered' => array(
90         'description' => 'Return the results as rendered HTML output for the display.',
91       ),
92       'show-admin-links' => array(
93         'description' => 'Show contextual admin links in the rendered markup.',
94       ),
95     ),
96     'outputformat' => array(
97       'default' => 'print-r',
98       'pipe-format' => 'var_export',
99     ),
100     'examples' => array(
101       'drush views-execute my_view' => 'Show the result set of the default display for the my_view view.',
102       'drush views-execute my_view page_1 --rendered' => 'Show the rendered output of the my_view:page_1 view.',
103       'drush views-execute my_view page_1 3 --count' => 'Show a count of my_view:page_1 with an agument of 3 being passed.',
104     ),
105   ) + $base;
106
107   $items['views-analyze'] = array(
108     'drupal dependencies' => array('views', 'views_ui'),
109     'description' => 'Get a list of all Views analyze warnings',
110     'aliases' => array('va'),
111     'options' => array(
112       'format' => array(
113         'description' => 'Define the output format. Known formats are: json, print_r, and export.',
114       ),
115     ),
116   ) + $base;
117
118   $items['views-enable'] = array(
119     'description' => 'Enable the specified views.',
120     'arguments' => array(
121       'views' => 'A space delimited list of view names.',
122     ),
123     'required-arguments' => 1,
124     'aliases' => array('ven'),
125     'examples' => array(
126       'drush ven frontpage taxonomy_term' => 'Enable the frontpage and taxonomy_term views.',
127     ),
128   ) + $base;
129
130   $items['views-disable'] = array(
131     'description' => 'Disable the specified views.',
132     'arguments' => array(
133       'views' => 'A space delimited list of view names.',
134     ),
135     'required-arguments' => 1,
136     'aliases' => array('vdis'),
137     'examples' => array(
138       'drush vdis frontpage taxonomy_term' => 'Disable the frontpage and taxonomy_term views.',
139     ),
140   ) + $base;
141
142   return $items;
143 }
144
145 /**
146  * Command callback function for views-dev command.
147  *
148  * Changes the settings to more developer oriented values.
149  */
150 function drush_views_dev() {
151   $settings = array(
152     'ui.show.listing_filters' => TRUE,
153     'ui.show.master_display' => TRUE,
154     'ui.show.advanced_column' => TRUE,
155     'ui.always_live_preview' => FALSE,
156     'ui.always_live_preview_button' => TRUE,
157     'ui.show.preview_information' => TRUE,
158     'ui.show.sql_query.enabled' => TRUE,
159     'ui.show.sql_query.where' => 'above',
160     'ui.show.performance_statistics' => TRUE,
161     'ui.show.additional_queries' => TRUE,
162     'debug.output' => TRUE,
163     'debug.region' => 'message',
164     'ui.show.display_embed' => TRUE,
165   );
166
167   $config = \Drupal::configFactory()->getEditable('views.settings');
168
169   foreach ($settings as $setting => $value) {
170     $config->set($setting, $value);
171     // Convert boolean values into a string to print.
172     if (is_bool($value)) {
173       $value = $value ? 'TRUE' : 'FALSE';
174     }
175     // Wrap string values in quotes.
176     elseif (is_string($value)) {
177       $value = "\"$value\"";
178     }
179     drush_log(dt('!setting set to !value', array('!setting' => $setting, '!value' => $value)));
180   }
181
182   // Save the new config.
183   $config->save();
184
185   drush_log(dt('New views configuration saved.'), LogLevel::SUCCESS);
186 }
187
188 /**
189  * Callback function for views-list command.
190  */
191 function drush_views_list() {
192   $disabled_views = array();
193   $enabled_views = array();
194
195   $format = drush_get_option('format', FALSE);
196
197   $views = \Drupal::entityManager()->getStorage('view')->loadMultiple();
198
199   // Get the --name option.
200   $name = array_filter(drush_get_option_list('name'));
201   $with_name = !empty($name) ? TRUE : FALSE;
202
203   // Get the --tags option.
204   $tags = array_filter(drush_get_option_list('tags'));
205   $with_tags = !empty($tags) ? TRUE : FALSE;
206
207   // Get the --status option. Store user input appart to reuse it after.
208   $status = drush_get_option('status', FALSE);
209
210   // Throw an error if it's an invalid status.
211   if ($status && !in_array($status, array('enabled', 'disabled'))) {
212     return drush_set_error(dt('Invalid status: @status. Available options are "enabled" or "disabled"', array('@status' => $status)));
213   }
214
215   // Setup a row for each view.
216   foreach ($views as $view) {
217     // If options were specified, check that first mismatch push the loop to the
218     // next view.
219     if ($with_name && !stristr($view->id(), $name[0])) {
220       continue;
221     }
222     if ($with_tags && !in_array($view->get('tag'), $tags)) {
223       continue;
224     }
225
226     $status_bool = $status == 'enabled';
227     if ($status && ($view->status() !== $status_bool)) {
228       continue;
229     }
230
231     $row = array(
232       'name' => $view->id(),
233       'label' => $view->label(),
234       'description' =>  $view->get('description'),
235       'status' =>  $view->status() ? dt('Enabled') : dt('Disabled'),
236       'tag' =>  $view->get('tag'),
237     );
238
239     // Place the row in the appropiate array, so we can have disabled views at
240     // the bottom.
241     if ($view->status()) {
242       $enabled_views[] = $row;
243       }
244     else{
245       $disabled_views[] = $row;
246     }
247   }
248
249   // Sort alphabeticaly.
250   asort($disabled_views);
251   asort($enabled_views);
252
253   if (count($enabled_views) || count($disabled_views)) {
254     $rows = array_merge($enabled_views, $disabled_views);
255     return $rows;
256   }
257   else {
258     drush_log(dt('No views found.'));
259   }
260 }
261
262 /**
263  * Drush views execute command.
264  */
265 function drush_views_execute($view_name, $display_id = NULL) {
266   $args = func_get_args();
267   $view_args = array();
268
269   // If it's more than 2, we have arguments. A display has to be specified in
270   // that case.
271   if (count($args) > 2) {
272     $view_args = array_slice($args, 2);
273   }
274
275   if (!$view = Views::getView($view_name)) {
276     return drush_set_error(dt('View: "@view" not found.', array('@view' => $view_name)));
277   }
278
279   // Set the display and execute the view.
280   $view->setDisplay($display_id);
281   $view->preExecute($view_args);
282   $view->execute();
283
284   if (drush_get_option('count', FALSE)) {
285     drush_set_default_outputformat('string');
286     return count($view->result);
287   }
288   elseif (!empty($view->result)) {
289     if (drush_get_option('rendered', FALSE)) {
290       drush_set_default_outputformat('string');
291       // Don't show admin links in markup by default.
292       $view->hide_admin_links = !drush_get_option('show-admin-links', FALSE);
293       $output = $view->preview();
294       return drupal_render($output);
295
296     }
297     else {
298       return $view->result;
299     }
300   }
301   else {
302     drush_log(dt('No results returned for this view.') ,LogLevel::WARNING);
303     return NULL;
304   }
305 }
306
307 /**
308  * Drush views analyze command.
309  */
310 function drush_views_analyze() {
311   $messages = NULL;
312   $messages_count = 0;
313
314   $format = drush_get_option('format', FALSE);
315
316   $views = \Drupal::entityManager()->getStorage('view')->loadMultiple();
317
318   if (!empty($views)) {
319     $analyzer = \Drupal::service('views.analyzer');
320     foreach ($views as $view_name => $view) {
321       $view = $view->getExecutable();
322
323       if ($messages = $analyzer->getMessages($view)) {
324         if ($format) {
325           $output = drush_format($messages, $format);
326           drush_print($output);
327           return $output;
328         }
329         else {
330           drush_print($view_name);
331           foreach ($messages as $message) {
332             $messages_count++;
333             drush_print($message['type'] .': '. $message['message'], 2);
334           }
335         }
336       }
337     }
338
339     drush_log(dt('A total of @total views were analyzed and @messages problems were found.', array('@total' => count($views), '@messages' => $messages_count)), LogLevel::OK);
340     return $messages;
341   }
342   else {
343     return drush_set_error(dt('There are no views to analyze'));
344   }
345 }
346
347 /**
348  * Drush views enable command.
349  */
350 function drush_views_enable() {
351   $view_names = func_get_args();
352   _views_drush_op('enable', $view_names);
353 }
354
355 /**
356  * Drush views disable command.
357  */
358 function drush_views_disable() {
359   $view_names = func_get_args();
360   _views_drush_op('disable', $view_names);
361 }
362
363 /**
364  * Perform operations on view objects.
365  *
366  * @param string $op
367  *   The operation to perform.
368  * @param array $view_names
369  *   An array of view names to load and perform this operation on.
370  */
371 function _views_drush_op($op = '', array $view_names = array()) {
372   $op_types = _views_drush_op_types();
373   if (!in_array($op, array_keys($op_types))) {
374     return drush_set_error(dt('Invalid op type'));
375   }
376
377   $view_names = array_combine($view_names, $view_names);
378
379   if ($views = \Drupal::entityManager()->getStorage('view')->loadMultiple($view_names)) {
380     foreach ($views as $view) {
381       $tokens = array('@view' => $view->id(), '@action' => $op_types[$op]['action']);
382
383       if ($op_types[$op]['validate']($view)) {
384         $function = 'views_' . $op . '_view';
385         drush_op($function, $view);
386         drush_log(dt('View: @view has been @action', $tokens), LogLevel::SUCCESS);
387       }
388       else {
389         drush_log(dt('View: @view is already @action', $tokens), LogLevel::NOTICE);
390       }
391       // Remove this view from the viewnames input list.
392       unset($view_names[$view->id()]);
393     }
394
395     return $views;
396   }
397   else {
398     drush_set_error(dt('No views have been loaded'));
399   }
400
401   // If we have some unmatched/leftover view names that weren't loaded.
402   if (!empty($view_names)) {
403     foreach ($view_names as $viewname) {
404       drush_log(dt('View: @view could not be found.', array('@view' => $viewname)), LogLevel::ERROR);
405     }
406   }
407
408 }
409
410 /**
411  * Returns an array of op types that can be performed on views.
412  *
413  * @return array
414  *   An associative array keyed by op type => action name.
415  */
416 function _views_drush_op_types() {
417   return array(
418     'enable' => array(
419       'action' => dt('enabled'),
420       'validate' => '_views_drush_view_is_disabled',
421     ),
422     'disable' => array(
423       'action' => dt('disabled'),
424       'validate' => '_views_drush_view_is_enabled',
425     ),
426   );
427 }
428
429 /**
430  * Returns whether a view is enabled.
431  *
432  * @param Drupal\views\Entity\ViewDrupal\views\ $view
433  *   The view object to check.
434  *
435  * @return bool
436  *   TRUE if the View is enabled, FALSE otherwise.
437  */
438 function _views_drush_view_is_enabled(View $view) {
439   return $view->status();
440 }
441
442 /**
443  * Returns whether a view is disabled.
444  *
445  * @param Drupal\views\Entity\View $view
446  *   The view object to check.
447  *
448  * @return bool
449  *   TRUE if the View is disabled, FALSE otherwise.
450  */
451 function _views_drush_view_is_disabled(View $view) {
452   return !$view->status();
453 }
454
455 /**
456  * Implements hook_cache_clear. Adds a cache clear option for views.
457  */
458 function views_drush_cache_clear(&$types, $include_bootstrapped_types) {
459   if ($include_bootstrapped_types && \Drupal::moduleHandler()->moduleExists('views')) {
460     $types['views'] = 'views_invalidate_cache';
461   }
462 }
463
464 /**
465  * Command argument complete callback.
466  */
467 function views_views_enable_complete() {
468   return _drush_views_complete();
469 }
470
471 /**
472  * Command argument complete callback.
473  */
474 function views_views_disable_complete() {
475   return _drush_views_complete();
476 }
477
478 /**
479  * Helper function to return a list of view names for complete callbacks.
480  *
481  * @return array
482  *   An array of available view names.
483  */
484 function _drush_views_complete() {
485   drush_bootstrap_max();
486   return array('values' => array_keys(\Drupal::entityManager()->getStorage('view')->loadMultiple()));
487 }