5 * Drush integration for views.
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;
15 * Implements hook_drush_help().
17 function views_drush_help($section) {
19 case 'meta:views:title':
20 return dt('Views commands');
21 case 'meta:views:summary':
22 return dt('Views drush commands.');
27 * Implements hook_drush_command().
29 function views_drush_command() {
33 'core' => array('8+'),
34 'drupal dependencies' => array('views'),
37 $items['views-dev'] = array(
38 'description' => 'Set the Views settings to more developer-oriented values.',
39 'aliases' => array('vd'),
42 $items['views-list'] = array(
43 'description' => 'Get a list of all views in the system.',
44 'aliases' => array('vl'),
47 'description' => 'A string contained in the view\'s name to filter the results with.',
48 'example-value' => 'node',
49 'value' => 'required',
52 'description' => 'A comma-separated list of views tags by which to filter the results.',
53 'example-value' => 'default',
54 'value' => 'required',
57 'description' => 'Status of the views by which to filter the results. Choices: enabled, disabled.',
58 'example-value' => 'enabled',
59 'value' => 'required',
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.',
68 'outputformat' => array(
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',
77 $items['views-execute'] = array(
78 'description' => 'Execute a view and get the results.',
79 'aliases' => array('vex'),
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.',
84 'required-arguments' => 1,
87 'description' => 'Display a count of the results instead of each row.',
90 'description' => 'Return the results as rendered HTML output for the display.',
92 'show-admin-links' => array(
93 'description' => 'Show contextual admin links in the rendered markup.',
96 'outputformat' => array(
97 'default' => 'print-r',
98 'pipe-format' => 'var_export',
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.',
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'),
113 'description' => 'Define the output format. Known formats are: json, print_r, and export.',
118 $items['views-enable'] = array(
119 'description' => 'Enable the specified views.',
120 'arguments' => array(
121 'views' => 'A space delimited list of view names.',
123 'required-arguments' => 1,
124 'aliases' => array('ven'),
126 'drush ven frontpage taxonomy_term' => 'Enable the frontpage and taxonomy_term views.',
130 $items['views-disable'] = array(
131 'description' => 'Disable the specified views.',
132 'arguments' => array(
133 'views' => 'A space delimited list of view names.',
135 'required-arguments' => 1,
136 'aliases' => array('vdis'),
138 'drush vdis frontpage taxonomy_term' => 'Disable the frontpage and taxonomy_term views.',
146 * Command callback function for views-dev command.
148 * Changes the settings to more developer oriented values.
150 function drush_views_dev() {
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,
167 $config = \Drupal::configFactory()->getEditable('views.settings');
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';
175 // Wrap string values in quotes.
176 elseif (is_string($value)) {
177 $value = "\"$value\"";
179 drush_log(dt('!setting set to !value', array('!setting' => $setting, '!value' => $value)));
182 // Save the new config.
185 drush_log(dt('New views configuration saved.'), LogLevel::SUCCESS);
189 * Callback function for views-list command.
191 function drush_views_list() {
192 $disabled_views = array();
193 $enabled_views = array();
195 $format = drush_get_option('format', FALSE);
197 $views = \Drupal::entityManager()->getStorage('view')->loadMultiple();
199 // Get the --name option.
200 $name = array_filter(drush_get_option_list('name'));
201 $with_name = !empty($name) ? TRUE : FALSE;
203 // Get the --tags option.
204 $tags = array_filter(drush_get_option_list('tags'));
205 $with_tags = !empty($tags) ? TRUE : FALSE;
207 // Get the --status option. Store user input appart to reuse it after.
208 $status = drush_get_option('status', FALSE);
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)));
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
219 if ($with_name && !stristr($view->id(), $name[0])) {
222 if ($with_tags && !in_array($view->get('tag'), $tags)) {
226 $status_bool = $status == 'enabled';
227 if ($status && ($view->status() !== $status_bool)) {
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'),
239 // Place the row in the appropiate array, so we can have disabled views at
241 if ($view->status()) {
242 $enabled_views[] = $row;
245 $disabled_views[] = $row;
249 // Sort alphabeticaly.
250 asort($disabled_views);
251 asort($enabled_views);
253 if (count($enabled_views) || count($disabled_views)) {
254 $rows = array_merge($enabled_views, $disabled_views);
258 drush_log(dt('No views found.'));
263 * Drush views execute command.
265 function drush_views_execute($view_name, $display_id = NULL) {
266 $args = func_get_args();
267 $view_args = array();
269 // If it's more than 2, we have arguments. A display has to be specified in
271 if (count($args) > 2) {
272 $view_args = array_slice($args, 2);
275 if (!$view = Views::getView($view_name)) {
276 return drush_set_error(dt('View: "@view" not found.', array('@view' => $view_name)));
279 // Set the display and execute the view.
280 $view->setDisplay($display_id);
281 $view->preExecute($view_args);
284 if (drush_get_option('count', FALSE)) {
285 drush_set_default_outputformat('string');
286 return count($view->result);
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);
298 return $view->result;
302 drush_log(dt('No results returned for this view.') ,LogLevel::WARNING);
308 * Drush views analyze command.
310 function drush_views_analyze() {
314 $format = drush_get_option('format', FALSE);
316 $views = \Drupal::entityManager()->getStorage('view')->loadMultiple();
318 if (!empty($views)) {
319 $analyzer = \Drupal::service('views.analyzer');
320 foreach ($views as $view_name => $view) {
321 $view = $view->getExecutable();
323 if ($messages = $analyzer->getMessages($view)) {
325 $output = drush_format($messages, $format);
326 drush_print($output);
330 drush_print($view_name);
331 foreach ($messages as $message) {
333 drush_print($message['type'] .': '. $message['message'], 2);
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);
343 return drush_set_error(dt('There are no views to analyze'));
348 * Drush views enable command.
350 function drush_views_enable() {
351 $view_names = func_get_args();
352 _views_drush_op('enable', $view_names);
356 * Drush views disable command.
358 function drush_views_disable() {
359 $view_names = func_get_args();
360 _views_drush_op('disable', $view_names);
364 * Perform operations on view objects.
367 * The operation to perform.
368 * @param array $view_names
369 * An array of view names to load and perform this operation on.
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'));
377 $view_names = array_combine($view_names, $view_names);
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']);
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);
389 drush_log(dt('View: @view is already @action', $tokens), LogLevel::NOTICE);
391 // Remove this view from the viewnames input list.
392 unset($view_names[$view->id()]);
398 drush_set_error(dt('No views have been loaded'));
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);
411 * Returns an array of op types that can be performed on views.
414 * An associative array keyed by op type => action name.
416 function _views_drush_op_types() {
419 'action' => dt('enabled'),
420 'validate' => '_views_drush_view_is_disabled',
423 'action' => dt('disabled'),
424 'validate' => '_views_drush_view_is_enabled',
430 * Returns whether a view is enabled.
432 * @param Drupal\views\Entity\ViewDrupal\views\ $view
433 * The view object to check.
436 * TRUE if the View is enabled, FALSE otherwise.
438 function _views_drush_view_is_enabled(View $view) {
439 return $view->status();
443 * Returns whether a view is disabled.
445 * @param Drupal\views\Entity\View $view
446 * The view object to check.
449 * TRUE if the View is disabled, FALSE otherwise.
451 function _views_drush_view_is_disabled(View $view) {
452 return !$view->status();
456 * Implements hook_cache_clear. Adds a cache clear option for views.
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';
465 * Command argument complete callback.
467 function views_views_enable_complete() {
468 return _drush_views_complete();
472 * Command argument complete callback.
474 function views_views_disable_complete() {
475 return _drush_views_complete();
479 * Helper function to return a list of view names for complete callbacks.
482 * An array of available view names.
484 function _drush_views_complete() {
485 drush_bootstrap_max();
486 return array('values' => array_keys(\Drupal::entityManager()->getStorage('view')->loadMultiple()));