c4ca6a15a80c957e83257b95af9de87daa3cb35b
[yaffs-website] / vendor / drush / drush / src / Drupal / Commands / core / ViewsCommands.php
1 <?php
2 namespace Drush\Drupal\Commands\core;
3
4 use Consolidation\OutputFormatters\StructuredData\RowsOfFields;
5 use Drupal\Core\Config\ConfigFactoryInterface;
6 use Drupal\Core\Entity\EntityTypeManagerInterface;
7 use Drupal\Core\Extension\ModuleHandlerInterface;
8 use Drupal\Core\Render\RendererInterface;
9 use Drush\Commands\DrushCommands;
10 use Drupal\views\Views;
11 use Drush\Utils\StringUtils;
12
13 class ViewsCommands extends DrushCommands
14 {
15
16     protected $configFactory;
17
18     protected $moduleHandler;
19
20     protected $entityTypeManager;
21
22     protected $renderer;
23
24     /**
25      * ViewsCommands constructor.
26      * @param $moduleHandler
27      * @param $entityTypeManager
28      * @param $renderer
29      */
30     public function __construct(ConfigFactoryInterface $configFactory, ModuleHandlerInterface $moduleHandler, EntityTypeManagerInterface $entityTypeManager, RendererInterface $renderer)
31     {
32         $this->moduleHandler = $moduleHandler;
33         $this->entityTypeManager = $entityTypeManager;
34         $this->renderer = $renderer;
35         $this->configFactory = $configFactory;
36     }
37
38     /**
39      * @return \Drupal\Core\Config\ConfigFactoryInterface
40      */
41     public function getConfigFactory()
42     {
43         return $this->configFactory;
44     }
45
46     /**
47      * @return \Drupal\Core\Extension\ModuleHandlerInterface
48      */
49     public function getModuleHandler()
50     {
51         return $this->moduleHandler;
52     }
53
54     /**
55      * @return \Drupal\Core\Entity\EntityTypeManagerInterface
56      */
57     public function getEntityTypeManager()
58     {
59         return $this->entityTypeManager;
60     }
61
62     /**
63      * @return \Drupal\Core\Render\RendererInterface
64      */
65     public function getRenderer()
66     {
67         return $this->renderer;
68     }
69
70     /**
71      * Set several Views settings to more developer-oriented values.
72      *
73      * @command views:dev
74      *
75      * @validate-module-enabled views
76      * @aliases vd,views-dev
77      */
78     public function dev()
79     {
80         $settings = [
81             'ui.show.listing_filters' => true,
82             'ui.show.master_display' => true,
83             'ui.show.advanced_column' => true,
84             'ui.always_live_preview' => false,
85             'ui.always_live_preview_button' => true,
86             'ui.show.preview_information' => true,
87             'ui.show.sql_query.enabled' => true,
88             'ui.show.sql_query.where' => 'above',
89             'ui.show.performance_statistics' => true,
90             'ui.show.additional_queries' => true,
91         ];
92
93         $config = $this->getConfigFactory()->getEditable('views.settings');
94
95         foreach ($settings as $setting => $value) {
96             $config->set($setting, $value);
97             // Convert boolean values into a string to print.
98             if (is_bool($value)) {
99                 $value = $value ? 'TRUE' : 'FALSE';
100             } // Wrap string values in quotes.
101             elseif (is_string($value)) {
102                 $value = "\"$value\"";
103             }
104             $this->logger()->success(dt('!setting set to !value', [
105                 '!setting' => $setting,
106                 '!value' => $value
107             ]));
108         }
109
110         // Save the new config.
111         $config->save();
112
113         $this->logger()->success(dt('New views configuration saved.'));
114     }
115
116     /**
117      * Get a list of all views in the system.
118      *
119      * @command views:list
120      *
121      * @option name A string contained in the view's name to filter the results with.
122      * @option tags A comma-separated list of views tags by which to filter the results.
123      * @option status Filter views by status. Choices: enabled, disabled.
124      * @usage drush vl
125      *   Show a list of all available views.
126      * @usage drush vl --name=blog
127      *   Show a list of views which names contain 'blog'.
128      * @usage drush vl --tags=tag1,tag2
129      *   Show a list of views tagged with 'tag1' or 'tag2'.
130      * @usage drush vl --status=enabled
131      *   Show a list of enabled views.
132      * @table-style default
133      * @field-labels
134      *   machine-name: Machine name
135      *   label: Name
136      *   description: Description
137      *   status: Status
138      *   tag: Tag
139      * @default-fields machine-name,label,description,status
140      * @aliases vl,views-list
141      * @validate-module-enabled views
142      *
143      * @return \Consolidation\OutputFormatters\StructuredData\RowsOfFields
144      */
145     public function vlist($options = ['name' => self::REQ, 'tags' => self::REQ, 'status' => self::REQ, 'format' => 'table'])
146     {
147         $disabled_views = [];
148         $enabled_views = [];
149
150         $views = $this->getEntityTypeManager()->getStorage('view')->loadMultiple();
151
152         // Get the --name option.
153         $name = StringUtils::csvToArray($options['name']);
154         $with_name = !empty($name) ? true : false;
155
156         // Get the --tags option.
157         $tags = \_convert_csv_to_array($options['tags']);
158         $with_tags = !empty($tags) ? true : false;
159
160         // Get the --status option. Store user input apart to reuse it after.
161         $status = $options['status'];
162
163         // @todo See https://github.com/consolidation/annotated-command/issues/53
164         if ($status && !in_array($status, ['enabled', 'disabled'])) {
165             throw new \Exception(dt('Invalid status: @status. Available options are "enabled" or "disabled"', ['@status' => $status]));
166         }
167
168         // Setup a row for each view.
169         foreach ($views as $view) {
170             // If options were specified, check that first mismatch push the loop to the
171             // next view.
172             if ($with_name && !stristr($view->id(), $name[0])) {
173                 continue;
174             }
175             if ($with_tags && !in_array($view->get('tag'), $tags)) {
176                 continue;
177             }
178
179             $status_bool = $status == 'enabled';
180             if ($status && ($view->status() !== $status_bool)) {
181                 continue;
182             }
183
184             $row = [
185             'machine-name' => $view->id(),
186             'label' => $view->label(),
187             'description' =>  $view->get('description'),
188             'status' =>  $view->status() ? dt('Enabled') : dt('Disabled'),
189             'tag' =>  $view->get('tag'),
190             ];
191
192             // Place the row in the appropriate array, so we can have disabled views at
193             // the bottom.
194             if ($view->status()) {
195                   $enabled_views[] = $row;
196             } else {
197                   $disabled_views[] = $row;
198             }
199         }
200
201         // Sort alphabetically.
202         asort($disabled_views);
203         asort($enabled_views);
204
205         if (count($enabled_views) || count($disabled_views)) {
206             $rows = array_merge($enabled_views, $disabled_views);
207             return new RowsOfFields($rows);
208         } else {
209             $this->logger()->notice(dt('No views found.'));
210         }
211     }
212
213     /**
214      * Execute a view and show a count of the results, or the rendered HTML.
215      *
216      * @command views:execute
217      *
218      * @param string $view_name The name of the view to execute.
219      * @param string $display The display ID to execute. If none specified, the default display will be used.
220      * @param string $view_args A comma delimited list of values, corresponding to contextual filters.
221      * @option count Display a count of the results instead of each row.
222      * @option show-admin-links Show contextual admin links in the rendered markup.
223      * @usage drush views:execute my_view
224      *   Show the rendered HTML for the default display for the my_view View.
225      * @usage drush views:execute my_view page_1 3 --count
226      *   Show a count of my_view:page_1 where the first contextual filter value is 3.
227      * @usage drush views:execute my_view page_1 3,foo
228      *   Show the rendered HTML of my_view:page_1 where the first two contextual filter values are 3 and 'foo' respectively.
229      * @validate-entity-load view view_name
230      * @aliases vex,views-execute
231      * @validate-module-enabled views
232      *
233      * @return string
234      */
235     public function execute($view_name, $display = null, $view_args = null, $options = ['count' => 0, 'show-admin-links' => false])
236     {
237
238         $view = Views::getView($view_name);
239
240         // Set the display and execute the view.
241         $view->setDisplay($display);
242         $view->preExecute(StringUtils::csvToArray($view_args));
243         $view->execute();
244
245         if (empty($view->result)) {
246             $this->logger()->success(dt('No results returned for this View.'));
247             return null;
248         } elseif ($options['count']) {
249             drush_backend_set_result(count($view->result));
250             drush_print(count($view->result));
251             return null;
252         } else {
253             // Don't show admin links in markup by default.
254             $view->hide_admin_links = !$options['show-admin-links'];
255             $build = $view->preview();
256             return (string) $this->getRenderer()->renderPlain($build);
257         }
258     }
259
260     /**
261      * Get a list of all Views and analyze warnings.
262      *
263      * @command views:analyze
264      * @todo Command has not  been fully tested. How to generate a message?
265      * @field-labels
266      *   type: Type
267      *   message: Message
268      * @aliases va,views-analyze
269      * @validate-module-enabled views
270      *
271      * @return \Consolidation\OutputFormatters\StructuredData\RowsOfFields
272      */
273     public function analyze()
274     {
275         $messages = null;
276         $messages_count = 0;
277         $rows = [];
278
279         $views = $this->getEntityTypeManager()->getStorage('view')->loadMultiple();
280
281         if (!empty($views)) {
282             $analyzer = \Drupal::service('views.analyzer');
283             foreach ($views as $view_name => $view) {
284                 $view = $view->getExecutable();
285
286                 if ($messages = $analyzer->getMessages($view)) {
287                     $rows[] = [$messages['type'], $messages['message']];
288                 }
289             }
290
291             $this->logger()->success(dt('A total of @total views were analyzed and @messages problems were found.', ['@total' => count($views), '@messages' => $messages_count]));
292             return new RowsOfFields($rows);
293         } else {
294             $this->logger()->success(dt('There are no views to analyze'));
295         }
296     }
297
298     /**
299      * Enable the specified views.
300      *
301      * @command views:enable
302      * @param string $views A comma delimited list of view names.
303      * @validate-entity-load view views
304      * @usage drush ven frontpage,taxonomy_term
305      *   Enable the frontpage and taxonomy_term views.
306      * @aliases ven,views-enable
307      */
308     public function enable($views)
309     {
310         $view_names = StringUtils::csvToArray($views);
311         if ($views = $this->getEntityTypeManager()->getStorage('view')->loadMultiple($view_names)) {
312             foreach ($views as $view) {
313                 $view->enable();
314                 $view->save();
315             }
316         }
317         $this->logger()->success(dt('!str enabled.', ['!str' => implode(', ', $view_names)]));
318     }
319
320     /**
321      * Disable the specified views.
322      *
323      * @command views:disable
324      * @validate-entity-load view views
325      * @param string $views A comma delimited list of view names.
326      * @usage drush vdis frontpage taxonomy_term
327      *   Disable the frontpage and taxonomy_term views.
328      * @aliases vdis,views-disable
329      */
330     public function disable($views)
331     {
332         $view_names = StringUtils::csvToArray($views);
333         if ($views = $this->getEntityTypeManager()->getStorage('view')->loadMultiple($view_names)) {
334             foreach ($views as $view) {
335                 $view->disable();
336                 $view->save();
337             }
338         }
339         $this->logger()->success(dt('!str disabled.', ['!str' => implode(', ', $view_names)]));
340     }
341
342     /**
343      * Adds a cache clear option for views.
344      *
345      * @hook on-event cache-clear
346      */
347     public function cacheClear(&$types, $include_bootstrapped_types)
348     {
349         if ($include_bootstrapped_types && $this->getModuleHandler()->moduleExists('views')) {
350             $types['views'] = 'views_invalidate_cache';
351         }
352     }
353 }