-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentity.drush.inc
1168 lines (1097 loc) · 33 KB
/
entity.drush.inc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Drush support for entities.
*/
/**
* Define how a print out needs to be
*/
define('DRUSH_ENTITY_SEPARATED_SPACE', 'space-separated');
/**
* Implementation of hook_drush_command().
*/
function entity_drush_command() {
// Some standard settings
$output_json = "Process the entity as JSON";
$output_format = "Define output format. Known formats are: json, print_r, properties, export";
$type = "Entity type";
$nids = "A list of space-separated entity IDs to print to stdout.";
$bundles = "Filter by entity bundles. Provide a comma separated list of entity types.";
$items = array();
/*
* Entity type commands
*/
$items['entity-type-read'] = array(
'description' => "List details of entity types",
'arguments' => array(
'type' => "Entity type to list. If omitted all types are listed.",
),
'options' => array(
'format' => $output_format,
'fields' => 'fields of type to list specific info.',
'exclude-fields' => 'exclude fields from the list',
'include-fieldapi' => 'include the bundle specific field definitions',
),
'examples' => array(
'entity-type-read' => 'List available entity types',
'entity-type-read node' => 'List node type information',
'entity-type-read node --fields=bundles' => 'List bundles for node type',
"etr --fields='entity keys',fieldable" => 'List all entity keys and fieldable.',
'entity-type-read node --fields=bundles/*/admin/path' => 'List admin path for all bundles',
),
'aliases' => array('etr'),
);
$items['entity-list'] = array(
'callback' => 'drush_entity_list',
'description' => 'Get a list of entity type information in a summary table.',
'aliases' => array('el'),
'arguments' => array(
'types' => dt('A space separated list of entity types to show.'),
),
'examples' => array(
'entity-list' => 'Displays all entity summaries',
'entity-list node' => 'Displays node entity summary',
'entity-list node user' => 'Displays node and user entity summaries.',
),
);
/*
* Entity commands
*/
$items['entity-create'] = array(
'description' => "Create an entity from a json object",
'arguments' => array(
'type' => "Entity type",
),
'options' => array(
'json' => $output_json,
),
'examples' => array(
'entity-read node 4 --json | drush entity-create node' => 'Copy node/4 to a new entity.',
),
'aliases' => array('ec'),
);
$items['entity-read'] = array(
'description' => "Print entity contents",
'arguments' => array(
'type' => $type,
'nids' => $nids,
),
'options' => array(
'format' => $output_format,
'fields' => 'fields of type to list specific info',
'bundles' => $bundles,
),
'examples' => array(
'entity-read user 4' => 'Print the user object 4',
'entity-read taxonomy_vocabulary 1' => 'Print the taxonomy_vocabulary object 1',
),
'aliases' => array('er'),
);
$items['entity-update'] = array(
'description' => "Update an entity as json in the default editor",
'arguments' => array(
'type' => $type,
'nids' => $nids,
),
'options' => array(
'json' => $output_json,
'fields' => 'fields of type to list specific info',
'json-input' => 'Filename with json content, or - for STDIN'
),
'examples' => array(
'entity-update node 4' => 'Update node 4 as json in the default editor',
),
'aliases' => array('eu'),
);
$items['entity-delete'] = array(
'description' => 'Delete entities.',
'arguments' => array(
'type' => $type,
'nids' => $nids,
),
'options' => array(
'json' => $output_json,
'bundles' => $bundles,
),
'examples' => array(
'entity-delete' => '.',
'entity-delete node 64' => '.',
'entity-delete node --type=story' => '.',
),
'aliases' => array('ed'),
);
return $items;
}
/**
* Implementation of hook_drush_help().
*
* @param
* A string with the help section (prepend with 'drush:')
*
* @return
* A string with the help text for your command.
*/
function entity_drush_help($section) {
switch ($section) {
case 'drush:entity-show':
return dt("Print entity objects to stdout");
case 'drush:entity-create':
return dt("Create an entity from a json object");
case 'drush:entity-edit':
return dt("Edit an entity as json in the default editor");
case 'drush:entity-delete':
return dt("Delete entities.");
case 'meta:entity:title':
return dt("Entity commands");
case 'meta:entity:summary':
return dt("Query (perform CRUD operations) drupal entities.");
}
}
/**
* Drush callback function to get entity info.
*/
function drush_entity_list() {
$entities = _drush_entity_get_info();
$types = func_get_args();
if (count($types)) {
foreach (array_keys($entities) as $entity) {
if (!in_array($entity, $types)) {
unset($entities[$entity]);
}
}
}
$count = count($entities);
drush_print("\nEntity count: $count\n");
$header = array(
dt("Entity"),
dt("Label"),
dt("Bundles"),
dt("Base table"),
dt("Revision table"),
dt("Count"),
dt("Fieldable"),
dt("Entity class"),
dt("Controller class"),
);
$newline = function($value) {
return $value . "\n";
};
$header = array_map($newline, $header);
// drush etr `drush etr` --fields="bundles/*/label,label,base table,revision table,fieldable,entity class,controller class,drush/count"
$rows = array();
$row = array();
foreach ($entities as $machine => $info) {
$row[] = $machine;
$row[] = isset($info['label']) ? $info['label'] : dt("No label found");
$row[] = is_array($info['bundles']) ? _drush_entity_get_bundle_labels($info['bundles']) : NULL;
$row[] = $info['base table'];
$row[] = isset($info['revision table']) ? $info['revision table'] : NULL;
$row[] = $info['drush']['count'];
$row[] = $info['fieldable'] ? dt("TRUE") : dt("FALSE");
$row[] = isset($info['entity class']) ? $info['entity class'] : dt("Default");
$row[] = isset($info['controller class']) ? $info['controller class'] : dt("Default");
// Add row to rows array.
$rows[$machine] = $row;
//Unset so we can start again on next iteration.
unset($row);
}
array_unshift($rows, $header);
drush_print_table($rows, TRUE);
}
/**
* Get list of bundle labels for an entity type.
* This list can be returned as an array or csv list.
*
* @param $bundles
* bundles array from entity_get_info().
* @param $csv
* (bool) return as csv list or as array of bundle labels.
*/
function _drush_entity_get_bundle_labels($bundles, $csv = TRUE) {
$labels = array();
foreach ($bundles as $bundle_key => $bundle_info) {
if (drush_drupal_major_version() < 7) {
$bundle_name = $bundle_info;
}
else {
$bundle_name = $bundle_info['label'];
}
$label = isset($bundle_name) ? $bundle_name : dt("No label found");
$labels[] = $label . " ($bundle_key)";
}
return $csv ? implode("\n", $labels) : $labels;
}
/**
* List details of entity types
*
* @param type $type
* @return type
*/
function drush_entity_type_read($entity_types = NULL) {
$types = func_get_args();
$entities_info = _drush_entity_get_info();
$fields = _drush_entity_get_fields();
$format = drush_get_option('format', 'print_r');
// List the available types
if (!count($entity_types)) {
if (!$fields) {
$result = array_keys($entities_info);
//$header = dt("Available entity types:");
drush_print(drush_format($result, NULL, $format));
return;
}
else {
$types = array_keys($entities_info);
}
}
$result = array();
if (count($types)) {
foreach ($types as $type) {
if (isset($entities_info[$type])) {
$info = $entities_info[$type];
$result_type = _drush_entity_filter_fields($info, $fields, _drush_entity_get_exclude_fields());
if (!empty($result_type)) {
$result[$type] = $result_type;
}
}
}
}
drush_print(drush_format($result, NULL, $format));
return;
}
/**
* Filter on the given paths
*
* Each path may contain forward slashes / to filter subtrees
*
* A path may contain a star * or ** to wildcard a path
*
* Example paths (ignore space after *)
* - schema_fields_sql
* - bundles/* /label
* - ** /display
*
* @param array $value
* @param array $paths
* List of paths to filter about.
* @return array
* The matching path
*/
function _drush_entity_filter_fields($value = array(), array $paths, array $delete_path = array()) {
// Store object hashs to prevent object ref recursion
$object_hash_list = array();
$return = array();
if (empty($paths)) {
$return = $value;
}
// List of path already done
$visited = array();
while (count($paths) > 0) {
$path = array_shift($paths);
if (isset($visited[$path])) {
continue;
}
$visited[$path] = $path;
// Contains the resulting path
$head = array();
// The result is a linked list done with an key => array construct
$tail = &$head; // By ref
$sub_tree = explode('/', $path);
$current_path = '';
$work_value = $value;
$failed_path = FALSE;
while (count($sub_tree) > 0) {
$p = array_shift($sub_tree);
if ($p == '*' || $p == '**') {
// Wildcards only usefull on arrays
if (is_array($work_value) || _drush_entity_visit_object(&$object_hash_list, $work_value)) {
// Say a/**/b was requested
// We need to search for a/b and a/$option/**/b
$new_tree = $sub_tree;
$new_path = $current_path . join('/', $new_tree);
if (!isset($visited[$new_path])) {
array_push($paths, $new_path);
}
// We cast to array only to generate paths
$p_options = array_keys((array) $work_value);
//$p = array_shift($p_options);
foreach ($p_options as $p_option) {
// Create
$new_tree = $sub_tree;
array_unshift($new_tree, $p_option);
$new_path = $current_path . join('/', $new_tree);
if (!isset($visited[$new_path])) {
array_push($paths, $new_path);
if ($p == '**') {
$new_tree = $sub_tree;
array_unshift($new_tree, '**');
array_unshift($new_tree, $p_option);
$new_path = $current_path . join('/', $new_tree);
if (!isset($visited[$new_path])) {
array_push($paths, $new_path);
}
}
}
}
}
else {
$failed_path = TRUE;
}
// We processed the wildcard paths so stop processing
break; // sub tree processing
}
// Remember current path
$current_path .= $p . '/';
// Consume key
$temp = (array) $work_value;
if (is_array($temp) && isset($temp[$p])) {
$work_value = $temp[$p];
if (is_object($work_value) || is_array($work_value)) {
if (count($sub_tree)) {
// We are not done yet
$tail[$p] = array();
}
else {
// Stuff value: object or array
$tail[$p] = $work_value;
}
}
else {
$tail[$p] = $work_value;
}
// Follow the build tree
$tail = &$tail[$p]; // By ref
}
else {
$failed_path = TRUE;
break; // while
}
}
if (!$failed_path && count($sub_tree) == 0) {
$return = array_merge_recursive($return, $head);
}
}
if ($delete_path) {
$delete = _drush_entity_filter_fields($return, $delete_path);
// TODO substract $delete from $return .. next command deletes more
// try etr --include-fieldapi ... the are deleted too
// $return = array_diff($return, $delete);
}
return $return;
}
/**
* List the entity IDs of the given type
*
* @param type $entity_type
* @param $bundles
* array of bundles (as returned from drush_get_option).
* @param $print
* TRUE/FALSE - print ids to screen.s
*/
function _drush_entity_id_list($entity_type, $bundles = NULL, $print = TRUE) {
$entity_info = _drush_entity_get_info($entity_type);
$bundle_list = '';
$result = array();
if (drush_drupal_major_version() < 7) {
if (isset($entity_info['load list sql'])) {
// TODO: Add bundle condition to query.
$sql = $entity_info['load list sql'];
$entities = array();
$result = db_query($sql);
while ($row = db_fetch_array($result)) {
$id = $row['id'];
$entities[$entity_type][$id] = $id;
}
}
}
else {
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', $entity_type);
if ($bundles) {
$query->entityCondition('bundle', $bundles);
//Return bundles values back to csv format.
$bundle_list = implode(',', $bundles);
}
$entities = $query->execute();
}
if (isset($entities[$entity_type])) {
$result = array_keys($entities[$entity_type]);
}
if ($print) {
if (!empty($result)) {
// Will only be set if there are results.
$drush_format = drush_get_option('format');
$format = $drush_format ? $drush_format : DRUSH_ENTITY_SEPARATED_SPACE;
//$header = $bundles ? dt("Available $bundle_list ids for $entity_type") : dt("Available ids for $entity_type");
}
else {
$format = DRUSH_ENTITY_SEPARATED_SPACE;
$header = $bundles ? dt("No $bundle_list entities found for $entity_type") : dt("No ids found for $entity_type");
$result = array();
}
_drush_entity_print($result, $format);
}
return $result;
}
/**
* Show entities by given type and id
*
* @param string $type
* Given entity type
*/
function drush_entity_read($entity_type = NULL) {
if (!$entity_type) {
drush_set_error('DRUSH_ENTITY_ERROR', dt("You must specify an entity_type"));
return;
}
$ids = func_get_args();
$entity_type = array_shift($ids);
_drush_entity_check_type($entity_type);
$bundles = _drush_entity_get_bundles();
// Do listing
if (count($ids) == 0) {
_drush_entity_id_list($entity_type, $bundles);
return;
}
// Do content
$entities = _drush_entity_load($entity_type, $ids);
$fields = _drush_entity_get_fields();
if ($fields) {
$entities = _drush_entity_select_fields($entities, $fields, TRUE);
}
if (drush_get_option('json', FALSE) && count($entities) == 1) {
// We only shift when requesting json and just one entity
$entities = array_shift($entities);
}
if ($entities) {
drush_print_pipe(drush_format($entities));
drush_print(drush_format($entities));
}
else {
$ids = implode(',', $ids); // This could be drush format too.
drush_set_error('DRUSH_ENTITY_READ_ERROR', dt("No entities returned for IDs: $ids."));
}
}
/**
* Extract the selected fields from a number of entities.
*
* @param type $entities Array of entities
* @param type $fields Array of fileds to be returned for each entity
* @return type
*/
function _drush_entity_select_fields($entities, $fields, $allow_path = FALSE) {
if (!$allow_path) {
foreach ($fields as $path) {
if (strpos($path, '/') !== FALSE) {
drush_set_error('DRUSH_ENTITY_FIELD_ERROR', dt("No path supported yet : $path"));
}
if (strpos($path, '*') !== FALSE) {
drush_set_error('DRUSH_ENTITY_FIELD_ERROR', dt("No wildcard supported yet : $path"));
}
}
}
$result = array();
foreach ($entities as $eid => $entity) {
$result[$eid] = _drush_entity_filter_fields((array) $entity, $fields);
}
return $result;
}
/**
* Create an entity by the given type.
*
* @param $entity_type
* @param $arg
*/
function drush_entity_create($entity_type = NULL, $arg = NULL) {
if (!$entity_type) {
drush_set_error('DRUSH_ERROR', dt("You must specify an entity type"));
return;
}
// if (!drush_get_option('json')) {
// drush_die("You must specify --json");
// }
_drush_entity_check_type($entity_type);
if (empty($arg)) {
$entity_class = isset($entity_info['entity class']) ? $entity_info['entity class'] : 'stdClass';
$entity = new $entity_class();
if (isset($entity_info['drush']['defaults'])) {
foreach ($entity_info['drush']['defaults'] as $key => $value) {
$entity->$key = $value;
}
}
$entity_json = _drush_entity_edit_string(drush_json_encode($entity));
}
else if ($arg === '-' || file_exists($arg)) {
if ($arg === '-') {
$entity_json = stream_get_contents(STDIN);
}
else {
drush_log("Reading file $arg");
$entity_json = file_get_contents($arg);
}
}
else {
drush_set_error('DRUSH_ERROR', dt("Improper input/args"));
}
if (!empty($entity_json)) {
$entities = drush_json_decode($entity_json);
if (is_array($entities)) {
foreach ($entities as $entity_array) {
$entity = (object) $entity_array;
_drush_entity_create_entity($entity_type, $entity);
}
}
else {
$entity = $entities;
_drush_entity_create_entity($entity_type, $entity);
}
}
else if ($arg === '-') {
drush_set_error('DRUSH_NO_STDIN', dt("stdin empty!"));
}
else {
drush_set_error('DRUSH_EMPTY_FILE', dt("Empty file!"));
}
}
/**
* Helper function to create entities.
*
* @param $entity_type
* @param $entity
*
*/
function _drush_entity_create_entity($entity_type, $entity) {
$entity_info = _drush_entity_get_info($entity_type);
$eid = $entity_info['drush']['new'][0];
if (_drush_entity_save($entity_type, $entity, TRUE)) {
_drush_entity_print('', DRUSH_ENTITY_SEPARATED_SPACE, 'Entity created.');
}
elseif (isset($entity->$eid)) {
_drush_entity_print(array($entity->$eid), DRUSH_ENTITY_SEPARATED_SPACE, 'Entity created.');
}
else {
drush_set_error('DRUSH_ERROR', dt("Failed to create entity!"));
}
}
/**
* Edit a string with the default shell editor.
*
* @param type $string
* @return type
*/
function _drush_entity_edit_string($string) {
$editor = getenv('EDITOR');
if (empty($editor)) {
drush_set_error('DRUSH_NO_EDITOR', dt('The environment variable EDITOR is not set'));
return $string;
}
else {
$file = drush_save_data_to_temp_file($string);
drush_shell_exec_interactive('$EDITOR ' . $file);
return file_get_contents($file, "r");
}
}
/**
* Convert bundles passed as drush options into array of bundle types.
*
* @return array of bundles types.
*/
function _drush_entity_get_bundles() {
$bundles = drush_get_option('bundles');
if ($bundles) {
return explode(',', $bundles);
}
return $bundles;
}
/**
* Convert the given fields into an array
*
* @return Array
*/
function _drush_entity_get_fields() {
$fields = drush_get_option('fields');
if ($fields) {
return explode(',', $fields);
}
return array();
}
function _drush_entity_get_exclude_fields() {
$fields = drush_get_option('exclude-fields', '');
// We always include 'drush' to exclude fields
if (!$fields) {
$fields = 'drush';
}
else {
$fields .= ',drush';
}
$exclude_fields = explode(',', $fields);
return array_diff($exclude_fields, _drush_entity_get_fields());
}
/**
* Update given entity.
*/
function drush_entity_update($entity_type, $id) {
$fields = _drush_entity_get_fields();
$entities = _drush_entity_load($entity_type, array($id));
if (isset($entities[$id])) {
$entity = $entities[$id];
$input = drush_get_option('json-input', NULL);
if ($input === '-') {
$edited_obj_json = stream_get_contents(STDIN);
}
elseif (file_exists($input)) {
drush_log("Reading file $input");
$edited_obj_json = file_get_contents($input);
}
else {
// Prepare to EDIT a json string
if ($fields) {
$entities_fields = _drush_entity_select_fields($entities, $fields, FALSE);
}
if ($fields) {
$edit_obj = $entities_fields[$id];
}
else {
$edit_obj = $entity;
}
$edited_obj_json = _drush_entity_edit_string(drush_json_encode($edit_obj));
}
// Prepare the changed entity to be saved
if ($fields) {
// Remap fields onto entity
$edited_entity = $entity;
$edited_fields = (object) drush_json_decode($edited_obj_json);
foreach ($fields as $field) {
$edited_entity->$field = $edited_fields->$field;
}
}
else {
$edited_entity = (object) drush_json_decode($edited_obj_json);
}
// Save
_drush_entity_save($entity_type, $edited_entity);
}
else {
drush_set_error('DRUSH_ENTITY_ERROR', dt("Entity to update not found!"));
}
}
/**
* Load entities with the given type and IDs
*
* @param type $entity_type
* @param type $ids
* @return array with entity objects
*/
function _drush_entity_load($entity_type, $ids) {
$entities = array();
switch (drush_drupal_major_version()) {
case 5:
case 6:
foreach ($ids as $id) {
$entity = _drush_entity_op('load', $entity_type, $id);
$entities[$id] = (object) $entity;
}
break;
default:
// This should always be the latest API core version.
// For now both 7 and 8
$entities = entity_load($entity_type, $ids);
break;
}
return $entities;
}
/**
* Entity delete command callback.
*/
function drush_entity_delete($entity_type = NULL, $ids = NULL) {
$ids = func_get_args();
$entity_type = array_shift($ids);
$bundles = _drush_entity_get_bundles();
if (!isset($entity_type)) {
drush_set_error('DRUSH_ERROR', dt("You must specify an entity type"));
return;
}
$info = _drush_entity_get_info($entity_type);
if (!isset($info)) {
drush_set_error('DRUSH_ERROR', dt("Type '$entity_type' does not exist."));
return;
}
if (!empty($ids)) {
$result = _drush_entity_delete($entity_type, $ids);
if (count($result) > 0) {
$header = dt("Deleted $entity_type entities:");
_drush_entity_print($result, DRUSH_ENTITY_SEPARATED_SPACE, $header);
}
}
else {
$ids = _drush_entity_id_list($entity_type, $bundles, FALSE);
$bundle_list = $bundles ? implode(', ', $bundles) : NULL;
if (!empty($ids) && drush_confirm(dt("Are you sure you want to delete all $entity_type $bundle_list entities?"))) {
_drush_entity_delete($entity_type, $ids);
drush_print(dt("All $entity_type entities deleted."));
}
elseif (empty($ids)) {
drush_print(dt("There are no $entity_type entities to delete."));
}
}
}
/**
* Save the given entity as a given type.
*
*
* @param $entity_type
* The type of the entity.
* @param $entity
* The entity to save.
* @return
* Depending on implementation and drupal version
*
* @see entity_type_supports()
*/
function _drush_entity_save($entity_type, &$entity, $new = FALSE) {
if ($new) {
$entity_info = _drush_entity_get_info($entity_type);
if (isset($entity_info['drush']['new'])) {
foreach ($entity_info['drush']['new'] as $field) {
unset($entity->$field);
}
}
}
return _drush_entity_op('save', $entity_type, $entity);
}
/**
* Try running CRUD op on the given id or entity.
*
* This mimics from D7 Entity API entity.module but for all CRUD ops
*
* @param type $op
* Operation to perform. Supported ops are: save, delete, load
* @param type $entity_type
* @param type $entity_or_id
* TODO: why by ref?
* @return type
*/
function _drush_entity_op($op, $entity_type, &$entity_or_id) {
// TODO: We need to fix for D7 when $op == delete
$op_alias = $op;
if ($op == 'delete') {
// D7 operator rename ..
// TODO: is this changed ?
$op_alias = 'deletion';
// D6 user_delete requires two arguments
if (drush_drupal_major_version() < 7 && $entity_type == 'user') {
user_delete(array(), $entity_or_id);
return;
}
}
$info = _drush_entity_get_info($entity_type);
// TODO: add comment
if (isset($info['drush'][$op . ' needs'])) {
switch ($info['drush'][$op . ' needs']) {
case 'array':
$entity_or_id = (array) $entity_or_id;
break;
case 'entity':
$old = $entity_or_id;
$entity_or_id = _drush_entity_load($entity_type, array($entity_or_id));
if (empty($entity_or_id)) {
drush_log("Unable to run $op on $entity_type : $old", 'warning');
return;
}
break;
default:
break;
}
}
if (method_exists($entity_or_id, $op)) {
return $entity_or_id->$op();
}
elseif (isset($info[$op . ' callback'])) {
return $info[$op . ' callback']($entity_or_id);
}
elseif (isset($info['controller class']) && in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
return entity_get_controller($entity_type)->$op($entity_or_id);
}
elseif (function_exists($entity_type . '_' . $op)) {
$op_function = $entity_type . '_' . $op;
// Fix user_save
if ($op == 'save' && isset($info['drush']['save needs keys'])) {
$keys = (array) $entity_or_id;
return $op_function($entity_or_id, $keys);
}
else {
return $op_function($entity_or_id);
}
}
else {
drush_log("Unable to $op the entity $entity_type. Maybe you could try to install and enable the entity.module");
return FALSE;
}
}
/**
* Try to run _delete_multiple or otherwise iterate.
*
* @param type $entity_type
* @param type $ids
* @return type the delete results per type implementation
*/
function _drush_entity_delete($entity_type, $ids = array()) {
if ($entity_type == 'node') {
// We want to use _delete_multiple
return _drush_entity_delete_node($ids);
}
else {
$result = array();
foreach ($ids as $id) {
$result[$id] = _drush_entity_op('delete', $entity_type, $id);
}
}
return array_keys($result);
}
/**
* This is special as we have node_delete_multiple
*
* The code for D6 is also special as cache_clear_all is only invoked in the end
*
* @param array $nids
* //TODO : better doc please
* @return the drupal behaviour for the delete function used.
*/
function _drush_entity_delete_node(array $nids) {
if (drush_drupal_major_version() >= 7) {
node_delete_multiple($nids);
return $nids;
}
else {
// Drupal 5/6
// node-delete is implemented this way to prevent calling cache_clear_all() for each node.
foreach ($nids as $nid) {
$node = node_load($nid, NULL, TRUE);
db_query('DELETE FROM {node} WHERE nid = %d', $nid);
db_query('DELETE FROM {node_revisions} WHERE nid = %d', $nid);
node_invoke($node, 'delete');
node_invoke_nodeapi($node, 'delete');
if (function_exists('search_wipe')) {
search_wipe($node->nid, 'node');
}
}
cache_clear_all();
}
return $nids;
}
/**
* Wrapper for entity_info()
*
* We wrap entity_info to make D5/6 compatible
*/
function _drush_entity_get_info($entity_type = NULL) {
static $entities_info;
if (!isset($entities_info)) {
if (drush_drupal_major_version() < 7) {
/*
* Mapping for D6/5 which mimic D7 info structure
*/
$entities_info = array(
'node' => array(
'label' => 'Node',
'base table' => 'node',
'entity keys' => array(
'id' => 'nid',
'revision' => 'vid',
'label' => 'title',
),
'bundles' => node_get_types('names'),
'fieldable' => TRUE,
'drush' => array(
'defaults' => array(
'type' => '',
'title' => '',
),
// What fields to zap for a new entity
'new' => array('nid', 'vid'),
),
'load list sql' => 'select nid id from {node}',
),
'user' => array(
'label' => 'User',
'base table' => 'users',
'entity keys' => array(
'id' => 'nid',
'label' => 'name',
),
'bundles' => array(),
'fieldable' => FALSE,
'drush' => array(
'defaults' => array(
'name' => '',
),
// What fields to zap for a new entity
'new' => array('uid'),
// user_save needs list of keys
'save needs keys' => TRUE,
),
'load list sql' => 'select uid id from {users}',
),