-
Notifications
You must be signed in to change notification settings - Fork 88
/
Scaffold_Command.php
1195 lines (1050 loc) · 37.2 KB
/
Scaffold_Command.php
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
use WP_CLI\Utils;
use WP_CLI\Inflector;
/**
* Generates code for post types, taxonomies, plugins, child themes, etc.
*
* ## EXAMPLES
*
* # Generate a new plugin with unit tests.
* $ wp scaffold plugin sample-plugin
* Success: Created plugin files.
* Success: Created test files.
*
* # Generate theme based on _s.
* $ wp scaffold _s sample-theme --theme_name="Sample Theme" --author="John Doe"
* Success: Created theme 'Sample Theme'.
*
* # Generate code for post type registration in given theme.
* $ wp scaffold post-type movie --label=Movie --theme=simple-life
* Success: Created '/var/www/example.com/public_html/wp-content/themes/simple-life/post-types/movie.php'.
*
* @package wp-cli
*/
class Scaffold_Command extends WP_CLI_Command {
/**
* Generates PHP code for registering a custom post type.
*
* ## OPTIONS
*
* <slug>
* : The internal name of the post type.
*
* [--label=<label>]
* : The text used to translate the update messages.
*
* [--textdomain=<textdomain>]
* : The textdomain to use for the labels.
*
* [--dashicon=<dashicon>]
* : The dashicon to use in the menu.
*
* [--theme]
* : Create a file in the active theme directory, instead of sending to
* STDOUT. Specify a theme with `--theme=<theme>` to have the file placed in that theme.
*
* [--plugin=<plugin>]
* : Create a file in the given plugin's directory, instead of sending to STDOUT.
*
* [--raw]
* : Just generate the `register_post_type()` call and nothing else.
*
* [--force]
* : Overwrite files that already exist.
*
* ## EXAMPLES
*
* # Generate a 'movie' post type for the 'simple-life' theme
* $ wp scaffold post-type movie --label=Movie --theme=simple-life
* Success: Created '/var/www/example.com/public_html/wp-content/themes/simple-life/post-types/movie.php'.
*
* @subcommand post-type
*
* @alias cpt
*/
public function post_type( $args, $assoc_args ) {
if ( strlen( $args[0] ) > 20 ) {
WP_CLI::error( 'Post type slugs cannot exceed 20 characters in length.' );
}
$defaults = [
'textdomain' => '',
'dashicon' => 'admin-post',
];
$templates = [
'post_type.mustache',
'post_type_extended.mustache',
];
$this->scaffold( $args[0], $assoc_args, $defaults, '/post-types/', $templates );
}
/**
* Generates PHP code for registering a custom taxonomy.
*
* ## OPTIONS
*
* <slug>
* : The internal name of the taxonomy.
*
* [--post_types=<post-types>]
* : Post types to register for use with the taxonomy.
*
* [--label=<label>]
* : The text used to translate the update messages.
*
* [--textdomain=<textdomain>]
* : The textdomain to use for the labels.
*
* [--theme]
* : Create a file in the active theme directory, instead of sending to
* STDOUT. Specify a theme with `--theme=<theme>` to have the file placed in that theme.
*
* [--plugin=<plugin>]
* : Create a file in the given plugin's directory, instead of sending to STDOUT.
*
* [--raw]
* : Just generate the `register_taxonomy()` call and nothing else.
*
* [--force]
* : Overwrite files that already exist.
*
* ## EXAMPLES
*
* # Generate PHP code for registering a custom taxonomy and save in a file
* $ wp scaffold taxonomy venue --post_types=event,presentation > taxonomy.php
*
* @subcommand taxonomy
*
* @alias tax
*/
public function taxonomy( $args, $assoc_args ) {
$defaults = [
'textdomain' => '',
'post_types' => "'post'",
];
if ( isset( $assoc_args['post_types'] ) ) {
$assoc_args['post_types'] = $this->quote_comma_list_elements( $assoc_args['post_types'] );
}
$templates = [
'taxonomy.mustache',
'taxonomy_extended.mustache',
];
$this->scaffold( $args[0], $assoc_args, $defaults, '/taxonomies/', $templates );
}
private function scaffold( $slug, $assoc_args, $defaults, $subdir, $templates ) {
$wp_filesystem = $this->init_wp_filesystem();
$control_defaults = [
'label' => preg_replace( '/_|-/', ' ', strtolower( $slug ) ),
'theme' => false,
'plugin' => false,
'raw' => false,
];
$control_args = $this->extract_args( $assoc_args, $control_defaults );
$vars = $this->extract_args( $assoc_args, $defaults );
$dashicon = $this->extract_dashicon( $assoc_args );
if ( $dashicon ) {
$vars['dashicon'] = $dashicon;
}
$vars['slug'] = $slug;
$vars['textdomain'] = $this->get_textdomain( $vars['textdomain'], $control_args );
$vars['label'] = $control_args['label'];
$vars['label_ucfirst'] = ucfirst( $vars['label'] );
$vars['label_plural'] = $this->pluralize( $vars['label'] );
$vars['label_plural_ucfirst'] = ucfirst( $vars['label_plural'] );
$machine_name = $this->generate_machine_name( $slug );
$machine_name_plural = $this->pluralize( $slug );
list( $raw_template, $extended_template ) = $templates;
$raw_output = self::mustache_render( $raw_template, $vars );
if ( ! $control_args['raw'] ) {
$vars['machine_name'] = $machine_name;
$vars['output'] = $raw_output;
$final_output = self::mustache_render( $extended_template, $vars );
} else {
$final_output = $raw_output;
}
$path = $this->get_output_path( $control_args, $subdir );
if ( is_string( $path ) && ! empty( $path ) ) {
$filename = "{$path}{$slug}.php";
$force = Utils\get_flag_value( $assoc_args, 'force' );
$files_written = $this->create_files( [ $filename => $final_output ], $force );
$skip_message = "Skipped creating '{$filename}'.";
$success_message = "Created '{$filename}'.";
$this->log_whether_files_written( $files_written, $skip_message, $success_message );
} else {
// STDOUT
echo $final_output;
}
}
/**
* Generates PHP, JS and CSS code for registering a Gutenberg block for a plugin or theme.
*
* **Warning: `wp scaffold block` is deprecated.**
*
* The official script to generate a block is the [@wordpress/create-block](https://developer.wordpress.org/block-editor/reference-guides/packages/packages-create-block/) package.
*
* See the [Create a Block tutorial](https://developer.wordpress.org/block-editor/getting-started/tutorial/) for a complete walk-through.
*
* ## OPTIONS
*
* <slug>
* : The internal name of the block.
*
* [--title=<title>]
* : The display title for your block.
*
* [--dashicon=<dashicon>]
* : The dashicon to make it easier to identify your block.
*
* [--category=<category>]
* : The category name to help users browse and discover your block.
* ---
* default: widgets
* options:
* - common
* - embed
* - formatting
* - layout
* - widgets
* ---
*
* [--theme]
* : Create files in the active theme directory. Specify a theme with `--theme=<theme>` to have the file placed in that theme.
*
* [--plugin=<plugin>]
* : Create files in the given plugin's directory.
*
* [--force]
* : Overwrite files that already exist.
*
* @subcommand block
*/
public function block( $args, $assoc_args ) {
$slug = $args[0];
if ( ! preg_match( '/^[a-z][a-z0-9\-]*$/', $slug ) ) {
WP_CLI::error( 'Invalid block slug specified. Block slugs can contain only lowercase alphanumeric characters or dashes, and start with a letter.' );
}
$defaults = [
'title' => str_replace( '-', ' ', $slug ),
'category' => 'widgets',
];
$data = $this->extract_args( $assoc_args, $defaults );
$data['slug'] = $slug;
$data['title_ucfirst'] = ucfirst( $data['title'] );
$data['title_ucfirst_js'] = esc_js( $data['title_ucfirst'] );
$dashicon = $this->extract_dashicon( $assoc_args );
if ( $dashicon ) {
$data['dashicon'] = $dashicon;
}
$control_defaults = [
'force' => false,
'plugin' => false,
'theme' => false,
];
$control_args = $this->extract_args( $assoc_args, $control_defaults );
if ( isset( $control_args['plugin'] ) ) {
if ( ! preg_match( '/^[A-Za-z0-9\-]*$/', $control_args['plugin'] ) ) {
WP_CLI::error( 'Invalid plugin name specified. The block editor can only register blocks for plugins that have nothing but lowercase alphanumeric characters or dashes in their slug.' );
}
}
$data['namespace'] = $control_args['plugin'] ? $control_args['plugin'] : $this->get_theme_name( $control_args['theme'] );
$data['machine_name'] = $this->generate_machine_name( $slug );
$data['plugin'] = $control_args['plugin'] ? true : false;
$data['theme'] = ! $data['plugin'];
$block_dir = $this->get_output_path( $control_args, '/blocks' );
if ( ! $block_dir ) {
WP_CLI::error( 'No plugin or theme selected.' );
}
$files_to_create = [
"{$block_dir}/{$slug}.php" => self::mustache_render( 'block-php.mustache', $data ),
"{$block_dir}/{$slug}/index.js" => self::mustache_render( 'block-index-js.mustache', $data ),
"{$block_dir}/{$slug}/editor.css" => self::mustache_render( 'block-editor-css.mustache', $data ),
"{$block_dir}/{$slug}/style.css" => self::mustache_render( 'block-style-css.mustache', $data ),
];
$files_written = $this->create_files( $files_to_create, $control_args['force'] );
$skip_message = 'All block files were skipped.';
$success_message = "Created block '{$data['title_ucfirst']}'.";
$this->log_whether_files_written( $files_written, $skip_message, $success_message );
}
/**
* Generates starter code for a theme based on _s.
*
* See the [Underscores website](https://underscores.me/) for more details.
*
* ## OPTIONS
*
* <slug>
* : The slug for the new theme, used for prefixing functions.
*
* [--activate]
* : Activate the newly downloaded theme.
*
* [--enable-network]
* : Enable the newly downloaded theme for the entire network.
*
* [--theme_name=<title>]
* : What to put in the 'Theme Name:' header in 'style.css'.
*
* [--author=<full-name>]
* : What to put in the 'Author:' header in 'style.css'.
*
* [--author_uri=<uri>]
* : What to put in the 'Author URI:' header in 'style.css'.
*
* [--sassify]
* : Include stylesheets as SASS.
*
* [--woocommerce]
* : Include WooCommerce boilerplate files.
*
* [--force]
* : Overwrite files that already exist.
*
* ## EXAMPLES
*
* # Generate a theme with name "Sample Theme" and author "John Doe"
* $ wp scaffold _s sample-theme --theme_name="Sample Theme" --author="John Doe"
* Success: Created theme 'Sample Theme'.
*
* @alias _s
*/
public function underscores( $args, $assoc_args ) {
$theme_slug = $args[0];
$theme_path = WP_CONTENT_DIR . '/themes';
$url = 'https://underscores.me';
$timeout = 30;
if ( ! preg_match( '/^[a-z_]\w+$/i', str_replace( '-', '_', $theme_slug ) ) ) {
WP_CLI::error( 'Invalid theme slug specified. Theme slugs can only contain letters, numbers, underscores and hyphens, and can only start with a letter or underscore.' );
}
$defaults = [
'theme_name' => ucfirst( $theme_slug ),
'author' => 'Me',
'author_uri' => '',
];
$data = wp_parse_args( $assoc_args, $defaults );
$_s_theme_path = "$theme_path/$data[theme_name]";
$error_msg = $this->check_target_directory( 'theme', $_s_theme_path );
if ( ! empty( $error_msg ) ) {
WP_CLI::error( "Invalid theme slug specified. {$error_msg}" );
}
$force = Utils\get_flag_value( $assoc_args, 'force' );
$should_write_file = $this->prompt_if_files_will_be_overwritten( $_s_theme_path, $force );
if ( ! $should_write_file ) {
WP_CLI::log( 'No files created' );
die;
}
$theme_description = "Custom theme: {$data['theme_name']}, developed by {$data['author']}";
$body = [];
$body['underscoresme_name'] = $data['theme_name'];
$body['underscoresme_slug'] = $theme_slug;
$body['underscoresme_author'] = $data['author'];
$body['underscoresme_author_uri'] = $data['author_uri'];
$body['underscoresme_description'] = $theme_description;
$body['underscoresme_generate_submit'] = 'Generate';
$body['underscoresme_generate'] = '1';
if ( Utils\get_flag_value( $assoc_args, 'sassify' ) ) {
$body['underscoresme_sass'] = 1;
}
if ( Utils\get_flag_value( $assoc_args, 'woocommerce' ) ) {
$body['underscoresme_woocommerce'] = 1;
}
$tmpfname = wp_tempnam( $url );
$post_args = [
'timeout' => $timeout,
'body' => $body,
'stream' => true,
'filename' => $tmpfname,
];
$response = wp_remote_post( $url, $post_args );
if ( is_wp_error( $response ) ) {
WP_CLI::error( $response );
}
$response_code = wp_remote_retrieve_response_code( $response );
if ( 200 !== (int) $response_code ) {
WP_CLI::error( "Couldn't create theme (received {$response_code} response)." );
}
$this->maybe_create_themes_dir();
$this->init_wp_filesystem();
$unzip_result = unzip_file( $tmpfname, $theme_path );
unlink( $tmpfname );
if ( true === $unzip_result ) {
$files_to_create = [
"{$theme_path}/{$theme_slug}/.editorconfig" => file_get_contents( self::get_template_path( '.editorconfig' ) ),
];
$this->create_files( $files_to_create, false );
WP_CLI::success( "Created theme '{$data['theme_name']}'." );
} else {
WP_CLI::error( "Could not decompress your theme files ('{$tmpfname}') at '{$theme_path}': {$unzip_result->get_error_message()}" );
}
if ( Utils\get_flag_value( $assoc_args, 'activate' ) ) {
WP_CLI::run_command( [ 'theme', 'activate', $theme_slug ] );
} elseif ( Utils\get_flag_value( $assoc_args, 'enable-network' ) ) {
WP_CLI::run_command( [ 'theme', 'enable', $theme_slug ], [ 'network' => true ] );
}
}
/**
* Generates child theme based on an existing theme.
*
* Creates a child theme folder with `functions.php` and `style.css` files.
*
* ## OPTIONS
*
* <slug>
* : The slug for the new child theme.
*
* --parent_theme=<slug>
* : What to put in the 'Template:' header in 'style.css'.
*
* [--theme_name=<title>]
* : What to put in the 'Theme Name:' header in 'style.css'.
*
* [--author=<full-name>]
* : What to put in the 'Author:' header in 'style.css'.
*
* [--author_uri=<uri>]
* : What to put in the 'Author URI:' header in 'style.css'.
*
* [--theme_uri=<uri>]
* : What to put in the 'Theme URI:' header in 'style.css'.
*
* [--activate]
* : Activate the newly created child theme.
*
* [--enable-network]
* : Enable the newly created child theme for the entire network.
*
* [--force]
* : Overwrite files that already exist.
*
* ## EXAMPLES
*
* # Generate a 'sample-theme' child theme based on TwentySixteen
* $ wp scaffold child-theme sample-theme --parent_theme=twentysixteen
* Success: Created '/var/www/example.com/public_html/wp-content/themes/sample-theme'.
*
* @subcommand child-theme
*/
public function child_theme( $args, $assoc_args ) {
$theme_slug = $args[0];
if ( in_array( $theme_slug, [ '.', '..' ], true ) ) {
WP_CLI::error( "Invalid theme slug specified. The slug cannot be '.' or '..'." );
}
$defaults = [
'theme_name' => ucfirst( $theme_slug ),
'author' => 'Me',
'author_uri' => '',
'theme_uri' => '',
];
$data = wp_parse_args( $assoc_args, $defaults );
$data['slug'] = $theme_slug;
$data['parent_theme_function_safe'] = str_replace( [ ' ', '-' ], '_', $data['parent_theme'] );
$data['description'] = ucfirst( $data['parent_theme'] ) . ' child theme.';
$theme_dir = WP_CONTENT_DIR . "/themes/{$theme_slug}";
$error_msg = $this->check_target_directory( 'theme', $theme_dir );
if ( ! empty( $error_msg ) ) {
WP_CLI::error( "Invalid theme slug specified. {$error_msg}" );
}
$theme_style_path = "{$theme_dir}/style.css";
$theme_functions_path = "{$theme_dir}/functions.php";
$this->maybe_create_themes_dir();
$files_to_create = [
$theme_style_path => self::mustache_render( 'child_theme.mustache', $data ),
$theme_functions_path => self::mustache_render( 'child_theme_functions.mustache', $data ),
"{$theme_dir}/.editorconfig" => file_get_contents( self::get_template_path( '.editorconfig' ) ),
];
$force = Utils\get_flag_value( $assoc_args, 'force' );
$files_written = $this->create_files( $files_to_create, $force );
$skip_message = 'All theme files were skipped.';
$success_message = "Created '{$theme_dir}'.";
$this->log_whether_files_written( $files_written, $skip_message, $success_message );
if ( Utils\get_flag_value( $assoc_args, 'activate' ) ) {
WP_CLI::run_command( [ 'theme', 'activate', $theme_slug ] );
} elseif ( Utils\get_flag_value( $assoc_args, 'enable-network' ) ) {
WP_CLI::run_command( [ 'theme', 'enable', $theme_slug ], [ 'network' => true ] );
}
}
private function get_output_path( $assoc_args, $subdir ) {
if ( $assoc_args['theme'] ) {
$theme = $assoc_args['theme'];
if ( is_string( $theme ) ) {
$path = get_theme_root( $theme ) . "/{$theme}";
} else {
$path = get_stylesheet_directory();
}
if ( ! is_dir( $path ) ) {
WP_CLI::error( "Can't find '{$theme}' theme." );
}
} elseif ( $assoc_args['plugin'] ) {
$plugin = $assoc_args['plugin'];
$path = WP_PLUGIN_DIR . "/{$plugin}";
if ( ! is_dir( $path ) ) {
WP_CLI::error( "Can't find '{$plugin}' plugin." );
}
} else {
return false;
}
$path .= $subdir;
return $path;
}
/**
* Generates starter code for a plugin.
*
* The following files are always generated:
*
* * `plugin-slug.php` is the main PHP plugin file.
* * `readme.txt` is the readme file for the plugin.
* * `package.json` needed by NPM holds various metadata relevant to the project. Packages: `grunt`, `grunt-wp-i18n` and `grunt-wp-readme-to-markdown`. Scripts: `start`, `readme`, `i18n`.
* * `Gruntfile.js` is the JS file containing Grunt tasks. Tasks: `i18n` containing `addtextdomain` and `makepot`, `readme` containing `wp_readme_to_markdown`.
* * `.editorconfig` is the configuration file for Editor.
* * `.gitignore` tells which files (or patterns) git should ignore.
* * `.distignore` tells which files and folders should be ignored in distribution.
*
* The following files are also included unless the `--skip-tests` is used:
*
* * `phpunit.xml.dist` is the configuration file for PHPUnit.
* * `.circleci/config.yml` is the configuration file for CircleCI. Use `--ci=<provider>` to select a different service.
* * `bin/install-wp-tests.sh` configures the WordPress test suite and a test database.
* * `tests/bootstrap.php` is the file that makes the current plugin active when running the test suite.
* * `tests/test-sample.php` is a sample file containing test cases.
* * `.phpcs.xml.dist` is a collection of PHP_CodeSniffer rules.
*
* ## OPTIONS
*
* <slug>
* : The internal name of the plugin.
*
* [--dir=<dirname>]
* : Put the new plugin in some arbitrary directory path. Plugin directory will be path plus supplied slug.
*
* [--plugin_name=<title>]
* : What to put in the 'Plugin Name:' header.
*
* [--plugin_description=<description>]
* : What to put in the 'Description:' header.
*
* [--plugin_author=<author>]
* : What to put in the 'Author:' header.
*
* [--plugin_author_uri=<url>]
* : What to put in the 'Author URI:' header.
*
* [--plugin_uri=<url>]
* : What to put in the 'Plugin URI:' header.
*
* [--skip-tests]
* : Don't generate files for unit testing.
*
* [--ci=<provider>]
* : Choose a configuration file for a continuous integration provider.
* ---
* default: circle
* options:
* - circle
* - gitlab
* - bitbucket
* - github
* ---
*
* [--activate]
* : Activate the newly generated plugin.
*
* [--activate-network]
* : Network activate the newly generated plugin.
*
* [--force]
* : Overwrite files that already exist.
*
* ## EXAMPLES
*
* $ wp scaffold plugin sample-plugin
* Success: Created plugin files.
* Success: Created test files.
*/
public function plugin( $args, $assoc_args ) {
$plugin_slug = $args[0];
$plugin_name = ucwords( str_replace( '-', ' ', $plugin_slug ) );
$plugin_package = str_replace( ' ', '_', $plugin_name );
if ( in_array( $plugin_slug, [ '.', '..' ], true ) ) {
WP_CLI::error( "Invalid plugin slug specified. The slug cannot be '.' or '..'." );
}
$defaults = [
'plugin_slug' => $plugin_slug,
'plugin_name' => $plugin_name,
'plugin_package' => $plugin_package,
'plugin_description' => 'PLUGIN DESCRIPTION HERE',
'plugin_author' => 'YOUR NAME HERE',
'plugin_author_uri' => 'YOUR SITE HERE',
'plugin_uri' => 'PLUGIN SITE HERE',
'plugin_tested_up_to' => get_bloginfo( 'version' ),
];
$data = wp_parse_args( $assoc_args, $defaults );
$data['textdomain'] = $plugin_slug;
if ( ! empty( $assoc_args['dir'] ) ) {
if ( ! is_dir( $assoc_args['dir'] ) ) {
WP_CLI::error( "Cannot create plugin in directory that doesn't exist." );
}
$plugin_dir = "{$assoc_args['dir']}/{$plugin_slug}";
} else {
$plugin_dir = WP_PLUGIN_DIR . "/{$plugin_slug}";
$this->maybe_create_plugins_dir();
$error_msg = $this->check_target_directory( 'plugin', $plugin_dir );
if ( ! empty( $error_msg ) ) {
WP_CLI::error( "Invalid plugin slug specified. {$error_msg}" );
}
}
$plugin_path = "{$plugin_dir}/{$plugin_slug}.php";
$plugin_readme_path = "{$plugin_dir}/readme.txt";
$files_to_create = [
$plugin_path => self::mustache_render( 'plugin.mustache', $data ),
$plugin_readme_path => self::mustache_render( 'plugin-readme.mustache', $data ),
"{$plugin_dir}/package.json" => self::mustache_render( 'plugin-packages.mustache', $data ),
"{$plugin_dir}/Gruntfile.js" => self::mustache_render( 'plugin-gruntfile.mustache', $data ),
"{$plugin_dir}/.gitignore" => self::mustache_render( 'plugin-gitignore.mustache', $data ),
"{$plugin_dir}/.distignore" => self::mustache_render( 'plugin-distignore.mustache', $data ),
"{$plugin_dir}/.editorconfig" => file_get_contents( self::get_template_path( '.editorconfig' ) ),
];
$force = Utils\get_flag_value( $assoc_args, 'force' );
$files_written = $this->create_files( $files_to_create, $force );
$skip_message = 'All plugin files were skipped.';
$success_message = 'Created plugin files.';
$this->log_whether_files_written( $files_written, $skip_message, $success_message );
if ( ! Utils\get_flag_value( $assoc_args, 'skip-tests' ) ) {
$command_args = [
'dir' => $plugin_dir,
'ci' => empty( $assoc_args['ci'] ) ? '' : $assoc_args['ci'],
'force' => $force,
];
WP_CLI::run_command( [ 'scaffold', 'plugin-tests', $plugin_slug ], $command_args );
}
if ( Utils\get_flag_value( $assoc_args, 'activate' ) ) {
WP_CLI::run_command( [ 'plugin', 'activate', $plugin_slug ] );
} elseif ( Utils\get_flag_value( $assoc_args, 'activate-network' ) ) {
WP_CLI::run_command( [ 'plugin', 'activate', $plugin_slug ], [ 'network' => true ] );
}
}
/**
* Generates files needed for running PHPUnit tests in a plugin.
*
* The following files are generated by default:
*
* * `phpunit.xml.dist` is the configuration file for PHPUnit.
* * `.circleci/config.yml` is the configuration file for CircleCI. Use `--ci=<provider>` to select a different service.
* * `bin/install-wp-tests.sh` configures the WordPress test suite and a test database.
* * `tests/bootstrap.php` is the file that makes the current plugin active when running the test suite.
* * `tests/test-sample.php` is a sample file containing the actual tests.
* * `.phpcs.xml.dist` is a collection of PHP_CodeSniffer rules.
*
* Learn more from the [plugin unit tests documentation](https://make.wordpress.org/cli/handbook/misc/plugin-unit-tests/).
*
* ## ENVIRONMENT
*
* The `tests/bootstrap.php` file looks for the WP_TESTS_DIR environment
* variable.
*
* ## OPTIONS
*
* [<plugin>]
* : The name of the plugin to generate test files for.
*
* [--dir=<dirname>]
* : Generate test files for a non-standard plugin path. If no plugin slug is specified, the directory name is used.
*
* [--ci=<provider>]
* : Choose a configuration file for a continuous integration provider.
* ---
* default: circle
* options:
* - circle
* - gitlab
* - bitbucket
* - github
* ---
*
* [--force]
* : Overwrite files that already exist.
*
* ## EXAMPLES
*
* # Generate unit test files for plugin 'sample-plugin'.
* $ wp scaffold plugin-tests sample-plugin
* Success: Created test files.
*
* @subcommand plugin-tests
*/
public function plugin_tests( $args, $assoc_args ) {
$this->scaffold_plugin_theme_tests( $args, $assoc_args, 'plugin' );
}
/**
* Generates files needed for running PHPUnit tests in a theme.
*
* The following files are generated by default:
*
* * `phpunit.xml.dist` is the configuration file for PHPUnit.
* * `.circleci/config.yml` is the configuration file for CircleCI. Use `--ci=<provider>` to select a different service.
* * `bin/install-wp-tests.sh` configures the WordPress test suite and a test database.
* * `tests/bootstrap.php` is the file that makes the current theme active when running the test suite.
* * `tests/test-sample.php` is a sample file containing the actual tests.
* * `.phpcs.xml.dist` is a collection of PHP_CodeSniffer rules.
*
* Learn more from the [plugin unit tests documentation](https://make.wordpress.org/cli/handbook/misc/plugin-unit-tests/).
*
* ## ENVIRONMENT
*
* The `tests/bootstrap.php` file looks for the WP_TESTS_DIR environment
* variable.
*
* ## OPTIONS
*
* [<theme>]
* : The name of the theme to generate test files for.
*
* [--dir=<dirname>]
* : Generate test files for a non-standard theme path. If no theme slug is specified, the directory name is used.
*
* [--ci=<provider>]
* : Choose a configuration file for a continuous integration provider.
* ---
* default: circle
* options:
* - circle
* - gitlab
* - bitbucket
* - github
* ---
*
* [--force]
* : Overwrite files that already exist.
*
* ## EXAMPLES
*
* # Generate unit test files for theme 'twentysixteenchild'.
* $ wp scaffold theme-tests twentysixteenchild
* Success: Created test files.
*
* @subcommand theme-tests
*/
public function theme_tests( $args, $assoc_args ) {
$this->scaffold_plugin_theme_tests( $args, $assoc_args, 'theme' );
}
private function scaffold_plugin_theme_tests( $args, $assoc_args, $type ) {
$wp_filesystem = $this->init_wp_filesystem();
if ( ! empty( $args[0] ) ) {
$slug = $args[0];
if ( in_array( $slug, [ '.', '..' ], true ) ) {
WP_CLI::error( "Invalid {$type} slug specified. The slug cannot be '.' or '..'." );
}
if ( 'theme' === $type ) {
$theme = wp_get_theme( $slug );
if ( $theme->exists() ) {
$target_dir = $theme->get_stylesheet_directory();
} else {
WP_CLI::error( "Invalid {$type} slug specified. The theme '{$slug}' does not exist." );
}
} else {
$target_dir = WP_PLUGIN_DIR . "/{$slug}";
}
if ( empty( $assoc_args['dir'] ) && ! is_dir( $target_dir ) ) {
WP_CLI::error( "Invalid {$type} slug specified. No such target directory '{$target_dir}'." );
}
$error_msg = $this->check_target_directory( $type, $target_dir );
if ( ! empty( $error_msg ) ) {
WP_CLI::error( "Invalid {$type} slug specified. {$error_msg}" );
}
}
if ( ! empty( $assoc_args['dir'] ) ) {
$target_dir = $assoc_args['dir'];
if ( ! is_dir( $target_dir ) ) {
WP_CLI::error( "Invalid {$type} directory specified. No such directory '{$target_dir}'." );
}
if ( empty( $slug ) ) {
$slug = Utils\basename( $target_dir );
}
}
if ( empty( $slug ) || empty( $target_dir ) ) {
WP_CLI::error( "Invalid {$type} specified." );
}
$name = ucwords( str_replace( '-', ' ', $slug ) );
$package = str_replace( ' ', '_', $name );
$tests_dir = "{$target_dir}/tests";
$bin_dir = "{$target_dir}/bin";
$wp_filesystem->mkdir( $tests_dir );
$wp_filesystem->mkdir( $bin_dir );
$wp_versions_to_test = [];
// Parse plugin readme.txt
if ( file_exists( "{$target_dir}/readme.txt" ) ) {
$readme_content = file_get_contents( "{$target_dir}/readme.txt" );
preg_match( '/Requires at least\:(.*)\n/m', $readme_content, $matches );
if ( isset( $matches[1] ) && $matches[1] ) {
$wp_versions_to_test[] = trim( $matches[1] );
}
}
$wp_versions_to_test[] = 'latest';
$wp_versions_to_test[] = 'trunk';
$main_file = "{$slug}.php";
if ( 'plugin' === $type ) {
if ( ! function_exists( 'get_plugins' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$all_plugins = get_plugins();
if ( ! empty( $all_plugins ) ) {
$filtered = array_filter(
array_keys( $all_plugins ),
static function ( $item ) use ( $slug ) {
return ( false !== strpos( $item, "{$slug}/" ) );
}
);
if ( ! empty( $filtered ) ) {
$main_file = basename( reset( $filtered ) );
}
}
}
$template_data = [
"{$type}_slug" => $slug,
"{$type}_package" => $package,
"{$type}_main_file" => $main_file,
];
$force = Utils\get_flag_value( $assoc_args, 'force' );
$files_to_create = [
"{$tests_dir}/bootstrap.php" => self::mustache_render( "{$type}-bootstrap.mustache", $template_data ),
"{$tests_dir}/test-sample.php" => self::mustache_render( "{$type}-test-sample.mustache", $template_data ),
];
if ( 'circle' === $assoc_args['ci'] ) {
$files_to_create[ "{$target_dir}/.circleci/config.yml" ] = self::mustache_render( 'plugin-circle.mustache', compact( 'wp_versions_to_test' ) );
} elseif ( 'gitlab' === $assoc_args['ci'] ) {
$files_to_create[ "{$target_dir}/.gitlab-ci.yml" ] = self::mustache_render( 'plugin-gitlab.mustache' );
} elseif ( 'bitbucket' === $assoc_args['ci'] ) {
$files_to_create[ "{$target_dir}/bitbucket-pipelines.yml" ] = self::mustache_render( 'plugin-bitbucket.mustache' );
} elseif ( 'github' === $assoc_args['ci'] ) {
$files_to_create[ "{$target_dir}/.github/workflows/testing.yml" ] = self::mustache_render( 'plugin-github.mustache' );
}
$files_written = $this->create_files( $files_to_create, $force );
$to_copy = [
'install-wp-tests.sh' => $bin_dir,
'phpunit.xml.dist' => $target_dir,
'.phpcs.xml.dist' => $target_dir,
];
foreach ( $to_copy as $file => $dir ) {
$file_name = "{$dir}/{$file}";
$force = Utils\get_flag_value( $assoc_args, 'force' );
$should_write_file = $this->prompt_if_files_will_be_overwritten( $file_name, $force );
if ( ! $should_write_file ) {
continue;
}
$files_written[] = $file_name;
$wp_filesystem->copy( self::get_template_path( $file ), $file_name, true );
if ( 'install-wp-tests.sh' === $file ) {
if ( ! $wp_filesystem->chmod( "{$dir}/{$file}", 0755 ) ) {
WP_CLI::warning( "Couldn't mark 'install-wp-tests.sh' as executable." );
}
}
}
$skip_message = 'All test files were skipped.';
$success_message = 'Created test files.';
$this->log_whether_files_written( $files_written, $skip_message, $success_message );
}
/**
* Checks that the `$target_dir` is a child directory of the WP themes or plugins directory, depending on `$type`.
*
* @param string $type "theme" or "plugin"
* @param string $target_dir The theme/plugin directory to check.
*
* @return null|string Returns null on success, error message on error.
*/
private function check_target_directory( $type, $target_dir ) {
$parent_dir = dirname( self::canonicalize_path( str_replace( '\\', '/', $target_dir ) ) );
if ( 'theme' === $type && str_replace( '\\', '/', WP_CONTENT_DIR . '/themes' ) !== $parent_dir ) {
return sprintf( 'The target directory \'%1$s\' is not in \'%2$s\'.', $target_dir, WP_CONTENT_DIR . '/themes' );
}
if ( 'plugin' === $type && str_replace( '\\', '/', WP_PLUGIN_DIR ) !== $parent_dir ) {
return sprintf( 'The target directory \'%1$s\' is not in \'%2$s\'.', $target_dir, WP_PLUGIN_DIR );
}
// Success.
return null;
}
protected function create_files( $files_and_contents, $force ) {
$wp_filesystem = $this->init_wp_filesystem();
$wrote_files = [];
foreach ( $files_and_contents as $filename => $contents ) {
$should_write_file = $this->prompt_if_files_will_be_overwritten( $filename, $force );
if ( ! $should_write_file ) {
continue;
}
$wp_filesystem->mkdir( dirname( $filename ) );
// Create multi-level folders.
if ( false === $wp_filesystem->exists( dirname( $filename ) ) ) {
$wp_filesystem->mkdir( dirname( dirname( $filename ) ) );
$wp_filesystem->mkdir( dirname( $filename ) );
}
if ( ! $wp_filesystem->put_contents( $filename, $contents ) ) {
WP_CLI::error( "Error creating file: {$filename}" );
} elseif ( $should_write_file ) {
$wrote_files[] = $filename;
}
}
return $wrote_files;
}
protected function prompt_if_files_will_be_overwritten( $filename, $force ) {
$should_write_file = true;
if ( ! file_exists( $filename ) ) {
return true;