From 7146824324da015e88cb84077ac68397610c9106 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Tue, 5 Jul 2022 11:56:43 +0200 Subject: [PATCH 01/52] Feature/refactor (#307) * refactoring cli commands --- bin/cli.php | 23 -- phpcs.xml.dist | 1 + phpunit.xml | 4 +- src/AdminMenus/AbstractAdminMenu.php | 41 ++- src/AdminMenus/AdminMenuCli.php | 31 +- src/AdminMenus/AdminReusableBlocksMenuCli.php | 34 +- src/AdminMenus/AdminSubMenuCli.php | 36 +- src/AnalyticsGdpr/AnalyticsGdprCli.php | 10 +- src/BlockPatterns/BlockPatternCli.php | 62 ++-- src/BlockPatterns/BlockPatternExample.php | 8 +- src/Blocks/AbstractBlocks.php | 106 ++---- src/Blocks/AbstractBlocksCli.php | 266 ++++++++------ src/Blocks/BlockVariationCli.php | 182 ---------- src/Blocks/BlockWrapperCli.php | 131 ------- src/Blocks/BlocksCli.php | 140 +------- src/Blocks/BlocksStorybookCli.php | 104 ------ src/Blocks/UseAssetsCli.php | 94 +++++ src/Blocks/{BlockCli.php => UseBlockCli.php} | 40 ++- ...ckComponentCli.php => UseComponentCli.php} | 37 +- src/Blocks/UseGlobalAssetsCli.php | 95 +++++ src/Blocks/UseManifestCli.php | 85 +++++ src/Blocks/UseStorybookCli.php | 95 +++++ src/Blocks/UseVariationCli.php | 109 ++++++ src/Blocks/UseWrapperCli.php | 91 +++++ src/Build/BuildCli.php | 35 +- src/Build/BuildExample.php | 2 +- src/CiExclude/CiExcludeCli.php | 45 +-- src/CiExclude/CiExcludeExample.php | 28 ++ src/CiExclude/ci-exclude.txt | 25 -- src/Cli/AbstractCli.php | 331 +++++++----------- src/Cli/Cli.php | 160 +++------ src/Cli/CliHelpers.php | 33 ++ src/Cli/CliInitAll.php | 91 ----- src/Cli/CliInitProject.php | 134 ------- src/Cli/CliInitTheme.php | 122 ------- src/Cli/CliReset.php | 80 ----- src/Cli/CliRunAll.php | 75 ---- src/Cli/CliShowAll.php | 95 ----- .../CliBoilerplate.php | 2 +- .../{CliSetup.php => CliInit.php} | 4 +- src/Cli/ParentGroups/CliProject.php | 24 -- src/Cli/ParentGroups/CliWebp.php | 24 -- src/Cli/README.md | 14 +- src/Columns/Media/WebPMediaColumnCli.php | 10 +- src/Config/AbstractConfigData.php | 3 +- src/Config/ConfigCli.php | 37 +- src/Config/ConfigExample.php | 6 +- src/ConfigProject/ConfigProjectCli.php | 48 ++- src/CustomMeta/AcfMetaCli.php | 22 +- src/CustomPostType/PostTypeCli.php | 87 +++-- src/CustomPostType/PostTypeExample.php | 18 +- src/CustomTaxonomy/TaxonomyCli.php | 60 ++-- src/CustomTaxonomy/TaxonomyExample.php | 14 +- src/Db/DbExport.php | 2 +- src/Db/DbImport.php | 126 ++++--- src/Db/ExportCli.php | 26 +- src/Db/ImportCli.php | 27 +- src/Enqueue/Admin/EnqueueAdminCli.php | 10 +- src/Enqueue/Blocks/EnqueueBlocksCli.php | 12 +- src/Enqueue/Theme/EnqueueThemeCli.php | 10 +- src/Geolocation/GeolocationCli.php | 30 +- src/GitIgnore/GitIgnoreCli.php | 31 +- src/Helpers/Components.php | 307 +++++++++++++--- src/Helpers/StoreTrait.php | 29 +- src/I18n/I18nCli.php | 12 +- src/Init/InitBlocksCli.php | 175 +++++++++ src/Init/InitProjectCli.php | 138 ++++++++ src/Init/InitThemeCli.php | 140 ++++++++ src/Login/LoginCli.php | 10 +- src/Main/MainCli.php | 16 +- src/Manifest/AbstractManifest.php | 4 +- src/Manifest/ManifestCli.php | 10 +- src/Media/MediaCli.php | 10 +- src/Media/RegenerateWebPMediaCli.php | 33 +- src/Media/UseWebPMediaCli.php | 6 +- src/Menu/MenuCli.php | 10 +- .../ModifyAdminAppearanceCli.php | 10 +- src/Readme/ReadmeCli.php | 31 +- src/Rest/Fields/FieldCli.php | 38 +- src/Rest/Fields/FieldExample.php | 4 +- src/Rest/Routes/LoadMore/LoadMoreRouteCli.php | 28 +- src/Rest/Routes/RouteCli.php | 37 +- src/Rest/Routes/RouteExample.php | 4 +- src/Services/ServiceExampleCli.php | 24 +- src/Setup/SetupCli.php | 47 +-- src/Setup/UpdateCli.php | 46 ++- src/ThemeOptions/ThemeOptionsCli.php | 10 +- src/View/EscapedViewCli.php | 10 +- src/WpCli/WpCli.php | 24 +- src/WpCli/WpCliExample.php | 2 +- tests/AdminMenus/AdminMenuCliTest.php | 124 +++++-- tests/AdminMenus/AdminMenuExampleTest.php | 95 +++-- .../AdminReusableBlocksMenuCliTest.php | 127 +++++-- tests/AdminMenus/AdminSubMenuCliTest.php | 122 +++++-- tests/AnalyticsGdpr/AnalyticsGdprCliTest.php | 30 +- tests/BlockPatterns/BlockPatternCliTest.php | 142 ++++---- tests/Blocks/BlockCliTest.php | 72 ++-- tests/Blocks/BlockComponentCliTest.php | 65 ++-- tests/Blocks/BlockVariationCliTest.php | 91 ++--- tests/Blocks/BlockWrapperCliTest.php | 74 +--- tests/Blocks/BlocksAssetsCliTest.php | 34 ++ tests/Blocks/BlocksCliTest.php | 57 ++- tests/Blocks/BlocksExampleTest.php | 129 +++---- tests/Blocks/BlocksGlobalAssetsCliTest.php | 34 ++ tests/Blocks/BlocksManifestCliTest.php | 34 ++ tests/Blocks/BlocksStorybookCliTest.php | 34 ++ tests/Build/BuildCliTest.php | 62 +--- tests/CiExclude/CiExcludeCliTest.php | 132 ++++--- tests/Cli/AbstractCliTest.php | 58 +-- tests/Cli/CliInitProjectTest.php | 85 ----- tests/Cli/CliInitThemeTest.php | 81 ----- tests/Cli/CliResetTest.php | 53 --- tests/Cli/CliRunAllTest.php | 59 ---- tests/Cli/CliShowAllTest.php | 66 ---- tests/Cli/CliTest.php | 53 +-- .../Columns/Media/WebPMediaColumnCliTest.php | 2 +- tests/Config/ConfigCliTest.php | 34 +- tests/Config/ConfigExampleTest.php | 45 +-- tests/ConfigProject/ConfigProjectCliTest.php | 93 ++--- tests/CustomMeta/CustomMetaCliTest.php | 33 +- .../CustomPostType/CustomPostTypeCliTest.php | 270 ++++++-------- tests/CustomTaxonomy/TaxonomyCliTest.php | 230 +++++------- tests/Db/DbExportTest.php | 40 +-- tests/Db/DbImportTest.php | 157 +++++++-- tests/Db/setup.json | 17 - tests/Enqueue/Admin/EnqueueAdminCliTest.php | 32 +- tests/Enqueue/Blocks/EnqueueBlockCliTest.php | 34 +- tests/Enqueue/Theme/EnqueueThemeCliTest.php | 32 +- tests/Geolocation/AbstractGeolocationTest.php | 38 +- tests/Geolocation/GeolocationCliTest.php | 4 +- tests/GitIgnore/GitIgnoreCliTest.php | 90 ++--- tests/Helpers.php | 113 +++++- tests/Helpers/AttributesTraitTest.php | 72 ++-- tests/Helpers/ComponentHelpersTest.php | 22 +- tests/Helpers/CssVariablesTraitTest.php | 31 +- tests/Helpers/SelectorsTraitTest.php | 24 +- tests/Helpers/StoreTraitTest.php | 20 +- tests/I18n/I18nCliTest.php | 56 ++- tests/Init/InitBlocksCliTest.php | 47 +++ tests/Init/InitProjectCliTest.php | 45 +++ tests/Init/InitThemeCliTest.php | 42 +++ tests/Login/LoginCliTest.php | 58 ++- tests/Main/AbstractMainTest.php | 26 +- tests/Main/MainCliTest.php | 60 ++-- tests/Main/MainExampleTest.php | 9 +- tests/Manifest/ManifestCliTest.php | 58 ++- tests/Media/MediaCliTest.php | 2 +- tests/Menu/MenuCliTest.php | 63 ++-- .../ModifyAdminAppearanceCliTest.php | 58 ++- tests/Readme/ReadmeCliTest.php | 92 ++--- tests/Rest/Fields/FieldCliTest.php | 76 ++-- tests/Rest/Routes/RouteCliTest.php | 76 ++-- tests/Services/ServiceExampleCliTest.php | 65 ++-- tests/Setup/SetupCliTest.php | 53 +-- tests/Setup/UpdateCliTest.php | 38 +- tests/ThemeOptions/ThemeOptionsCliTest.php | 59 ++-- tests/View/EscapedViewCliTest.php | 42 +-- tests/WpCli/WpCliExampleTest.php | 33 +- tests/WpCli/WpCliTest.php | 49 +-- tests/data/assets/assets.php | 2 + tests/data/setup/setup-empty.json | 0 tests/data/setup/setup-missing-urls.json | 3 + tests/data/setup/setup.json | 19 + tests/data/src/Blocks/assets/assets.php | 2 + tests/data/storybook/storybook.php | 2 + 165 files changed, 4527 insertions(+), 4897 deletions(-) delete mode 100755 bin/cli.php delete mode 100644 src/Blocks/BlockVariationCli.php delete mode 100644 src/Blocks/BlockWrapperCli.php delete mode 100644 src/Blocks/BlocksStorybookCli.php create mode 100644 src/Blocks/UseAssetsCli.php rename src/Blocks/{BlockCli.php => UseBlockCli.php} (70%) rename src/Blocks/{BlockComponentCli.php => UseComponentCli.php} (68%) create mode 100644 src/Blocks/UseGlobalAssetsCli.php create mode 100644 src/Blocks/UseManifestCli.php create mode 100644 src/Blocks/UseStorybookCli.php create mode 100644 src/Blocks/UseVariationCli.php create mode 100644 src/Blocks/UseWrapperCli.php create mode 100644 src/CiExclude/CiExcludeExample.php delete mode 100644 src/CiExclude/ci-exclude.txt delete mode 100644 src/Cli/CliInitAll.php delete mode 100644 src/Cli/CliInitProject.php delete mode 100644 src/Cli/CliInitTheme.php delete mode 100644 src/Cli/CliReset.php delete mode 100644 src/Cli/CliRunAll.php delete mode 100644 src/Cli/CliShowAll.php rename src/Cli/{TopLevelGroup => ParentGroups}/CliBoilerplate.php (94%) rename src/Cli/ParentGroups/{CliSetup.php => CliInit.php} (83%) delete mode 100644 src/Cli/ParentGroups/CliProject.php delete mode 100644 src/Cli/ParentGroups/CliWebp.php create mode 100644 src/Init/InitBlocksCli.php create mode 100644 src/Init/InitProjectCli.php create mode 100644 src/Init/InitThemeCli.php create mode 100644 tests/Blocks/BlocksAssetsCliTest.php create mode 100644 tests/Blocks/BlocksGlobalAssetsCliTest.php create mode 100644 tests/Blocks/BlocksManifestCliTest.php create mode 100644 tests/Blocks/BlocksStorybookCliTest.php delete mode 100644 tests/Cli/CliInitProjectTest.php delete mode 100644 tests/Cli/CliInitThemeTest.php delete mode 100644 tests/Cli/CliResetTest.php delete mode 100644 tests/Cli/CliRunAllTest.php delete mode 100644 tests/Cli/CliShowAllTest.php delete mode 100644 tests/Db/setup.json create mode 100644 tests/Init/InitBlocksCliTest.php create mode 100644 tests/Init/InitProjectCliTest.php create mode 100644 tests/Init/InitThemeCliTest.php create mode 100644 tests/data/assets/assets.php create mode 100644 tests/data/setup/setup-empty.json create mode 100644 tests/data/setup/setup-missing-urls.json create mode 100644 tests/data/setup/setup.json create mode 100644 tests/data/src/Blocks/assets/assets.php create mode 100644 tests/data/storybook/storybook.php diff --git a/bin/cli.php b/bin/cli.php deleted file mode 100755 index f7b2503d4..000000000 --- a/bin/cli.php +++ /dev/null @@ -1,23 +0,0 @@ -loadDevelop($args); -} catch (ReflectionException $e) { - // Let it go. -} catch (ExitException $e) { - exit("{$e->getCode()}: {$e->getMessage()}"); -} diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 0563871e8..d33bdd79d 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -10,6 +10,7 @@ */src/commands/templates/* */src/Build/BuildExample.php */bin/cli.php + */src/CiExclude/CiExcludeExample.php diff --git a/phpunit.xml b/phpunit.xml index ed4824318..d2f863e38 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -10,8 +10,8 @@ - - + + ./src diff --git a/src/AdminMenus/AbstractAdminMenu.php b/src/AdminMenus/AbstractAdminMenu.php index d6eeaa18c..8767fe8ff 100644 --- a/src/AdminMenus/AbstractAdminMenu.php +++ b/src/AdminMenus/AbstractAdminMenu.php @@ -29,22 +29,37 @@ abstract class AbstractAdminMenu implements ServiceInterface, RenderableBlockInt */ public function register(): void { - \add_action( - 'admin_menu', - function () { - \add_menu_page( - $this->getTitle(), - $this->getMenuTitle(), - $this->getCapability(), - $this->getMenuSlug(), - [$this, 'processAdminMenu'], - $this->getIcon(), - $this->getPosition() - ); - } + \add_action('admin_menu', [$this, 'callback'], $this->getPriorityOrder()); + } + + /** + * Return action callback method. + * + * @return void + */ + public function callback(): void + { + \add_menu_page( + $this->getTitle(), + $this->getMenuTitle(), + $this->getCapability(), + $this->getMenuSlug(), + [$this, 'processAdminMenu'], + $this->getIcon(), + $this->getPosition() ); } + /** + * Return hook priority order. + * + * @return integer + */ + public function getPriorityOrder(): int + { + return 10; + } + /** * Process the admin menu attributes and prepare rendering. * diff --git a/src/AdminMenus/AdminMenuCli.php b/src/AdminMenus/AdminMenuCli.php index 486b3e3c8..d97204aeb 100644 --- a/src/AdminMenus/AdminMenuCli.php +++ b/src/AdminMenus/AdminMenuCli.php @@ -12,19 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class AdminMenuCli */ class AdminMenuCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'AdminMenus'; - /** * Get WPCLI command parent name * @@ -45,25 +39,6 @@ public function getCommandName(): string return 'admin_menu'; } - /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. - * - * @return array - */ - public function getDevelopArgs(array $args): array - { - return [ - 'title' => 'Test Title', - 'menu_title' => 'Test Menu Title', - 'capability' => 'test_edit_posts', - 'menu_slug' => 'test_title', - 'menu_icon' => 'dashicons-admin-media', - 'menu_position' => 50, - ]; - } - /** * Define default arguments. * @@ -151,6 +126,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Arguments. $title = $this->getArg($assocArgs, 'title'); $menuTitle = $this->getArg($assocArgs, 'menu_title'); @@ -183,6 +160,6 @@ public function __invoke(array $args, array $assocArgs) } // Output final class to new file/folder and finish. - $class->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + $class->outputWrite(Components::getProjectPaths('srcDestination', 'AdminMenus'), "{$className}.php", $assocArgs); } } diff --git a/src/AdminMenus/AdminReusableBlocksMenuCli.php b/src/AdminMenus/AdminReusableBlocksMenuCli.php index 81ca9dc86..6829a7f79 100644 --- a/src/AdminMenus/AdminReusableBlocksMenuCli.php +++ b/src/AdminMenus/AdminReusableBlocksMenuCli.php @@ -12,19 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class AdminReusableBlocksMenuCli */ class AdminReusableBlocksMenuCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'AdminMenus'; - /** * Get WPCLI command parent name * @@ -45,24 +39,6 @@ public function getCommandName(): string return 'admin_reusable_blocks_menu'; } - /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. - * - * @return array - */ - public function getDevelopArgs(array $args): array - { - return [ - 'title' => 'Test Reusable Blocks', - 'menu_title' => 'Test Reusable Blocks', - 'capability' => 'test_edit_posts', - 'menu_icon' => 'dashicons-editor-generic', - 'menu_position' => 100, - ]; - } - /** * Define default arguments. * @@ -94,14 +70,14 @@ public function getDoc(): array 'name' => 'title', 'description' => 'The text to be displayed in the title tags of the page when the menu is selected.', 'optional' => true, - 'default' => 'Reusable Blocks', + 'default' => $this->getDefaultArg('title'), ], [ 'type' => 'assoc', 'name' => 'menu_title', 'description' => 'The text to be used for the menu.', 'optional' => true, - 'default' => 'Reusable Blocks', + 'default' => $this->getDefaultArg('menu_title'), ], [ 'type' => 'assoc', @@ -146,6 +122,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Arguments. $title = $this->getArg($assocArgs, 'title'); $menuTitle = $this->getArg($assocArgs, 'menu_title'); @@ -176,6 +154,6 @@ public function __invoke(array $args, array $assocArgs) } // Output final class to new file/folder and finish. - $class->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + $class->outputWrite(Components::getProjectPaths('srcDestination', 'AdminMenus'), "{$className}.php", $assocArgs); } } diff --git a/src/AdminMenus/AdminSubMenuCli.php b/src/AdminMenus/AdminSubMenuCli.php index 5708d6715..9af22fdb4 100644 --- a/src/AdminMenus/AdminSubMenuCli.php +++ b/src/AdminMenus/AdminSubMenuCli.php @@ -12,19 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class AdminSubMenuCli */ class AdminSubMenuCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'AdminMenus'; - /** * Get WPCLI command parent name * @@ -45,24 +39,6 @@ public function getCommandName(): string return 'admin_sub_menu'; } - /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. - * - * @return array - */ - public function getDevelopArgs(array $args): array - { - return [ - 'parent_slug' => 'test-example-menu-slug', - 'title' => 'Test Admin Title', - 'menu_title' => 'Test Admin Sub Menu Title', - 'capability' => 'test_edit_posts', - 'menu_slug' => 'test_admin_title', - ]; - } - /** * Define default arguments. * @@ -141,6 +117,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Arguments. $parentSlug = $this->getArg($assocArgs, 'parent_slug'); $title = $this->getArg($assocArgs, 'title'); @@ -153,7 +131,7 @@ public function __invoke(array $args, array $assocArgs) $className = $className . $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. - $class = $this->getExampleTemplate(__DIR__, $this->getClassShortName()) + $this->getExampleTemplate(__DIR__, $this->getClassShortName()) ->renameClassNameWithPrefix($this->getClassShortName(), $className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) @@ -162,9 +140,7 @@ public function __invoke(array $args, array $assocArgs) ->searchReplaceString($this->getArgTemplate('title'), $title) ->searchReplaceString($this->getArgTemplate('menu_title'), $menuTitle) ->searchReplaceString($this->getArgTemplate('capability'), $capability) - ->searchReplaceString($this->getArgTemplate('menu_slug'), $menuSlug); - - // Output final class to new file/folder and finish. - $class->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->searchReplaceString($this->getArgTemplate('menu_slug'), $menuSlug) + ->outputWrite(Components::getProjectPaths('srcDestination', 'AdminMenus'), "{$className}.php", $assocArgs); } } diff --git a/src/AnalyticsGdpr/AnalyticsGdprCli.php b/src/AnalyticsGdpr/AnalyticsGdprCli.php index 590237179..6ea855158 100644 --- a/src/AnalyticsGdpr/AnalyticsGdprCli.php +++ b/src/AnalyticsGdpr/AnalyticsGdprCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class AnalyticsGdprCli */ class AnalyticsGdprCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'AnalyticsGdpr'; - /** * Get WPCLI command parent name * @@ -77,6 +73,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) // phpcs:ignore { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); $this->getExampleTemplate(__DIR__, $className) @@ -84,6 +82,6 @@ public function __invoke(array $args, array $assocArgs) // phpcs:ignore ->renameNamespace($assocArgs) ->renameUse($assocArgs) ->renameTextDomain($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'AnalyticsGdpr'), "{$className}.php", $assocArgs); } } diff --git a/src/BlockPatterns/BlockPatternCli.php b/src/BlockPatterns/BlockPatternCli.php index a56cfb0fa..6be1d73c8 100644 --- a/src/BlockPatterns/BlockPatternCli.php +++ b/src/BlockPatterns/BlockPatternCli.php @@ -11,7 +11,7 @@ namespace EightshiftLibs\BlockPatterns; use EightshiftLibs\Cli\AbstractCli; -use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Cli\ParentGroups\CliBlocks; use EightshiftLibs\Helpers\Components; /** @@ -19,13 +19,6 @@ */ class BlockPatternCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'BlockPatterns'; - /** * Get WPCLI command parent name * @@ -33,7 +26,7 @@ class BlockPatternCli extends AbstractCli */ public function getCommandParentName(): string { - return CliCreate::COMMAND_NAME; + return CliBlocks::COMMAND_NAME; } /** @@ -43,23 +36,21 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'block_pattern'; + return 'create_block_pattern'; } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'title' => $args[1] ?? 'Something', - 'name' => $args[2] ?? 'eightshift-boilerplate/something', - 'description' => $args[3] ?? 'This is an example block pattern', - 'content' => $args[4] ?? '', + 'title' => 'example-title', + 'name' => 'example-name', + 'description' => 'example-description', + 'content' => 'example-content', ]; } @@ -84,20 +75,21 @@ public function getDoc(): array 'name' => 'name', 'description' => 'Pattern name with namespace. If not provided will be generated from title. Example: eightshift/pattern-name', 'optional' => true, + 'default' => $this->getDefaultArg('name'), ], [ 'type' => 'assoc', 'name' => 'description', 'description' => 'Description of the pattern.', 'optional' => true, - 'default' => '', + 'default' => $this->getDefaultArg('description'), ], [ 'type' => 'assoc', 'name' => 'content', 'description' => 'Content of the pattern. Needs to be the WP block markup (tho most likely you\'d add this manually after you generate the pattern)', 'optional' => true, - 'default' => 'Description of this pattern', + 'default' => $this->getDefaultArg('content'), ], ], 'longdesc' => $this->prepareLongDesc(" @@ -108,7 +100,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --title='Call to action' --menu_title='content' --capability='edit_posts' --menu_slug='es-content' + $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --title='Button' --description='This is description' --capability='edit_posts' --menu_slug='es-content' ## RESOURCES @@ -121,27 +113,31 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Props. - $title = $assocArgs['title'] ?? ''; - $name = isset($assocArgs['name']) ? $assocArgs['name'] : $this->generateName($title); - $content = $assocArgs['content'] ?? ''; - $description = isset($assocArgs['description']) ? $assocArgs['description'] : 'Description of this pattern'; + $title = $this->getArg($assocArgs, 'title'); + $name = $this->getArg($assocArgs, 'name'); + $content = $this->getArg($assocArgs, 'content'); + $description = $this->getArg($assocArgs, 'description'); + + if (!$name) { + $name = $this->generateName($title); + } $className = $this->getFileName($title); $className = $className . $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. - $class = $this->getExampleTemplate(__DIR__, $this->getClassShortName()) + $this->getExampleTemplate(__DIR__, $this->getClassShortName()) ->renameClassNameWithPrefix($this->getClassShortName(), $className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->searchReplaceString('example-name', $name) - ->searchReplaceString('example-title', $title) - ->searchReplaceString('example-description', $description) - ->searchReplaceString('example-content', $content); - - // Output final class to new file/folder and finish. - $class->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->searchReplaceString($this->getArgTemplate('title'), $title) + ->searchReplaceString($this->getArgTemplate('name'), $name) + ->searchReplaceString($this->getArgTemplate('content'), $content) + ->searchReplaceString($this->getArgTemplate('description'), $description) + ->outputWrite(Components::getProjectPaths('srcDestination', 'BlockPatterns'), "{$className}.php", $assocArgs); } /** diff --git a/src/BlockPatterns/BlockPatternExample.php b/src/BlockPatterns/BlockPatternExample.php index e43df1782..a02c6454f 100644 --- a/src/BlockPatterns/BlockPatternExample.php +++ b/src/BlockPatterns/BlockPatternExample.php @@ -45,7 +45,7 @@ protected function getKeywords(): array */ protected function getName(): string { - return 'example-name'; + return '%name%'; } /** @@ -55,7 +55,7 @@ protected function getName(): string */ protected function getTitle(): string { - return 'example-title'; + return '%title%'; } /** @@ -65,7 +65,7 @@ protected function getTitle(): string */ protected function getDescription(): string { - return 'example-description'; + return '%description%'; } /** @@ -77,6 +77,6 @@ protected function getDescription(): string */ protected function getContent(): string { - return 'example-content'; + return '%content%'; } } diff --git a/src/Blocks/AbstractBlocks.php b/src/Blocks/AbstractBlocks.php index b19bab7fa..9de1773fd 100644 --- a/src/Blocks/AbstractBlocks.php +++ b/src/Blocks/AbstractBlocks.php @@ -22,48 +22,6 @@ */ abstract class AbstractBlocks implements ServiceInterface, RenderableBlockInterface { - /** - * Relative path to blocks folder. - * - * @var string - */ - public const PATH_BLOCKS_PARENT = \DIRECTORY_SEPARATOR . 'src' . \DIRECTORY_SEPARATOR . 'Blocks' . \DIRECTORY_SEPARATOR; - - /** - * Relative path to blocks folder in test mode. - * - * @var string - */ - public const PATH_BLOCKS_PARENT_TESTS = \DIRECTORY_SEPARATOR . 'tests' . \DIRECTORY_SEPARATOR . 'data' . self::PATH_BLOCKS_PARENT; - - /** - * Relative path to custom folder. - * - * @var string - */ - public const PATH_BLOCKS = 'custom'; - - /** - * Relative path to components folder. - * - * @var string - */ - public const PATH_COMPONENTS = 'components'; - - /** - * Relative path to variations folder. - * - * @var string - */ - public const PATH_VARIATIONS = 'variations'; - - /** - * Relative path to wrapper folder. - * - * @var string - */ - public const PATH_WRAPPER = 'wrapper'; - /** * Create custom project color palette. * These colors are fetched from the main settings manifest.json. @@ -122,6 +80,7 @@ static function ($block) use ($namespace) { Components::setComponents($this->getComponentsManifests()); Components::setVariations($this->getVariationsManifests()); Components::setConfigFlags(); + Components::setPaths(); if (Components::getConfigUseWrapper()) { Components::setWrapper($this->getWrapperManifest()); @@ -232,13 +191,11 @@ public function render(array $attributes, string $innerBlockContent): string // Get block view path. $sep = \DIRECTORY_SEPARATOR; - $blockPathName = self::PATH_BLOCKS; - $templatePath = "{$this->getBlocksFolderPath()}{$blockPathName}{$sep}{$blockName}{$sep}{$blockName}.php"; + $templatePath = Components::getProjectPaths('blocksDestinationCustom', "{$blockName}{$sep}{$blockName}.php"); // Get block wrapper view path. if (Components::getConfigUseWrapper()) { - $wrapperPathName = self::PATH_WRAPPER; - $wrapperPath = "{$this->getBlocksFolderPath()}{$wrapperPathName}{$sep}wrapper.php"; + $wrapperPath = Components::getProjectPaths('blocksDestinationWrapper', 'wrapper.php'); // Check if wrapper component exists. if (!\file_exists($wrapperPath)) { @@ -397,22 +354,6 @@ private function registerBlock(array $blockDetails): void ); } - /** - * Get blocks folder absolute path. - * - * @return string - */ - private function getBlocksFolderPath(): string - { - $blocksPath = \dirname(__DIR__, 5) . self::PATH_BLOCKS_PARENT; - - if (\getenv('ES_TEST')) { - $blocksPath = \dirname(__DIR__, 2) . self::PATH_BLOCKS_PARENT_TESTS; - } - - return $blocksPath; - } - /** * Retrieve block data from manifest.json combined with some additional stuff. * @@ -423,7 +364,7 @@ private function getBlocksFolderPath(): string private function getBlocksManifests(): array { $sep = \DIRECTORY_SEPARATOR; - $pathName = self::PATH_BLOCKS; + $path = Components::getProjectPaths('blocksDestinationCustom'); return \array_map( function (string $blockPath) { @@ -449,7 +390,7 @@ function (string $blockPath) { return $block; }, - (array)\glob("{$this->getBlocksFolderPath()}{$pathName}{$sep}*{$sep}manifest.json") + (array)\glob("{$path}*{$sep}manifest.json") ); } @@ -463,7 +404,7 @@ function (string $blockPath) { private function getComponentsManifests(): array { $sep = \DIRECTORY_SEPARATOR; - $pathName = self::PATH_COMPONENTS; + $path = Components::getProjectPaths('blocksDestinationComponents'); return \array_map( function (string $componentPath) { @@ -477,7 +418,7 @@ function (string $componentPath) { return $component; }, - (array)\glob("{$this->getBlocksFolderPath()}{$pathName}{$sep}*{$sep}manifest.json") + (array)\glob("{$path}*{$sep}manifest.json") ); } @@ -491,7 +432,7 @@ function (string $componentPath) { private function getVariationsManifests(): array { $sep = \DIRECTORY_SEPARATOR; - $pathName = self::PATH_VARIATIONS; + $path = Components::getProjectPaths('blocksDestinationVariations'); return \array_map( function (string $variationPath) { @@ -505,7 +446,7 @@ function (string $variationPath) { return $variation; }, - (array)\glob("{$this->getBlocksFolderPath()}{$pathName}{$sep}*{$sep}manifest.json") + (array)\glob("{$path}*{$sep}manifest.json") ); } @@ -518,18 +459,16 @@ function (string $variationPath) { */ private function getWrapperManifest(): array { - $sep = \DIRECTORY_SEPARATOR; - $pathName = self::PATH_WRAPPER; - $manifestPath = "{$this->getBlocksFolderPath()}{$pathName}{$sep}manifest.json"; + $path = Components::getProjectPaths('blocksDestinationWrapper', "manifest.json"); - if (!\file_exists($manifestPath)) { - throw InvalidBlock::missingWrapperManifestException($manifestPath); + if (!\file_exists($path)) { + throw InvalidBlock::missingWrapperManifestException($path); } - $wrapper = \implode(' ', (array)\file($manifestPath)); - $wrapper = Components::parseManifest($wrapper); + $manifest = \implode(' ', (array)\file($path)); + $manifest = Components::parseManifest($manifest); - return $wrapper; + return $manifest; } /** @@ -542,21 +481,20 @@ private function getWrapperManifest(): array */ private function getSettingsManifest(): array { - $sep = \DIRECTORY_SEPARATOR; - $manifestPath = "{$this->getBlocksFolderPath()}{$sep}manifest.json"; + $path = Components::getProjectPaths('blocksDestination', 'manifest.json'); - if (!\file_exists($manifestPath)) { - throw InvalidBlock::missingSettingsManifestException($manifestPath); + if (!\file_exists($path)) { + throw InvalidBlock::missingSettingsManifestException($path); } - $settings = \implode(' ', (array)\file(($manifestPath))); - $settings = Components::parseManifest($settings); + $manifest = \implode(' ', (array)\file(($path))); + $manifest = Components::parseManifest($manifest); - if (!isset($settings['namespace'])) { + if (!isset($manifest['namespace'])) { throw InvalidBlock::missingNamespaceException(); } - return $settings; + return $manifest; } /** diff --git a/src/Blocks/AbstractBlocksCli.php b/src/Blocks/AbstractBlocksCli.php index 20baeb354..8696c96fa 100644 --- a/src/Blocks/AbstractBlocksCli.php +++ b/src/Blocks/AbstractBlocksCli.php @@ -11,6 +11,7 @@ namespace EightshiftLibs\Blocks; use EightshiftLibs\Cli\AbstractCli; +use EightshiftLibs\Helpers\Components; use WP_CLI; /** @@ -19,152 +20,205 @@ abstract class AbstractBlocksCli extends AbstractCli { /** - * Move block/component to project folder. + * Move items for the block editor to project folder. * - * @param array $assocArgs Array of arguments from WP-CLI command. - * @param string $outputDir Output dir path. - * @param bool $isComponents Is output used for components. + * @param array $args Array of arguments from WP-CLI command. + * @param string $source Source path. + * @param string $destination Destination path. + * @param string $type Type of items used for output log. + * @param bool $isSingleFolder Is single folder item. * * @return void */ - protected function blocksMove(array $assocArgs, string $outputDir, bool $isComponents = false): void + protected function moveItems(array $args, string $source, string $destination, string $type, bool $isSingleFolder = false): void { + $sep = \DIRECTORY_SEPARATOR; + // Get Props. - $name = $assocArgs['name'] ?? ''; + $skipExisting = $this->getSkipExisting($args); - // Set optional arguments. - $skipExisting = $this->getSkipExisting($assocArgs); + // Clean up name. + $name = $args['name'] ?? ''; + $name = \str_replace(' ', '', $name); + $name = \trim($name, \DIRECTORY_SEPARATOR); - $root = $this->getProjectRootPath(); - $rootNode = $this->getFrontendLibsBlockPath(); + $isFile = \strpos($name, '.') !== false; - $ds = \DIRECTORY_SEPARATOR; - $sourcePathFolder = "{$rootNode}{$ds}{$outputDir}{$ds}"; + $itemsList = [$name]; - $blocks = \scandir($sourcePathFolder); - $blocksFullList = \array_diff((array)$blocks, ['..', '.']); + if (\strpos($name, ',') !== false || \strpos($name, ', ') !== false) { + $itemsList = \explode(',', $name); + } - $blocks = [$name]; + if (!\is_dir($source)) { + self::cliError( + \sprintf( + // translators: %s will be replaced with type of item, and shorten cli path. + "%s files doesn't exist on this path: `%s`. Please check if you have eightshift-frontend-libs instaled.", + $type, + $this->getShortenCliPathOutput($source) + ) + ); + } - // If you pass a name "all" it will move all blocks/components to the project. - if ($name === 'all') { - $skipExisting = true; - $blocks = $blocksFullList; + $sourceItems = \array_diff(\scandir($source), ['..', '.']); + $sourceItems = \array_values($sourceItems); + + if ($isSingleFolder || $isFile) { + $sourceItems = [ + $name, + ]; } - // Iterate blocks/components. - foreach ($blocks as $block) { - $path = "{$outputDir}{$ds}{$block}"; - $sourcePath = "{$sourcePathFolder}{$block}"; + if (!$sourceItems) { + self::cliError( + \sprintf( + // translators: %s will be replaced with type of item, and shorten cli path. + "%s files doesn't exist on this path: `%s`. Please check if you have eightshift-frontend-libs instaled.", + $type, + $this->getShortenCliPathOutput($source) + ) + ); + } - if (!\getenv('ES_TEST')) { - $destinationPath = "{$root}{$ds}{$path}"; - } else { - $destinationPath = "{$this->getProjectRootPath(true)}{$ds}cliOutput"; + foreach ($itemsList as $item) { + if (!\in_array($item, $sourceItems, true)) { + self::cliError( + \sprintf( + // translators: %s will be replaced with type of item, item name and shorten cli path. + "Requested %s with the name `%s` doesn't exist in our library please review you search.\nYou can find all available items on this list: \n\n%s\n\nOr find them on this link: https://infinum.github.io/eightshift-docs/storybook/", + $type, + $item, + \implode(\PHP_EOL, $sourceItems) + ) + ); } - $typePlural = !$isComponents ? 'blocks' : 'components'; - $typeSingular = !$isComponents ? 'block' : 'component'; + $fullSource = Components::joinPaths([$source, $item]); + $fullDestination = Components::joinPaths([$destination, $item]); - // Source doesn't exist. - if (!\file_exists($sourcePath)) { - // Make a list for output. - $blocksList = \implode(\PHP_EOL, $blocksFullList); + if ($isSingleFolder) { + $fullSource = $source; + $fullDestination = $destination; + } - WP_CLI::log( - "Please check the docs for all available {$typePlural}." - ); - WP_CLI::log( - "You can find all available {$typePlural} on this link: https://infinum.github.io/eightshift-docs/storybook/." + if (\file_exists($fullDestination) && $skipExisting === false && !$isSingleFolder) { + self::cliError( + \sprintf( + // translators: %s will be replaced with type of item, and shorten cli path. + "%s files exist on this path: `%s`. If you want to override the destination folder plase use --skip_existing='true' argument.", + $type, + $this->getShortenCliPathOutput($fullDestination) + ) ); - WP_CLI::log( - "Or here is the list of all available {$typeSingular} names: \n{$blocksList}" + } + + // Move item to project folder. + if ($isFile) { + $this->copyItem($fullSource, $fullDestination); + } else { + $this->copyRecursively($fullSource, $fullDestination); + } + + $partialsOutput = []; + $partialsPath = Components::joinPaths([$fullDestination, 'partials']); + + // Check if we have partials folder. If so output and that folder with items in it. + if (\is_dir($partialsPath)) { + $partials = \array_diff(\scandir($partialsPath), ['..', '.']); + $partials = \array_values($partials); + + $partialsOutput = \array_map( + static function ($item) use ($sep) { + return "partials{$sep}{$item}"; + }, + $partials ); + } - self::cliError("The {$typeSingular} '{$sourcePath}' doesn\'t exist in our library."); + $innerItems = \array_merge( + $this->getFullBlocksFiles($name), + $partialsOutput + ); + + foreach ($innerItems as $innerItem) { + // Set output file path. + $class = $this->getExampleTemplate($fullDestination, $innerItem, true); + + if (!empty($class->fileContents)) { + $class->renameProjectName($args) + ->renameNamespace($args) + ->renameTextDomainFrontendLibs($args) + ->renameUseFrontendLibs($args) + ->outputWrite($fullDestination, $innerItem, [ + 'skip_existing' => true, + 'groupOutput' => true, + ]); + } } - // Destination exists. - if (\file_exists($destinationPath) && $skipExisting === false) { - self::cliError( + if ($type === 'component' || $type === 'block') { + WP_CLI::success( \sprintf( - 'The %s in you project exists on this "%s" path. Please check or remove that folder before running this command again.', - $typeSingular, - $destinationPath, + // translators: %s will be replaced with type of item, item name and shorten cli path. + "Added %s `%s` at `%s`.", + $type, + $item, + $this->getShortenCliPathOutput($destination) ) ); - } - // Move all files from library to project. - $this->moveBlock($destinationPath, $sourcePath, $block, $assocArgs, $path, $typeSingular); - } + $checkDependency = $args['checkDependency'] ?? true; - WP_CLI::success('Please start `npm start` again to make sure everything works correctly.'); + if ($checkDependency) { + $this->outputDependencyItems($fullSource, $type); + } + } else { + WP_CLI::success( + \sprintf( + // translators: %s will be replaced with type of item, and shorten cli path. + "`%s` created at `%s`.", + $type, + $this->getShortenCliPathOutput($destination) + ) + ); + } + } } /** - * Move block/component from frontend libs to project. + * Determin if item has dependencies and output helper commands. * - * @param string $destinationPath Path where to move. - * @param string $sourcePath Path of the block/component. - * @param string $name Name of block/component. - * @param array $assocArgs WP-CLI command arguments. - * @param string $path Path to write. - * @param string $typeSingular If block or component output string. + * @param string $source Source or the item. + * @param string $type Type for log. * * @return void */ - private function moveBlock(string $destinationPath, string $sourcePath, string $name, array $assocArgs, string $path, string $typeSingular): void + private function outputDependencyItems(string $source, string $type): void { - $ds = \DIRECTORY_SEPARATOR; - - // Create folder in project if missing. - if (!\is_dir("{$destinationPath}{$ds}")) { - \mkdir("{$destinationPath}{$ds}"); - } - - // Move block/component to project folder. - $this->copyRecursively($sourcePath, "{$destinationPath}{$ds}"); - - $typeSingular = \ucfirst($typeSingular); - - WP_CLI::success("{$typeSingular} successfully moved to your project."); - - WP_CLI::log('--------------------------------------------------'); - - $partialsOutput = []; - - // Check if we have partials folder. If so output and that folder with items in it. - if (\is_dir("{$destinationPath}/partials")) { - $partials = \array_diff(\scandir("{$destinationPath}/partials"), ['..', '.']); - - $partialsOutput = \array_map( + $manifest = Components::getManifestDirect($source); + + $dependencies = $manifest['components'] ?? []; + + if ($dependencies) { + $this->cliLog(''); + $this->cliLog('Note:', 'B'); + $this->cliLog( + \sprintf( + // translators: %s will be replaced with type of item. + \esc_html__("We have found that this %s has dependencies, please run this commands also if you don't have it in your project:", 'eightshift-libs'), + $type + ) + ); + $componentsCommandName = UseComponentCli::COMMAND_NAME; + $allDependencies = \array_map( static function ($item) { - return "partials/{$item}"; + return Components::camelToKebabCase($item); }, - $partials + $dependencies ); + $allDependencies = \implode(', ', $dependencies); + $this->cliLog("wp boilerplate {$this->getCommandParentName()} {$componentsCommandName} --name='{$allDependencies}'", 'C'); } - - $items = \array_merge( - $this->getFullBlocksFiles($name), - $partialsOutput - ); - - // Move all files from library to project. - foreach ($items as $file) { - // Set output file path. - $class = $this->getExampleTemplate($destinationPath, $file, true); - - if (!empty($class->fileContents)) { - $class->renameProjectName($assocArgs) - ->renameNamespace($assocArgs) - ->renameTextDomainFrontendLibs($assocArgs) - ->renameUseFrontendLibs($assocArgs) - ->outputWrite($path, $file, ['skip_existing' => true]); - } - } - - WP_CLI::log('--------------------------------------------------'); } } diff --git a/src/Blocks/BlockVariationCli.php b/src/Blocks/BlockVariationCli.php deleted file mode 100644 index 3e0a504cc..000000000 --- a/src/Blocks/BlockVariationCli.php +++ /dev/null @@ -1,182 +0,0 @@ - - */ - public function getDevelopArgs(array $args): array - { - return [ - 'name' => $args[1] ?? 'button', - ]; - } - - /** - * Get WPCLI command doc - * - * @return array>|string> - */ - public function getDoc(): array - { - return [ - 'shortdesc' => 'Copy variation from our library to your project.', - 'synopsis' => [ - [ - 'type' => 'assoc', - 'name' => 'name', - 'description' => 'Specify variation name.', - 'optional' => false, - ], - ], - 'longdesc' => $this->prepareLongDesc(" - ## USAGE - - Used to copy pre-created variation from our library to your project. After copying you can modify the variation in any way you see fit. - - ## EXAMPLES - - # Copy variation by name. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --name='button-block' - - ## RESOURCES - - All our variations can be found here: - https://github.com/infinum/eightshift-frontend-libs/tree/develop/blocks/init/src/Blocks/variations - "), - ]; - } - - /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) - { - // Get Props. - $name = $assocArgs['name'] ?? ''; - - // Set optional arguments. - $skipExisting = $this->getSkipExisting($assocArgs); - - $root = $this->getProjectRootPath(); - $rootNode = $this->getFrontendLibsBlockPath(); - $ds = \DIRECTORY_SEPARATOR; - - $path = static::OUTPUT_DIR . $ds . $name; - $sourcePathFolder = $rootNode . $ds . static::OUTPUT_DIR . $ds; - $sourcePath = "{$sourcePathFolder}{$name}"; - - if (!\getenv('ES_TEST')) { - $destinationPath = $root . $ds . $path; - } else { - $destinationPath = $this->getProjectRootPath(true) . '/cliOutput'; - } - - // Source doesn't exist. - if (!\file_exists($sourcePath)) { - $nameList = ''; - $filesList = \scandir($sourcePathFolder); - - if (!$filesList) { - self::cliError("The folder in the '{$sourcePath}' seems to be empty."); - } - - foreach (\array_diff((array)$filesList, ['..', '.']) as $item) { - $nameList .= "- {$item} \n"; - } - - WP_CLI::log( - "Please check the docs for all available variations." - ); - WP_CLI::log( - "You can find all available variations on this link: https://infinum.github.io/eightshift-docs/storybook/." - ); - WP_CLI::log( - "Or here is the list of all available variation names: \n{$nameList}" - ); - - self::cliError("The variation '{$sourcePath}' doesn\'t exist in our library."); - } - - // Destination exists. - if (\file_exists($destinationPath) && $skipExisting === false) { - self::cliError( - /* translators: %s will be replaced with the path. */ - \sprintf( - 'The variation in you project exists on this "%s" path. Please check or remove that folder before running this command again.', - $destinationPath - ) - ); - } - - // Move block/component to project folder. - $this->copyRecursively($sourcePath, $destinationPath); - - WP_CLI::success('Variation successfully moved to your project.'); - - WP_CLI::log('--------------------------------------------------'); - - foreach ($this->getFullBlocksFiles($name) as $file) { - // Set output file path. - $class = $this->getExampleTemplate($destinationPath, $file, true); - - if (!empty($class->fileContents)) { - $class->renameProjectName($assocArgs) - ->renameNamespace($assocArgs) - ->renameTextDomainFrontendLibs($assocArgs) - ->renameUseFrontendLibs($assocArgs) - ->outputWrite($path, $file, ['skip_existing' => true]); - } - } - - WP_CLI::log('--------------------------------------------------'); - - WP_CLI::success('Please start `npm start` again to make sure everything works correctly.'); - } -} diff --git a/src/Blocks/BlockWrapperCli.php b/src/Blocks/BlockWrapperCli.php deleted file mode 100644 index 38caa7baf..000000000 --- a/src/Blocks/BlockWrapperCli.php +++ /dev/null @@ -1,131 +0,0 @@ ->|string> - */ - public function getDoc(): array - { - return [ - 'shortdesc' => 'Copy wrapper from our library to your project.', - 'longdesc' => " - ## EXAMPLES - - # Copy wrapper. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} - - ## RESOURCES - - Our wrapper can be found here: - https://github.com/infinum/eightshift-frontend-libs/tree/develop/blocks/init/src/Blocks/wrapper - " - ]; - } - - /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) - { - // Get Props. - $name = 'wrapper'; - - // Set optional arguments. - $skipExisting = $this->getSkipExisting($assocArgs); - - $root = $this->getProjectRootPath(); - $rootNode = $this->getFrontendLibsBlockPath(); - - $ds = \DIRECTORY_SEPARATOR; - - $path = static::OUTPUT_DIR; - $sourcePathFolder = $rootNode . $ds . static::OUTPUT_DIR . $ds; - $sourcePath = "{$sourcePathFolder}"; - - if (!\getenv('ES_TEST')) { - $destinationPath = $root . $ds . $path; - } else { - $destinationPath = $this->getProjectRootPath(true) . '/cliOutput'; - } - - // Destination exists. - if (\file_exists($destinationPath) && $skipExisting === false) { - self::cliError( - \sprintf( // phpcs:ignore Eightshift.Commenting.FunctionComment.WrongStyle - 'The wrapper exists in your project on this "%s" path. Please check or remove that folder before running this command again.', - $destinationPath - ) - ); - } else { - \mkdir("{$destinationPath}/"); - } - - $this->copyRecursively($sourcePath, "{$destinationPath}/"); - - WP_CLI::success('Wrapper successfully moved to your project.'); - - WP_CLI::log('--------------------------------------------------'); - - foreach ($this->getFullBlocksFiles($name) as $file) { - // Set output file path. - $class = $this->getExampleTemplate($destinationPath, $file, true); - - if (!empty($class->fileContents)) { - $class->renameProjectName($assocArgs) - ->renameNamespace($assocArgs) - ->renameTextDomainFrontendLibs($assocArgs) - ->renameUseFrontendLibs($assocArgs) - ->outputWrite($path, $file, ['skip_existing' => true]); - } - } - - WP_CLI::log('--------------------------------------------------'); - - WP_CLI::success('Please start `npm start` again to make sure everything works correctly.'); - } -} diff --git a/src/Blocks/BlocksCli.php b/src/Blocks/BlocksCli.php index 72293cd1b..7f0c618ce 100644 --- a/src/Blocks/BlocksCli.php +++ b/src/Blocks/BlocksCli.php @@ -11,72 +11,14 @@ namespace EightshiftLibs\Blocks; use EightshiftLibs\Cli\AbstractCli; -use EightshiftLibs\Cli\ParentGroups\CliCreate; use EightshiftLibs\Cli\ParentGroups\CliBlocks; -use WP_CLI; +use EightshiftLibs\Helpers\Components; /** * Class BlocksCli */ class BlocksCli extends AbstractCli { - /** - * Toggle to see if this is running inside tests or not - * - * @var bool - */ - private $isTest; - - /** - * Output dir relative path - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Blocks'; - - /** - * List of components only used in the project init. - * All components are read from the disc path. - * - * @var string[] - */ - public const COMPONENTS = [ - 'button', - 'card', - 'copyright', - 'drawer', - 'footer', - 'hamburger', - 'head', - 'header', - 'heading', - 'icon', - 'image', - 'layout-three-columns', - 'lists', - 'logo', - 'menu', - 'paragraph', - 'tracking-before-body-end', - 'tracking-head', - ]; - - /** - * List of blocks only used in the project init. - * All blocks are read from the disc path. - * - * @var string[] - */ - public const BLOCKS = [ - 'button', - 'card', - 'group', - 'heading', - 'image', - 'lists', - 'paragraph', - ]; - /** * Get WPCLI command parent name * @@ -84,7 +26,7 @@ class BlocksCli extends AbstractCli */ public function getCommandParentName(): string { - return CliCreate::COMMAND_NAME; + return CliBlocks::COMMAND_NAME; } /** @@ -94,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'blocks'; + return 'create_blocks_class'; } /** @@ -119,79 +61,17 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); + $class = $this->getExampleTemplate(__DIR__, $className); + // Read the template contents, and replace the placeholders with provided variables. - $class = $this->getExampleTemplate(__DIR__, $className) - ->renameClassName($className) + $class->renameClassName($className) ->renameNamespace($assocArgs) ->renameTextDomainFrontendLibs($assocArgs) - ->renameUse($assocArgs); - - if (! \defined('ES_DEVELOP_MODE')) { - if (!$this->isTest && \function_exists('\add_action')) { - $this->blocksInit($assocArgs); - } - } - - // Output final class to new file/folder and finish. - $class->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); - } - - /** - * Copy blocks from Eightshift-frontend-libs to project - * - * @param string[] $args Arguments array. - * - * @return void - */ - private function blocksInit(array $args): void - { - $root = $this->getProjectRootPath(); - $rootNode = $this->getFrontendLibsBlockPath(); - - $folders = [ - 'assetsGlobal' => "{$root}/assets", - 'blocks' => "{$root}/src/Blocks", - 'assets' => "{$root}/src/Blocks/assets", - 'components' => "{$root}/src/Blocks/components", - 'custom' => "{$root}/src/Blocks/custom", - 'variations' => "{$root}/src/Blocks/variations", - ]; - - foreach ($folders as $folder) { - if (!\file_exists($folder)) { - \mkdir($folder); - } - } - - $this->copyRecursively("{$rootNode}/assets/", "{$folders['assetsGlobal']}/"); - $this->copyRecursively("{$rootNode}/src/Blocks/assets/", "{$folders['assets']}/"); - $this->copyRecursively("{$rootNode}/src/Blocks/variations/", "{$folders['variations']}/"); - \copy("{$rootNode}/src/Blocks/manifest.json", "{$folders['blocks']}/manifest.json"); - - $commandParentName = CliBlocks::COMMAND_NAME; - - WP_CLI::runcommand("{$this->commandParentName} {$commandParentName} wrapper {$this->prepareArgsManual($args)}"); - - foreach (static::COMPONENTS as $component) { - WP_CLI::runcommand("{$this->commandParentName} {$commandParentName} component --name={$component} {$this->prepareArgsManual($args)}"); - } - - foreach (static::BLOCKS as $block) { - WP_CLI::runcommand("{$this->commandParentName} {$commandParentName} block --name={$block} {$this->prepareArgsManual($args)}"); - } - - WP_CLI::success('Blocks successfully set.'); - } - - /** - * Used when running tests. - * - * @return void - */ - public function setTest(): void - { - $this->isTest = true; + ->renameUse($assocArgs) + ->outputWrite(Components::getProjectPaths('blocksDestination'), "{$className}.php", $assocArgs); } } diff --git a/src/Blocks/BlocksStorybookCli.php b/src/Blocks/BlocksStorybookCli.php deleted file mode 100644 index 0b3d5534b..000000000 --- a/src/Blocks/BlocksStorybookCli.php +++ /dev/null @@ -1,104 +0,0 @@ ->|string> - */ - public function getDoc(): array - { - return [ - 'shortdesc' => 'Setup storybook in your project.', - 'longdesc' => $this->prepareLongDesc(" - ## USAGE - - Used to copy all configuration files to your project needed to run Storybook. - - ## EXAMPLES - - # Create Storybook config: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} - - ## RESOURCES - - Storybook config will be created from this folder: - https://github.com/infinum/eightshift-frontend-libs/tree/develop/blocks/init/storybook - "), - ]; - } - - /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) - { - if (\function_exists('\add_action')) { - $root = $this->getProjectRootPath(); - $rootNode = $this->getFrontendLibsBlockPath(); - - $folder = "{$root}/.storybook"; - - if (!\file_exists($folder)) { - \mkdir($folder); - } - - $this->copyRecursively("{$rootNode}/storybook/", "{$folder}/"); - - WP_CLI::success('Storybook config successfully set.'); - - WP_CLI::log('--------------------------------------------------'); - - WP_CLI::log((string)shell_exec('npm install @eightshift/storybook --save-dev --legacy-peer-deps')); // phpcs:ignore - - WP_CLI::success('Storybook package successfully installed.'); - - WP_CLI::log('--------------------------------------------------'); - - WP_CLI::success('Storybook successfully set.'); - WP_CLI::log('Please open you package.json and add this commands in your scripts:'); - WP_CLI::log('"storybookBuild": "build-storybook -s public -o storybook"'); - WP_CLI::log('"storybook": "start-storybook -s public"'); - - WP_CLI::log('--------------------------------------------------'); - - WP_CLI::success('To start storybook please run this command `npm run storybook`.'); - } - } -} diff --git a/src/Blocks/UseAssetsCli.php b/src/Blocks/UseAssetsCli.php new file mode 100644 index 000000000..e863386b5 --- /dev/null +++ b/src/Blocks/UseAssetsCli.php @@ -0,0 +1,94 @@ +>|string> + */ + public function getDoc(): array + { + return [ + 'shortdesc' => 'Copy assets from our library to your project.', + 'longdesc' => $this->prepareLongDesc(" + ## USAGE + + Used to copy pre-created assets from our library to your project. After copying you can modify it in any way you see fit. + + ## EXAMPLES + + # Copy assets. + $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + + ## RESOURCES + + Assets will be created from this folder: + https://github.com/infinum/eightshift-frontend-libs/tree/develop/blocks/init/src/Blocks/assets + "), + ]; + } + + /* @phpstan-ignore-next-line */ + public function __invoke(array $args, array $assocArgs) // phpcs:ignore + { + $this->getIntroText($assocArgs); + + $groupOutput = $assocArgs['groupOutput'] ?? false; + + $this->moveItems( + \array_merge( + $assocArgs, + [ + 'name' => 'assets', + ], + ), + Components::getProjectPaths('blocksAssetsSource'), + Components::getProjectPaths('blocksAssetsDestination'), + 'assets', + true + ); + + if (!$groupOutput) { + WP_CLI::log('--------------------------------------------------'); + $this->cliLog('Please run `npm start` again to make sure everything works correctly.', "M"); + } + } +} diff --git a/src/Blocks/BlockCli.php b/src/Blocks/UseBlockCli.php similarity index 70% rename from src/Blocks/BlockCli.php rename to src/Blocks/UseBlockCli.php index ef5d0eca7..6aea2058e 100644 --- a/src/Blocks/BlockCli.php +++ b/src/Blocks/UseBlockCli.php @@ -11,19 +11,14 @@ namespace EightshiftLibs\Blocks; use EightshiftLibs\Cli\ParentGroups\CliBlocks; +use EightshiftLibs\Helpers\Components; +use WP_CLI; /** - * Class BlockCli + * Class UseBlockCli */ -class BlockCli extends AbstractBlocksCli +class UseBlockCli extends AbstractBlocksCli { - /** - * Output dir relative path - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Blocks' . \DIRECTORY_SEPARATOR . 'custom'; - /** * Get WPCLI command parent name * @@ -41,20 +36,18 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'block'; + return 'use_block'; } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'name' => $args[1] ?? 'button', + 'name' => 'button', ]; } @@ -96,6 +89,21 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) // phpcs:ignore Eightshift.Commenting.FunctionComment.WrongStyle { - $this->blocksMove($assocArgs, static::OUTPUT_DIR); + $this->getIntroText($assocArgs); + + $groupOutput = $assocArgs['groupOutput'] ?? false; + + $this->moveItems( + $assocArgs, + Components::getProjectPaths('blocksSourceCustom'), + Components::getProjectPaths('blocksDestinationCustom'), + 'block' + ); + + if (!$groupOutput) { + WP_CLI::log('--------------------------------------------------'); + + $this->cliLog('Please run `npm start` again to make sure everything works correctly.', "M"); + } } } diff --git a/src/Blocks/BlockComponentCli.php b/src/Blocks/UseComponentCli.php similarity index 68% rename from src/Blocks/BlockComponentCli.php rename to src/Blocks/UseComponentCli.php index 5d627699f..d3c017d2e 100644 --- a/src/Blocks/BlockComponentCli.php +++ b/src/Blocks/UseComponentCli.php @@ -11,18 +11,20 @@ namespace EightshiftLibs\Blocks; use EightshiftLibs\Cli\ParentGroups\CliBlocks; +use EightshiftLibs\Helpers\Components; +use WP_CLI; /** - * Class BlockComponentCli + * Class UseComponentCli */ -class BlockComponentCli extends AbstractBlocksCli +class UseComponentCli extends AbstractBlocksCli { /** - * Output dir relative path + * Command name. * * @var string */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Blocks' . \DIRECTORY_SEPARATOR . 'components'; + public const COMMAND_NAME = 'use_component'; /** * Get WPCLI command parent name @@ -41,20 +43,18 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'component'; + return self::COMMAND_NAME; } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'name' => $args[1] ?? 'button', + 'name' => 'button', ]; } @@ -96,6 +96,21 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) // phpcs:ignore Eightshift.Commenting.FunctionComment.WrongStyle { - $this->blocksMove($assocArgs, static::OUTPUT_DIR, true); + $this->getIntroText($assocArgs); + + $groupOutput = $assocArgs['groupOutput'] ?? false; + + $this->moveItems( + $assocArgs, + Components::getProjectPaths('blocksSourceComponents'), + Components::getProjectPaths('blocksDestinationComponents'), + 'component' + ); + + if (!$groupOutput) { + WP_CLI::log('--------------------------------------------------'); + + $this->cliLog('Please run `npm start` again to make sure everything works correctly.', "M"); + } } } diff --git a/src/Blocks/UseGlobalAssetsCli.php b/src/Blocks/UseGlobalAssetsCli.php new file mode 100644 index 000000000..3c03f18f3 --- /dev/null +++ b/src/Blocks/UseGlobalAssetsCli.php @@ -0,0 +1,95 @@ +>|string> + */ + public function getDoc(): array + { + return [ + 'shortdesc' => 'Copy global assets from our library to your project.', + 'longdesc' => $this->prepareLongDesc(" + ## USAGE + + Used to copy pre-created global assets from our library to your project. After copying you can modify it in any way you see fit. + + ## EXAMPLES + + # Copy global assets. + $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + + ## RESOURCES + + Global assets will be created from this folder: + https://github.com/infinum/eightshift-frontend-libs/tree/develop/blocks/init/assets + "), + ]; + } + + /* @phpstan-ignore-next-line */ + public function __invoke(array $args, array $assocArgs) // phpcs:ignore + { + $this->getIntroText($assocArgs); + + $groupOutput = $assocArgs['groupOutput'] ?? false; + + $this->moveItems( + \array_merge( + $assocArgs, + [ + 'name' => 'assets', + ], + ), + Components::getProjectPaths('blocksGlobalAssetsSource'), + Components::getProjectPaths('blocksGlobalAssetsDestination'), + 'assets', + true + ); + + if (!$groupOutput) { + WP_CLI::log('--------------------------------------------------'); + + $this->cliLog('Please run `npm start` again to make sure everything works correctly.', "M"); + } + } +} diff --git a/src/Blocks/UseManifestCli.php b/src/Blocks/UseManifestCli.php new file mode 100644 index 000000000..d826064c0 --- /dev/null +++ b/src/Blocks/UseManifestCli.php @@ -0,0 +1,85 @@ +>|string> + */ + public function getDoc(): array + { + return [ + 'shortdesc' => 'Create blocks manifest.json file.', + 'longdesc' => " + This file is a block editor main setting file where you can find color, option and much more. + + ## EXAMPLES + $ wp boilerplate create manifest + ", + ]; + } + + /* @phpstan-ignore-next-line */ + public function __invoke(array $args, array $assocArgs) // phpcs:ignore + { + $this->getIntroText($assocArgs); + + $groupOutput = $assocArgs['groupOutput'] ?? false; + + $this->moveItems( + \array_merge( + $assocArgs, + [ + 'name' => 'manifest.json', + ], + ), + Components::getProjectPaths('blocksSource'), + Components::getProjectPaths('blocksDestination'), + 'manifest.json' + ); + + if (!$groupOutput) { + WP_CLI::log('--------------------------------------------------'); + + $this->cliLog('Please run `npm start` again to make sure everything works correctly.', "M"); + } + } +} diff --git a/src/Blocks/UseStorybookCli.php b/src/Blocks/UseStorybookCli.php new file mode 100644 index 000000000..9933cdea0 --- /dev/null +++ b/src/Blocks/UseStorybookCli.php @@ -0,0 +1,95 @@ +>|string> + */ + public function getDoc(): array + { + return [ + 'shortdesc' => 'Setup storybook in your project.', + 'longdesc' => $this->prepareLongDesc(" + ## USAGE + + Used to copy all configuration files to your project needed to run Storybook. + + ## EXAMPLES + + # Create Storybook config: + $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + + ## RESOURCES + + Storybook config will be created from this folder: + https://github.com/infinum/eightshift-frontend-libs/tree/develop/blocks/init/storybook + "), + ]; + } + + /* @phpstan-ignore-next-line */ + public function __invoke(array $args, array $assocArgs) // phpcs:ignore + { + $this->getIntroText($assocArgs); + + $groupOutput = $assocArgs['groupOutput'] ?? false; + + $this->moveItems( + \array_merge( + $assocArgs, + [ + 'name' => 'storybook', + ], + ), + Components::getProjectPaths('blocksStorybookSource'), + Components::getProjectPaths('blocksStorybookDestination'), + 'storybook', + true + ); + + if (!$groupOutput) { + WP_CLI::log('--------------------------------------------------'); + + $this->cliLog('Please run `npm start` again to make sure everything works correctly.', "M"); + } + } +} diff --git a/src/Blocks/UseVariationCli.php b/src/Blocks/UseVariationCli.php new file mode 100644 index 000000000..da42904a9 --- /dev/null +++ b/src/Blocks/UseVariationCli.php @@ -0,0 +1,109 @@ + + */ + public function getDefaultArgs(): array + { + return [ + 'name' => 'button-block', + ]; + } + + /** + * Get WPCLI command doc + * + * @return array>|string> + */ + public function getDoc(): array + { + return [ + 'shortdesc' => 'Copy variation from our library to your project.', + 'synopsis' => [ + [ + 'type' => 'assoc', + 'name' => 'name', + 'description' => 'Specify variation name.', + 'optional' => false, + ], + ], + 'longdesc' => $this->prepareLongDesc(" + ## USAGE + + Used to copy pre-created variation from our library to your project. After copying you can modify the variation in any way you see fit. + + ## EXAMPLES + + # Copy variation by name. + $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --name='button-block' + + ## RESOURCES + + All our variations can be found here: + https://github.com/infinum/eightshift-frontend-libs/tree/develop/blocks/init/src/Blocks/variations + "), + ]; + } + + /* @phpstan-ignore-next-line */ + public function __invoke(array $args, array $assocArgs) // phpcs:ignore + { + $this->getIntroText($assocArgs); + + $groupOutput = $assocArgs['groupOutput'] ?? false; + + $this->moveItems( + $assocArgs, + Components::getProjectPaths('blocksSourceVariations'), + Components::getProjectPaths('blocksDestinationVariations'), + 'variation' + ); + + if (!$groupOutput) { + WP_CLI::log('--------------------------------------------------'); + + $this->cliLog('Please run `npm start` again to make sure everything works correctly.', "M"); + } + } +} diff --git a/src/Blocks/UseWrapperCli.php b/src/Blocks/UseWrapperCli.php new file mode 100644 index 000000000..c62ab10e0 --- /dev/null +++ b/src/Blocks/UseWrapperCli.php @@ -0,0 +1,91 @@ +>|string> + */ + public function getDoc(): array + { + return [ + 'shortdesc' => 'Copy wrapper from our library to your project.', + 'longdesc' => " + ## EXAMPLES + + # Copy wrapper. + $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + + ## RESOURCES + + Our wrapper can be found here: + https://github.com/infinum/eightshift-frontend-libs/tree/develop/blocks/init/src/Blocks/wrapper + " + ]; + } + + /* @phpstan-ignore-next-line */ + public function __invoke(array $args, array $assocArgs) // phpcs:ignore + { + $this->getIntroText($assocArgs); + + $groupOutput = $assocArgs['groupOutput'] ?? false; + + $this->moveItems( + \array_merge( + $assocArgs, + [ + 'name' => 'wrapper', + ], + ), + Components::getProjectPaths('blocksSourceWrapper'), + Components::getProjectPaths('blocksDestinationWrapper'), + 'wrapper', + true + ); + + if (!$groupOutput) { + WP_CLI::log('--------------------------------------------------'); + + $this->cliLog('Please run `npm start` again to make sure everything works correctly.', "M"); + } + } +} diff --git a/src/Build/BuildCli.php b/src/Build/BuildCli.php index 6ad3eaff3..d1ece9c97 100644 --- a/src/Build/BuildCli.php +++ b/src/Build/BuildCli.php @@ -11,20 +11,14 @@ namespace EightshiftLibs\Build; use EightshiftLibs\Cli\AbstractCli; -use EightshiftLibs\Cli\ParentGroups\CliProject; +use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class BuildCli */ class BuildCli extends AbstractCli { - /** - * Output dir relative path - * - * @var string - */ - public const OUTPUT_DIR = '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR; - /** * Get WPCLI command parent name * @@ -32,7 +26,7 @@ class BuildCli extends AbstractCli */ public function getCommandParentName(): string { - return CliProject::COMMAND_NAME; + return CliCreate::COMMAND_NAME; } /** @@ -46,16 +40,16 @@ public function getCommandName(): string } /** - * Define default develop props - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'root' => $args[1] ?? './', + 'path' => Components::getProjectPaths('projectRoot', 'bin'), + 'project_name' => 'eightshift-boilerplate', + 'project_type' => 'themes', ]; } @@ -71,21 +65,24 @@ public function getDoc(): array 'synopsis' => [ [ 'type' => 'assoc', - 'name' => 'root', - 'description' => 'Define project root relative to initialization file of WP CLI.', + 'name' => 'path', + 'description' => 'Define absolute folder path where build script file will be created.', 'optional' => true, + 'default' => $this->getDefaultArg('path'), ], [ 'type' => 'assoc', 'name' => 'project_name', 'description' => 'Set project file name, if theme use theme folder name, if plugin use plugin folder name.', 'optional' => true, + 'default' => $this->getDefaultArg('project_name'), ], [ 'type' => 'assoc', 'name' => 'project_type', 'description' => 'Set project file name, if theme use theme folder name, if plugin use plugin folder name. Default is themes.', 'optional' => true, + 'default' => $this->getDefaultArg('project_type'), ], ], 'longdesc' => $this->prepareLongDesc(" @@ -109,13 +106,15 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Props. - $root = $assocArgs['root'] ?? static::OUTPUT_DIR; + $path = $this->getArg($assocArgs, 'path'); // Read the template contents, and replace the placeholders with provided variables. $this->getExampleTemplate(__DIR__, $this->getClassShortName()) ->renameProjectName($assocArgs) ->renameProjectType($assocArgs) - ->outputWrite($root . 'bin', 'build.sh', $assocArgs); + ->outputWrite($path, 'build.sh', $assocArgs); } } diff --git a/src/Build/BuildExample.php b/src/Build/BuildExample.php index bade769b4..0cb6953a2 100644 --- a/src/Build/BuildExample.php +++ b/src/Build/BuildExample.php @@ -3,7 +3,7 @@ set -e function build() { - cd 'wp-content/themes/eightshift-boilerplate'; + cd 'wp-content/%project_type%/%project_name%'; npm install composer install --no-dev npm run build diff --git a/src/CiExclude/CiExcludeCli.php b/src/CiExclude/CiExcludeCli.php index 07a975e71..937d32def 100644 --- a/src/CiExclude/CiExcludeCli.php +++ b/src/CiExclude/CiExcludeCli.php @@ -11,20 +11,14 @@ namespace EightshiftLibs\CiExclude; use EightshiftLibs\Cli\AbstractCli; -use EightshiftLibs\Cli\ParentGroups\CliProject; +use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class CiExcludeCli */ class CiExcludeCli extends AbstractCli { - /** - * Output dir relative path - * - * @var string - */ - public const OUTPUT_DIR = '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR; - /** * Get WPCLI command parent name * @@ -32,7 +26,7 @@ class CiExcludeCli extends AbstractCli */ public function getCommandParentName(): string { - return CliProject::COMMAND_NAME; + return CliCreate::COMMAND_NAME; } /** @@ -46,16 +40,16 @@ public function getCommandName(): string } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'root' => $args[1] ?? './', + 'path' => Components::getProjectPaths('projectRoot'), + 'project_name' => 'eightshift-boilerplate', + 'project_type' => 'themes', ]; } @@ -71,21 +65,24 @@ public function getDoc(): array 'synopsis' => [ [ 'type' => 'assoc', - 'name' => 'root', - 'description' => 'Define project root relative to initialization file of WP CLI.', + 'name' => 'path', + 'description' => 'Define absolute folder path where exclude file file will be created.', 'optional' => true, + 'default' => $this->getDefaultArg('path'), ], [ 'type' => 'assoc', 'name' => 'project_name', 'description' => 'Set project file name, if theme use theme folder name, if plugin use plugin folder name.', 'optional' => true, + 'default' => $this->getDefaultArg('project_name'), ], [ 'type' => 'assoc', 'name' => 'project_type', 'description' => 'Set project file name, if theme use theme folder name, if plugin use plugin folder name. Default is themes.', 'optional' => true, + 'default' => $this->getDefaultArg('project_type'), ], ], 'longdesc' => $this->prepareLongDesc(" @@ -110,13 +107,19 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Props. - $root = $assocArgs['root'] ?? static::OUTPUT_DIR; + $path = $this->getArg($assocArgs, 'path'); + $projectName = $this->getArg($assocArgs, 'project_name'); + $projectType = $this->getArg($assocArgs, 'project_type'); // Read the template contents, and replace the placeholders with provided variables. - $this->getExampleTemplate(__DIR__, 'ci-exclude.txt') - ->renameProjectName($assocArgs) - ->renameProjectType($assocArgs) - ->outputWrite($root, 'ci-exclude.txt', $assocArgs); + $this->getExampleTemplate(__DIR__, $this->getClassShortName()) + ->searchReplaceString('searchReplaceString('\';', '') + ->searchReplaceString($this->getArgTemplate('project_name'), $projectName) + ->searchReplaceString($this->getArgTemplate('project_type'), $projectType) + ->outputWrite($path, 'ci-exclude.txt', $assocArgs); } } diff --git a/src/CiExclude/CiExcludeExample.php b/src/CiExclude/CiExcludeExample.php new file mode 100644 index 000000000..0e8f69bbc --- /dev/null +++ b/src/CiExclude/CiExcludeExample.php @@ -0,0 +1,28 @@ + + - */ - public function getDevelopArgs(array $args): array - { - $output = []; - - $i = 1; - foreach ($this->getDefaultArgs() as $key => $value) { - $output[$key] = $args[$i] ?? $value; - - $i++; - } - - return $output; - } - /** * Define default props for command. * @@ -345,84 +317,81 @@ public function getExampleFileName(string $string): string /** * Open an updated file and create it on output location * - * @param string $outputDir Absolute path to output from project root dir. - * @param string $outputFile Absolute path to output file. + * @param string $destination Absolute path to output. + * @param string $fileName File name to use on a new file.. * @param array $args Optional arguments. * * @return void */ - public function outputWrite(string $outputDir, string $outputFile, array $args = []): void + public function outputWrite(string $destination, string $fileName, array $args = []): void { + $groupOutput = $args['groupOutput'] ?? false; + $typeOutput = $args['typeOutput'] ?? 'service class'; // Set optional arguments. $skipExisting = $this->getSkipExisting($args); - // Set output paths. - $outputDir = $this->getOutputDir($outputDir); - // Set output file path. - $outputFile = $this->getOutputFile($outputFile); - $outputFile = "{$outputDir}{$outputFile}"; + $destinationFile = Components::joinPaths([$destination, $fileName]); // Bailout if file already exists. - if (\file_exists($outputFile) && $skipExisting === false) { - self::cliError("The file {$outputFile} can\'t be generated because it already exists."); + if (\file_exists($destinationFile) && $skipExisting === false) { + self::cliError( + \sprintf( + "%s file `%s` exist on this path: `%s`. If you want to override the destination folder plase use --skip_existing='true' argument.", + $typeOutput, + $fileName, + $this->getShortenCliPathOutput($destinationFile) + ) + ); } // Create output dir if it doesn't exist. - if (!\is_dir($outputDir)) { - \mkdir($outputDir, 0755, true); + if (!\is_dir($destination)) { + \mkdir($destination, 0755, true); } // Open a new file on output. // If there is any error, bailout. For example, user permission. - if (\fopen($outputFile, "wb") !== false) { - $fp = \fopen($outputFile, "wb"); + if (\fopen($destinationFile, "wb") === false) { + self::cliError( + \sprintf( + "%s file `%s` couldn't be created on this path `%s`. There was an unknown error.", + $typeOutput, + $fileName, + $this->getShortenCliPathOutput($destinationFile) + ) + ); + } + + $fp = \fopen($destinationFile, "wb"); - // Write and close. - \fwrite($fp, $this->fileContents); - \fclose($fp); + // Write and close. + \fwrite($fp, $this->fileContents); + \fclose($fp); + if (!$groupOutput) { // Return success. if ($skipExisting) { - WP_CLI::success("File {$outputFile} successfully renamed."); + WP_CLI::success( + \sprintf( + "`%s` renamed at `%s`.", + $fileName, + $this->getShortenCliPathOutput($destinationFile) + ) + ); } else { - WP_CLI::success("File {$outputFile} successfully created."); + WP_CLI::success( + \sprintf( + "`%s` created at `%s`.", + $fileName, + $this->getShortenCliPathOutput($destinationFile) + ) + ); } - return; } - self::cliError("File {$outputFile} couldn\'t be created. There was an error."); - } - - /** - * Get full output dir path - * - * @param string $path Project specific path. - * - * @return string - */ - public function getOutputDir(string $path = ''): string - { - $ds = \DIRECTORY_SEPARATOR; - - if (\function_exists('\add_action') && !\getenv('ES_TEST')) { - $root = $this->getProjectRootPath(); - } else { - $root = "{$this->getProjectRootPath(true)}{$ds}cliOutput"; - } - - $root = \rtrim($root, $ds); - $root = \trim($root, $ds); - - $path = \rtrim($path, $ds); - $path = \trim($path, $ds); - - if ($ds === '/') { - return "{$ds}{$root}{$ds}{$path}"; - } - - return "{$root}{$ds}{$path}"; + return; } /** @@ -436,7 +405,6 @@ public function getOutputFile(string $file): string { $ds = \DIRECTORY_SEPARATOR; - $file = \rtrim($file, $ds); $file = \trim($file, $ds); if (\strpos($file, '.') !== false) { @@ -459,15 +427,15 @@ public function renameNamespace(array $args = []): self $namespace = $this->getNamespace($args); $vendorPrefix = $this->getVendorPrefix($args); - if (\function_exists('\add_action') && !\getenv('ES_TEST')) { + if (\getenv('ES_TEST')) { $output = \str_replace( - "namespace {$vendorPrefix}\EightshiftBoilerplate\\", + 'namespace EightshiftBoilerplate\\', "namespace {$namespace}\\", $output ); } else { $output = \str_replace( - 'namespace EightshiftBoilerplate\\', + "namespace {$vendorPrefix}\EightshiftBoilerplate\\", "namespace {$namespace}\\", $output ); @@ -495,7 +463,13 @@ public function renameUse(array $args = []): self $prefixUse = 'use'; $prefixPackage = '@package'; - if (\function_exists('\add_action')) { + if (\getenv('ES_TEST')) { + $output = \str_replace( + "{$prefixUse} EightshiftBoilerplate\\", + "{$prefixUse} {$namespace}\\", + $output + ); + } else { $output = \str_replace( "{$prefixUse} EightshiftBoilerplateVendor\\", "{$prefixUse} {$vendorPrefix}\\", @@ -507,12 +481,6 @@ public function renameUse(array $args = []): self "{$prefixUse} {$namespace}\\", $output ); - } else { - $output = \str_replace( - "{$prefixUse} EightshiftBoilerplate\\", - "{$prefixUse} {$namespace}\\", - $output - ); } $output = \str_replace( @@ -617,8 +585,9 @@ public function renameProjectName(array $args = []): self { $projectName = 'eightshift-boilerplate'; - if (\function_exists('\add_action') && !\getenv('ES_TEST')) { - $projectName = \basename(\dirname(__DIR__, 5)); + // Don't use this option on the tests. + if (!\getenv('ES_TEST')) { + $projectName = \basename(Components::getProjectPaths('root')); } if (isset($args['project_name'])) { @@ -645,8 +614,9 @@ public function renameProjectType(array $args = []): self { $projectType = 'themes'; - if (\function_exists('\add_action')) { - $projectType = \basename(\dirname(__DIR__, 6)); + // Don't use this option on the tests. + if (!\getenv('ES_TEST')) { + $projectType = \basename(Components::getProjectPaths('wpContent')); } if (isset($args['project_type'])) { @@ -720,13 +690,8 @@ public function searchReplaceString(string $oldString, string $newString): self */ public function getComposer(array $args = []): array { - $ds = \DIRECTORY_SEPARATOR; if (!isset($args['config_path'])) { - if (\function_exists('\add_action')) { - $composerPath = "{$this->getProjectRootPath()}{$ds}composer.json"; - } else { - $composerPath = "{$this->getProjectRootPath(true)}{$ds}composer.json"; - } + $composerPath = Components::getProjectPaths('root', 'composer.json'); } else { $composerPath = $args['config_path']; } @@ -811,13 +776,12 @@ public function prepareSlug(string $string): string * Loop array of classes and output the commands * * @param class-string[] $items Array of classes. - * @param bool $run Run or log output. * @param array $args CLI command args. * * @return void * @throws ReflectionException Reflection exception. */ - public function getEvalLoop(array $items = [], bool $run = false, array $args = []): void + public function getEvalLoop(array $items = [], array $args = []): void { foreach ($items as $item) { $reflectionClass = new ReflectionClass($item); @@ -825,114 +789,11 @@ public function getEvalLoop(array $items = [], bool $run = false, array $args = $class = $reflectionClass->newInstanceArgs(['null']); if (\method_exists($class, 'getCommandName') && \method_exists($class, 'getCommandParentName')) { - if (\function_exists('\add_action')) { - WP_CLI::runcommand("{$this->commandParentName} {$class->getCommandParentName()} {$class->getCommandName()} {$this->prepareArgsManual($args)}"); - } else { - $sep = \DIRECTORY_SEPARATOR; - - if (!$run) { - WP_CLI::log("wp eval-file bin{$sep}cli.php {$class->getCommandParentName()}_{$class->getCommandName()} --skip-wordpress"); - } else { - WP_CLI::runcommand("eval-file bin{$sep}cli.php {$class->getCommandParentName()}_{$class->getCommandName()} --skip-wordpress"); - } - } + WP_CLI::runcommand("{$this->commandParentName} {$class->getCommandParentName()} {$class->getCommandName()} {$this->prepareArgsManual($args)}"); } } } - /** - * Run reset command in develop mode only - * - * @return void - */ - public function runReset(): void - { - $reset = new CliReset(''); - $sep = \DIRECTORY_SEPARATOR; - WP_CLI::runcommand("eval-file bin{$sep}cli.php {$reset->getCommandParentName()}_{$reset->getCommandName()} --skip-wordpress"); - } - - /** - * Returns projects root folder based on the environment - * - * @param bool $isDev Returns path based on the env. - * - * @return string - */ - public function getProjectRootPath(bool $isDev = false): string - { - $output = \dirname(__DIR__, 5); - - if ($isDev || \getenv('ES_TEST') !== false) { - $output = \dirname(__DIR__, 2); - } - - return $output; - } - - /** - * Returns projects root where config is installed based on the environment - * - * @param bool $isDev Returns path based on the env. - * - * @return string - */ - public function getProjectConfigRootPath(bool $isDev = false): string - { - $output = \dirname(__DIR__, 8); - - if ($isDev) { - $output = \dirname(__DIR__, 2); - } - - if (\getenv('ES_TEST')) { - $output = \dirname(__DIR__, 2); - } - - return $output; - } - - /** - * Returns Eightshift frontend libs path - * - * @param string $path Additional path. - * - * @return string - */ - public function getFrontendLibsPath(string $path = ''): string - { - $ds = \DIRECTORY_SEPARATOR; - return "{$this->getProjectRootPath()}{$ds}node_modules{$ds}@eightshift{$ds}frontend-libs{$ds}{$path}"; - } - - /** - * Returns Eightshift libs path - * - * @param string $path Additional path. - * - * @return string - */ - public function getLibsPath(string $path = ''): string - { - $ds = \DIRECTORY_SEPARATOR; - if (\getenv('ES_TEST')) { - return "{$this->getProjectRootPath()}{$ds}{$path}"; - } - - return "{$this->getProjectRootPath()}{$ds}vendor{$ds}infinum{$ds}eightshift-libs{$ds}{$path}"; - } - - /** - * Returns Eightshift frontend libs blocks init path. - * - * @return string - */ - public function getFrontendLibsBlockPath(): string - { - $ds = \DIRECTORY_SEPARATOR; - return $this->getFrontendLibsPath("blocks{$ds}init"); - } - /** * Full blocks files list used for renaming * @@ -1059,6 +920,10 @@ public function prepareLongDesc(string $string): string */ protected function copyRecursively(string $source, string $destination): void { + if (!\is_dir($destination)) { + \mkdir($destination, 0755, true); + } + try { $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($source, FilesystemIterator::SKIP_DOTS), @@ -1083,4 +948,58 @@ protected function copyRecursively(string $source, string $destination): void } } } + + /** + * Copy item from source to destination. + * + * @param string $source Source path. + * @param string $destination Destination path. + * + * @return void + */ + protected function copyItem(string $source, string $destination): void + { + $dir = \dirname($destination); + + if (!\file_exists($dir)) { + \mkdir($dir, 0755, true); + } + + \copy($source, $destination); + } + + /** + * Return cli intro. + * + * @param array $arg $argument to pass. + * + * @return void + */ + protected function getIntroText(array $arg = []): void + { + $introOutput = $arg['introOutput'] ?? true; + + if (!$introOutput) { + return; + } + + $this->cliLog($this->prepareLongDesc(". + --------------------------------------------------------------------------------------- + ._____ ___ ____ _ _ _____ ____ _ _ ___ _____ _____ + | ____| |_ _| / ___| | | | | |_ _| / ___| | | | | |_ _| | ___| |_ _| + | _| | | | | _ | |_| | | | \___ \ | |_| | | | | |_ | | + | |___ | | | |_| | | _ | | | ___) | | _ | | | | _| | | + |_____| |___| \____| |_| |_| |_| |____/ |_| |_| |___| |_| |_| + .____ ___ ___ _ _____ ____ ____ _ _ _____ _____ + | __ ) / _ \ |_ _| | | | ____| | _ \ | _ \ | | / \ |_ _| | ____| + | _ \ | | | | | | | | | _| | |_) | | |_) | | | / _ \ | | | _| + | |_) | | |_| | | | | |___ | |___ | _ < | __/ | |___ / ___ \ | | | |___ + |____/ \___/ |___| |_____| |_____| |_| \_\ |_| |_____| /_/ \_\ |_| |_____| + . + Thank you for using Eightshift boilerplate for your project. + Documentation can be found on this link: https://infinum.github.io/eightshift-docs/. + --------------------------------------------------------------------------------------- + . + "), 'M'); + } } diff --git a/src/Cli/Cli.php b/src/Cli/Cli.php index 5ce6628d0..e3c504050 100644 --- a/src/Cli/Cli.php +++ b/src/Cli/Cli.php @@ -16,20 +16,21 @@ use EightshiftLibs\AnalyticsGdpr\AnalyticsGdprCli; use EightshiftLibs\BlockPatterns\BlockPatternCli; use EightshiftLibs\Blocks\BlocksCli; -use EightshiftLibs\Blocks\BlockComponentCli; -use EightshiftLibs\Blocks\BlockCli; -use EightshiftLibs\Blocks\BlocksStorybookCli; -use EightshiftLibs\Blocks\BlockVariationCli; -use EightshiftLibs\Blocks\BlockWrapperCli; +use EightshiftLibs\Blocks\UseComponentCli; +use EightshiftLibs\Blocks\UseBlockCli; +use EightshiftLibs\Blocks\UseAssetsCli; +use EightshiftLibs\Blocks\UseGlobalAssetsCli; +use EightshiftLibs\Blocks\UseManifestCli; +use EightshiftLibs\Blocks\UseStorybookCli; +use EightshiftLibs\Blocks\UseVariationCli; +use EightshiftLibs\Blocks\UseWrapperCli; use EightshiftLibs\Build\BuildCli; use EightshiftLibs\CiExclude\CiExcludeCli; use EightshiftLibs\Cli\ParentGroups\CliBoilerplate; use EightshiftLibs\Cli\ParentGroups\CliCreate; -use EightshiftLibs\Cli\ParentGroups\CliProject; use EightshiftLibs\Cli\ParentGroups\CliRun; -use EightshiftLibs\Cli\ParentGroups\CliSetup; use EightshiftLibs\Cli\ParentGroups\CliBlocks; -use EightshiftLibs\Cli\ParentGroups\CliWebp; +use EightshiftLibs\Cli\ParentGroups\CliInit; use EightshiftLibs\Columns\Media\WebPMediaColumnCli; use EightshiftLibs\Config\ConfigCli; use EightshiftLibs\ConfigProject\ConfigProjectCli; @@ -55,6 +56,9 @@ use EightshiftLibs\Db\ImportCli; use EightshiftLibs\Geolocation\GeolocationCli; use EightshiftLibs\GitIgnore\GitIgnoreCli; +use EightshiftLibs\Init\InitBlocksCli; +use EightshiftLibs\Init\InitProjectCli; +use EightshiftLibs\Init\InitThemeCli; use EightshiftLibs\Media\RegenerateWebPMediaCli; use EightshiftLibs\Media\UseWebPMediaCli; use EightshiftLibs\Readme\ReadmeCli; @@ -73,31 +77,28 @@ class Cli { /** - * All classes defined as parent list commands. + * All commands defined as parent list commands. * * @var class-string[] */ - public const PARENTS_LIST = [ + public const PARENT_COMMANDS = [ CliCreate::class, - CliProject::class, CliRun::class, - CliSetup::class, CliBlocks::class, - CliWebp::class, + CliInit::class, ]; /** - * All classes and commands that can be used on development and public WP CLI. + * All commands that are service classes type. Command prefix - create. * * @var class-string[] */ - public const CLASSES_LIST = [ + public const CREATE_COMMANDS = [ AdminMenuCli::class, AdminReusableBlocksMenuCli::class, AdminSubMenuCli::class, AcfMetaCli::class, AnalyticsGdprCli::class, - BlocksCli::class, EnqueueAdminCli::class, EnqueueBlocksCli::class, EnqueueThemeCli::class, @@ -129,130 +130,60 @@ class Cli ]; /** - * All classes and commands that can be used on WP project. + * All commands that can be used on WP project directly from the libs. Command prefix - run. * * @var class-string[] */ - public const COMMANDS_LIST = [ + public const RUN_COMMANDS = [ RegenerateWebPMediaCli::class, UseWebPMediaCli::class, - ]; - - /** - * All classes and commands used only for WPCLI - blocks. - * - * @var class-string[] - */ - public const BLOCKS_CLASSES = [ - BlockCli::class, - BlockComponentCli::class, - BlockVariationCli::class, - BlockWrapperCli::class, - BlockPatternCli::class, - BlocksStorybookCli::class, - ]; - - /** - * All classes and commands used only for WPCLI - project. - * - * @var class-string[] - */ - public const PROJECT_CLASSES = [ ExportCli::class, ImportCli::class, UpdateCli::class, ]; /** - * All classes and commands used for project setup. + * All commands used for block editor. Command prefix - blocks. * * @var class-string[] */ - public const SETUP_CLASSES = [ - CliInitTheme::class, - CliInitProject::class, - CliInitAll::class, + public const BLOCKS_COMMANDS = [ + BlocksCli::class, + BlockPatternCli::class, + UseStorybookCli::class, + UseManifestCli::class, + UseAssetsCli::class, + UseGlobalAssetsCli::class, + UseBlockCli::class, + UseComponentCli::class, + UseVariationCli::class, + UseWrapperCli::class, ]; /** - * All classes and commands used only for development. + * All commands used for setting up. Command prefix - init. * * @var class-string[] */ - public const DEVELOP_CLASSES = [ - CliReset::class, - CliRunAll::class, - CliShowAll::class, + public const INIT_COMMANDS = [ + InitThemeCli::class, + InitProjectCli::class, + InitBlocksCli::class, ]; - /** - * Define all classes to register for development. - * - * @return class-string[] - */ - public function getDevelopClasses(): array - { - return \array_merge( - static::CLASSES_LIST, - static::DEVELOP_CLASSES, - static::SETUP_CLASSES, - static::COMMANDS_LIST - ); - } - /** * Define all classes to register for normal WP. * * @return class-string[] */ - public function getPublicClasses(): array - { - return \array_merge( - static::CLASSES_LIST, - static::BLOCKS_CLASSES, - static::PROJECT_CLASSES, - static::SETUP_CLASSES, - static::COMMANDS_LIST - ); - } - - /** - * Run all CLI commands for develop. - * - * @param string[] $args WPCLI eval-file arguments. - * - * @throws Exception Exception if the class doesn't exist. - * - * @return void - */ - public function loadDevelop(array $args = []): void + public function getCommandsClasses(): array { - $commandName = $args[0] ?? ''; - - if (empty($commandName)) { - CliHelpers::cliError('First argument must be a valid command name.'); - } - - foreach ($this->getDevelopClasses() as $item) { - $reflectionClass = new ReflectionClass($item); - $class = $reflectionClass->newInstanceArgs(['null']); - - if ( - \method_exists($class, 'getCommandName') && - \method_exists($class, 'getCommandParentName') && - \method_exists($class, 'getDevelopArgs') && - \method_exists($class, '__invoke') - ) { - if ("{$class->getCommandParentName()}_{$class->getCommandName()}" === $commandName) { - $class->__invoke( - [], - $class->getDevelopArgs($args) - ); - - break; - } - } - } + return [ + ...static::CREATE_COMMANDS, + ...static::BLOCKS_COMMANDS, + ...static::INIT_COMMANDS, + ...static::RUN_COMMANDS + ]; } /** @@ -266,12 +197,13 @@ public function loadDevelop(array $args = []): void */ public function load(string $commandParentName): void { + // Duplicate condition because WP_CLI will throw error on the project. if (!\getenv('ES_TEST') && \defined('WP_CLI')) { // Top Level command name. WP_CLI::add_command($commandParentName, new CliBoilerplate()); // Register all top level commands. - foreach (self::PARENTS_LIST as $item) { + foreach (self::PARENT_COMMANDS as $item) { $reflectionClass = new ReflectionClass($item); $class = $reflectionClass->newInstanceArgs(); $name = $reflectionClass->getConstant('COMMAND_NAME'); @@ -280,7 +212,7 @@ public function load(string $commandParentName): void } } - foreach ($this->getPublicClasses() as $item) { + foreach ($this->getCommandsClasses() as $item) { $reflectionClass = new ReflectionClass($item); $class = $reflectionClass->newInstanceArgs([$commandParentName]); diff --git a/src/Cli/CliHelpers.php b/src/Cli/CliHelpers.php index 7afa92012..6ef1a29e8 100644 --- a/src/Cli/CliHelpers.php +++ b/src/Cli/CliHelpers.php @@ -10,6 +10,7 @@ namespace EightshiftLibs\Cli; +use EightshiftLibs\Helpers\Components; use WP_CLI; use WP_CLI\ExitException; @@ -57,4 +58,36 @@ public static function getGithubPluginName(string $name): string return $splitName[\count($splitName) - 1]; } + + /** + * Output WP_CLI log with color. + * + * @param string $msg Msg to output. + * @param string $color Color to use from this list https://make.wordpress.org/cli/handbook/references/internal-api/wp-cli-colorize/. + * + * @return void + */ + protected function cliLog(string $msg, string $color = ''): void + { + if ($color) { + WP_CLI::log(WP_CLI::colorize("%{$color}{$msg}%n")); + return; + } + + WP_CLI::log($msg); + return; + } + + /** + * Return shorten CLI path output + * + * @param string $path Path to check. + * @param string $ref Ref from getProjectPaths to remove. + * + * @return string + */ + protected function getShortenCliPathOutput(string $path, string $ref = 'projectRoot'): string + { + return \str_replace(Components::getProjectPaths($ref), '', $path); + } } diff --git a/src/Cli/CliInitAll.php b/src/Cli/CliInitAll.php deleted file mode 100644 index 937201b86..000000000 --- a/src/Cli/CliInitAll.php +++ /dev/null @@ -1,91 +0,0 @@ ->|string> - */ - public function getDoc(): array - { - return [ - 'shortdesc' => 'Initial setup for all service classes in the WordPress theme project.', - 'longdesc' => $this->prepareLongDesc(" - ## USAGE - - Used to create ALL service classes in your project. - This command is used only in develop mode. For this to work you must set global constant ES_DEVELOP_MODE to true. - - ## EXAMPLES - - # Create all service classes: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} - "), - - ]; - } - - /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) // phpcs:ignore - { - if (!\function_exists('\add_action')) { - $this->runReset(); - WP_CLI::log('--------------------------------------------------'); - } - - $classes = \array_merge( - Cli::CLASSES_LIST, - Cli::BLOCKS_CLASSES, - Cli::SETUP_CLASSES - ); - - $this->getEvalLoop($classes, true, $assocArgs); - - WP_CLI::log('--------------------------------------------------'); - - if (!\getenv('ES_TEST')) { - WP_CLI::log((string)shell_exec('npm run start')); // phpcs:ignore - } - - WP_CLI::log('--------------------------------------------------'); - - WP_CLI::success('All commands are finished.'); - } -} diff --git a/src/Cli/CliInitProject.php b/src/Cli/CliInitProject.php deleted file mode 100644 index 59e545167..000000000 --- a/src/Cli/CliInitProject.php +++ /dev/null @@ -1,134 +0,0 @@ ->|string> - */ - public function getDoc(): array - { - return [ - 'shortdesc' => 'Kickstart your WordPress project with this simple command.', - 'longdesc' => $this->prepareLongDesc(" - ## USAGE - - Generates initial project setup with all files to run on the client project. - For example: gitignore file for the full WordPress project, continuous integration exclude files, etc. - - ## EXAMPLES - - # Setup project: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} - "), - ]; - } - - /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) - { - if (!\function_exists('\add_action')) { - $this->runReset(); - WP_CLI::log('--------------------------------------------------'); - } - - foreach (static::INIT_PROJECT_CLASSES as $item) { - $reflectionClass = new ReflectionClass($item); - - $class = $reflectionClass->newInstanceArgs([$this->commandParentName]); - - if (\method_exists($class, 'getCommandName') && \method_exists($class, 'getCommandParentName')) { - if (\function_exists('\add_action')) { - WP_CLI::runcommand("{$this->commandParentName} {$class->getCommandParentName()} {$class->getCommandName()} {$this->prepareArgsManual($assocArgs)}"); - } else { - $sep = \DIRECTORY_SEPARATOR; - WP_CLI::runcommand("eval-file bin{$sep}cli.php {$class->getCommandParentName()}_{$class->getCommandName()} --skip-wordpress"); - } - } - } - - WP_CLI::log('--------------------------------------------------'); - - if (!\getenv('ES_TEST')) { - WP_CLI::log((string)shell_exec('npm run start')); // phpcs:ignore - } - - WP_CLI::log('--------------------------------------------------'); - - WP_CLI::success('All commands are finished.'); - } -} diff --git a/src/Cli/CliInitTheme.php b/src/Cli/CliInitTheme.php deleted file mode 100644 index 8934e467c..000000000 --- a/src/Cli/CliInitTheme.php +++ /dev/null @@ -1,122 +0,0 @@ ->|string> - */ - public function getDoc(): array - { - return [ - 'shortdesc' => 'Kickstart your WordPress theme with this simple command.', - 'longdesc' => $this->prepareLongDesc(" - ## USAGE - - Generates initial theme setup with all files to create a custom theme. - - ## EXAMPLES - - # Setup theme: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} - "), - ]; - } - - /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) - { - if (!\function_exists('\add_action')) { - $this->runReset(); - WP_CLI::log('--------------------------------------------------'); - } - - foreach (static::INIT_THEME_CLASSES as $item) { - $reflectionClass = new ReflectionClass($item); - - $class = $reflectionClass->newInstanceArgs([$this->commandParentName]); - - if (\method_exists($class, 'getCommandName') && \method_exists($class, 'getCommandParentName')) { - if (\function_exists('\add_action')) { - WP_CLI::runcommand("{$this->commandParentName} {$class->getCommandParentName()} {$class->getCommandName()} {$this->prepareArgsManual($assocArgs)}"); - } else { - // phpcs:ignore Generic.Files.LineLength.TooLong - WP_CLI::runcommand("eval-file bin" . \DIRECTORY_SEPARATOR . "cli.php {$class->getCommandParentName()}_{$class->getCommandName()} {$this->prepareArgsManual($assocArgs)} --skip-wordpress"); - } - } - } - - WP_CLI::log('--------------------------------------------------'); - - if (!\getenv('ES_TEST')) { - WP_CLI::log('We have copied everyting that you need in your active theme. Now make sure that you naviate inside and type:'); - WP_CLI::log(WP_CLI::colorize('%Mnpm run start%n')); - } - - WP_CLI::log('--------------------------------------------------'); - - WP_CLI::success('You are ready to start developing, good luck.'); - } -} diff --git a/src/Cli/CliReset.php b/src/Cli/CliReset.php deleted file mode 100644 index ec9542549..000000000 --- a/src/Cli/CliReset.php +++ /dev/null @@ -1,80 +0,0 @@ ->|string> - */ - public function getDoc(): array - { - return [ - 'shortdesc' => 'DEVELOP - Used to reset and remove all outputs.', - ]; - } - - /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) - { - $dir = $this->getOutputDir(''); - - if (!\is_dir($dir)) { - WP_CLI::error('Output directory is not a directory.'); - } - - $iterator = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS); - $files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST); - - foreach ($files as $file) { - if ($file->isDir()) { - \rmdir($file->getRealPath()); - } else { - \unlink($file->getRealPath()); - } - } - - \rmdir($dir); - - WP_CLI::success('Output directory successfully removed.'); - } -} diff --git a/src/Cli/CliRunAll.php b/src/Cli/CliRunAll.php deleted file mode 100644 index d5bb36ab9..000000000 --- a/src/Cli/CliRunAll.php +++ /dev/null @@ -1,75 +0,0 @@ ->|string> - */ - public function getDoc(): array - { - return [ - 'shortdesc' => 'DEVELOP - Used to run all commands.', - ]; - } - - /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) - { - // Set output paths. - $outputDir = $this->getOutputDir(); - - // Create output dir if it doesn't exist. - if (!\is_dir($outputDir)) { - \mkdir($outputDir, 0755, true); - } - - $this->runReset(); - - WP_CLI::log('--------------------------------------------------'); - - $this->getEvalLoop(Cli::CLASSES_LIST, true); - - WP_CLI::log('--------------------------------------------------'); - - WP_CLI::success('All commands are finished.'); - } -} diff --git a/src/Cli/CliShowAll.php b/src/Cli/CliShowAll.php deleted file mode 100644 index 39c5927a4..000000000 --- a/src/Cli/CliShowAll.php +++ /dev/null @@ -1,95 +0,0 @@ ->|string> - */ - public function getDoc(): array - { - return [ - 'shortdesc' => 'DEVELOP - Used to show all commands.', - ]; - } - - /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) - { - WP_CLI::log(WP_CLI::colorize('%mCommands for development:%n')); - - $this->getEvalLoop(Cli::DEVELOP_CLASSES); - - WP_CLI::log('-----------------------------------------'); - - WP_CLI::log(WP_CLI::colorize('%mCommands for wp-cli and development:%n')); - - $this->getEvalLoop(Cli::CLASSES_LIST); - - WP_CLI::log('-----------------------------------------'); - - WP_CLI::log(WP_CLI::colorize('%mCommands for wp-cli only - blocks:%n')); - - $this->getEvalLoop(Cli::BLOCKS_CLASSES); - - WP_CLI::log('-----------------------------------------'); - - WP_CLI::log(WP_CLI::colorize('%mCommands for wp-cli only - project:%n')); - - $this->getEvalLoop(Cli::PROJECT_CLASSES); - - WP_CLI::log('-----------------------------------------'); - - WP_CLI::log(WP_CLI::colorize('%mCommands for project setup:%n')); - - $this->getEvalLoop(Cli::SETUP_CLASSES); - - WP_CLI::log('-----------------------------------------'); - - WP_CLI::log(WP_CLI::colorize('%mCommands for WP project only:%n')); - - $this->getEvalLoop(Cli::COMMANDS_LIST); - - WP_CLI::log('-----------------------------------------'); - - WP_CLI::success('All commands are outputted.'); - } -} diff --git a/src/Cli/TopLevelGroup/CliBoilerplate.php b/src/Cli/ParentGroups/CliBoilerplate.php similarity index 94% rename from src/Cli/TopLevelGroup/CliBoilerplate.php rename to src/Cli/ParentGroups/CliBoilerplate.php index 527d5834e..1d0b96426 100644 --- a/src/Cli/TopLevelGroup/CliBoilerplate.php +++ b/src/Cli/ParentGroups/CliBoilerplate.php @@ -3,7 +3,7 @@ /** * Class that registers WPCLI commands used as top level placeholders. * - * @package EightshiftLibs\Cli\TopLevelGroup + * @package EightshiftLibs\Cli\ParentGroups */ declare(strict_types=1); diff --git a/src/Cli/ParentGroups/CliSetup.php b/src/Cli/ParentGroups/CliInit.php similarity index 83% rename from src/Cli/ParentGroups/CliSetup.php rename to src/Cli/ParentGroups/CliInit.php index 0364894ae..36768bb99 100644 --- a/src/Cli/ParentGroups/CliSetup.php +++ b/src/Cli/ParentGroups/CliInit.php @@ -15,10 +15,10 @@ /** * Initially setup your project like theme, plugin, project, etc. These commands should be used only once. */ -class CliSetup extends WP_CLI_Command +class CliInit extends WP_CLI_Command { /** * Cli command name parent constant. */ - public const COMMAND_NAME = 'setup'; + public const COMMAND_NAME = 'init'; } diff --git a/src/Cli/ParentGroups/CliProject.php b/src/Cli/ParentGroups/CliProject.php deleted file mode 100644 index b64e528c9..000000000 --- a/src/Cli/ParentGroups/CliProject.php +++ /dev/null @@ -1,24 +0,0 @@ -getIntroText($assocArgs); + $className = $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. @@ -81,6 +79,6 @@ public function __invoke(array $args, array $assocArgs) ->renameNamespace($assocArgs) ->renameUse($assocArgs) ->renameTextDomain($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'Columns' . \DIRECTORY_SEPARATOR . 'Media'), "{$className}.php", $assocArgs); } } diff --git a/src/Config/AbstractConfigData.php b/src/Config/AbstractConfigData.php index c8087b2cb..5a4075224 100644 --- a/src/Config/AbstractConfigData.php +++ b/src/Config/AbstractConfigData.php @@ -11,6 +11,7 @@ namespace EightshiftLibs\Config; use EightshiftLibs\Exception\InvalidPath; +use EightshiftLibs\Helpers\Components; /** * The project config class. @@ -31,7 +32,7 @@ abstract class AbstractConfigData implements ConfigDataInterface public static function getProjectPath(string $path = ''): string { $locations = [ - \trailingslashit(\dirname(__DIR__, 5)) . $path, + Components::getProjectPaths('root', $path), \trailingslashit(\get_stylesheet_directory()) . $path, \trailingslashit(\get_template_directory()) . $path, ]; diff --git a/src/Config/ConfigCli.php b/src/Config/ConfigCli.php index d7ec14dcc..bbe0e75aa 100644 --- a/src/Config/ConfigCli.php +++ b/src/Config/ConfigCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class ConfigCli */ class ConfigCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Config'; - /** * Get WPCLI command parent name * @@ -44,18 +40,16 @@ public function getCommandName(): string } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'name' => $args[1] ?? 'Boilerplate', - 'version' => $args[2] ?? '1', - 'routes_version' => $args[5] ?? 'v2', + 'name' => 'Boilerplate', + 'version' => '1', + 'routes_version' => '2', ]; } @@ -74,18 +68,21 @@ public function getDoc(): array 'name' => 'name', 'description' => 'Define project name.', 'optional' => true, + 'default' => $this->getDefaultArg('name'), ], [ 'type' => 'assoc', 'name' => 'version', 'description' => 'Define project version.', 'optional' => true, + 'default' => $this->getDefaultArg('version'), ], [ 'type' => 'assoc', 'name' => 'routes_version', 'description' => 'Define project REST version.', 'optional' => true, + 'default' => $this->getDefaultArg('routes_version'), ], ], 'longdesc' => $this->prepareLongDesc(" @@ -109,10 +106,12 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Props. - $name = $assocArgs['name'] ?? ''; - $version = $assocArgs['version'] ?? ''; - $routesVersion = $assocArgs['routes_version'] ?? ''; + $name = $this->getArg($assocArgs, 'name'); + $version = $this->getArg($assocArgs, 'version'); + $routesVersion = $this->getArg($assocArgs, 'routes_version'); $className = $this->getClassShortName(); @@ -123,18 +122,18 @@ public function __invoke(array $args, array $assocArgs) ->renameUse($assocArgs); if (!empty($name)) { - $class->searchReplaceString('eightshift-libs', $name); + $class->searchReplaceString($this->getArgTemplate('name'), $name); } if (!empty($version)) { - $class->searchReplaceString('1.0.0', $version); + $class->searchReplaceString($this->getArgTemplate('version'), $version); } if (!empty($routesVersion)) { - $class->searchReplaceString('v1', $routesVersion); + $class->searchReplaceString($this->getArgTemplate('routes_version'), $routesVersion); } // Output final class to new file/folder and finish. - $class->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + $class->outputWrite(Components::getProjectPaths('srcDestination', 'Config'), "{$className}.php", $assocArgs); } } diff --git a/src/Config/ConfigExample.php b/src/Config/ConfigExample.php index 784bd0853..8a3b8ab4d 100644 --- a/src/Config/ConfigExample.php +++ b/src/Config/ConfigExample.php @@ -27,7 +27,7 @@ class ConfigExample extends AbstractConfigData */ public static function getProjectName(): string { - return 'eightshift-libs'; + return '%name%'; } /** @@ -37,7 +37,7 @@ public static function getProjectName(): string */ public static function getProjectVersion(): string { - return '1.0.0'; + return '%version%'; } /** @@ -61,6 +61,6 @@ public static function getProjectRoutesNamespace(): string */ public static function getProjectRoutesVersion(): string { - return 'v1'; + return '%routes_version%'; } } diff --git a/src/ConfigProject/ConfigProjectCli.php b/src/ConfigProject/ConfigProjectCli.php index 6307997ee..e42e36862 100644 --- a/src/ConfigProject/ConfigProjectCli.php +++ b/src/ConfigProject/ConfigProjectCli.php @@ -11,19 +11,14 @@ namespace EightshiftLibs\ConfigProject; use EightshiftLibs\Cli\AbstractCli; -use EightshiftLibs\Cli\ParentGroups\CliProject; -use WP_CLI; +use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class ConfigProjectCli */ class ConfigProjectCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR; - /** * Get WPCLI command parent name * @@ -31,7 +26,7 @@ class ConfigProjectCli extends AbstractCli */ public function getCommandParentName(): string { - return CliProject::COMMAND_NAME; + return CliCreate::COMMAND_NAME; } /** @@ -45,16 +40,14 @@ public function getCommandName(): string } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'root' => $args[2] ?? './', + 'path' => Components::getProjectPaths('projectRoot'), ]; } @@ -70,9 +63,10 @@ public function getDoc(): array 'synopsis' => [ [ 'type' => 'assoc', - 'name' => 'root', - 'description' => 'Define project root relative to initialization file of WP CLI.', + 'name' => 'path', + 'description' => 'Define absolute path to project root folder.', 'optional' => true, + 'default' => $this->getDefaultArg('path'), ], ], 'longdesc' => $this->prepareLongDesc(" @@ -96,8 +90,10 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Props. - $root = $assocArgs['root'] ?? static::OUTPUT_DIR; + $path = $this->getArg($assocArgs, 'path'); // Read the template contents, and replace the placeholders with provided variables. $class = $this->getExampleTemplate(__DIR__, $this->getClassShortName()) @@ -105,22 +101,24 @@ public function __invoke(array $args, array $assocArgs) ->renameTextDomain($assocArgs); // Output final class to new file/folder and finish. - $class->outputWrite($root, 'wp-config-project.php', $assocArgs); - - WP_CLI::success("Please do the following steps manually to complete the setup:"); - WP_CLI::success("1. In wp-config.php - Make sure to define WP_ENVIRONMENT_TYPE const to 'development' like so: `"); - WP_CLI::success("2. In wp-config.php - Make sure to require wp-config-project.php (at the end of the file) but before the wp-settings.php. Like this:`);"); - WP_CLI::success(" + $class->outputWrite($path, 'wp-config-project.php', $assocArgs); + + $this->cliLog('', 'B'); + $this->cliLog('Please do the following steps manually to complete the `wp-config-project.php` setup:', 'B'); + $this->cliLog("1. Open `wp-config.php` file located in the root of your project.", 'B'); + $this->cliLog("2. Make sure to define `WP_ENVIRONMENT_TYPE` constant to 'development' like so: `.", 'B'); + $this->cliLog("3. Make sure to require `wp-config-project.php` (at the end of the file) but before the `wp-settings.php`. Like this:`);", 'B'); + $this->cliLog(" /** Absolute path to the WordPress directory. */ if ( !\defined('ABSPATH') ) { define('ABSPATH', \dirname(__FILE__) . '/'); } - + // Include wp config for your project. require_once(ABSPATH . 'wp-config-project.php'); - + /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php'); - "); + ", 'B'); } } diff --git a/src/CustomMeta/AcfMetaCli.php b/src/CustomMeta/AcfMetaCli.php index 99bfa8b4f..6542bff50 100644 --- a/src/CustomMeta/AcfMetaCli.php +++ b/src/CustomMeta/AcfMetaCli.php @@ -12,19 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class AcfMetaCli */ class AcfMetaCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'CustomMeta'; - /** * Get WPCLI command parent name * @@ -46,16 +40,14 @@ public function getCommandName(): string } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'name' => $args[1] ?? 'title', + 'name' => 'title', ]; } @@ -101,8 +93,10 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Props. - $fieldName = $this->prepareSlug($assocArgs['name'] ?? ''); + $fieldName = $this->prepareSlug($this->getArg($assocArgs, 'name')); // Get full class name. $className = $this->getFileName($fieldName); @@ -113,6 +107,6 @@ public function __invoke(array $args, array $assocArgs) ->renameClassNameWithPrefix($this->getClassShortName(), $className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'CustomMeta'), "{$className}.php", $assocArgs); } } diff --git a/src/CustomPostType/PostTypeCli.php b/src/CustomPostType/PostTypeCli.php index cff2cf127..831b919de 100644 --- a/src/CustomPostType/PostTypeCli.php +++ b/src/CustomPostType/PostTypeCli.php @@ -12,19 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class PostTypeCli */ class PostTypeCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'CustomPostType'; - /** * Get WPCLI command parent name * @@ -44,24 +38,23 @@ public function getCommandName(): string { return 'post_type'; } + /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'label' => $args[1] ?? 'Product', - 'slug' => $args[2] ?? 'product', - 'rewrite_url' => $args[3] ?? 'product', - 'rest_endpoint_slug' => $args[4] ?? 'products', - 'capability' => $args[5] ?? 'post', - 'menu_position' => $args[6] ?? 40, - 'menu_icon' => $args[7] ?? 'admin-settings', - 'plural_label' => $args[8] ?? 'Products', + 'label' => 'Product', + 'plural_label' => 'Products', + 'slug' => 'product', + 'rewrite_url' => 'product', + 'rest_endpoint_slug' => 'products', + 'capability' => 'post', + 'menu_position' => 20, + 'menu_icon' => 'admin-settings', ]; } @@ -81,6 +74,13 @@ public function getDoc(): array 'description' => 'The label of the custom post type to show in WP admin.', 'optional' => false, ], + [ + 'type' => 'assoc', + 'name' => 'plural_label', + 'description' => 'The plural label of the custom post type. Used for label generation. If not specified the plural will have appended s at the end of the label.', // phpcs:ignore Generic.Files.LineLength.TooLong + 'optional' => false, + 'default' => $this->getDefaultArg('plural_label'), + ], [ 'type' => 'assoc', 'name' => 'slug', @@ -104,24 +104,21 @@ public function getDoc(): array 'name' => 'capability', 'description' => 'The default capability for the custom post types. Example: post.', 'optional' => true, + 'default' => $this->getDefaultArg('capability'), ], [ 'type' => 'assoc', 'name' => 'menu_position', 'description' => 'The default menu position for the custom post types. Example: 20.', 'optional' => true, + 'default' => $this->getDefaultArg('menu_position'), ], [ 'type' => 'assoc', 'name' => 'menu_icon', 'description' => 'The default menu icon for the custom post types. Example: dashicons-analytics.', 'optional' => true, - ], - [ - 'type' => 'assoc', - 'name' => 'plural_label', - 'description' => 'The plural label of the custom post type. Used for label generation. If not specified the plural will have appended s at the end of the label.', // phpcs:ignore Generic.Files.LineLength.TooLong - 'optional' => true, + 'default' => $this->getDefaultArg('menu_icon'), ], ], 'longdesc' => $this->prepareLongDesc(" @@ -145,15 +142,17 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Props. - $label = $assocArgs['label'] ?? 'Custom Post Type'; - $slug = $this->prepareSlug($assocArgs['slug'] ?? 'custom-post-type'); - $rewriteUrl = $this->prepareSlug($assocArgs['rewrite_url'] ?? 'custom-post-type'); - $restEndpointSlug = $this->prepareSlug($assocArgs['rest_endpoint_slug'] ?? 'custom-post-type'); - $capability = $assocArgs['capability'] ?? ''; - $menuPosition = (string) ($assocArgs['menu_position'] ?? ''); - $menuIcon = $assocArgs['menu_icon'] ?? ''; - $pluralLabel = $assocArgs['plural_label'] ?? $label . 's'; + $label = $this->getArg($assocArgs, 'label'); + $slug = $this->prepareSlug($this->getArg($assocArgs, 'slug')); + $rewriteUrl = $this->prepareSlug($this->getArg($assocArgs, 'rewrite_url')); + $restEndpointSlug = $this->prepareSlug($this->getArg($assocArgs, 'rest_endpoint_slug')); + $capability = $this->getArg($assocArgs, 'capability'); + $menuPosition = $this->getArg($assocArgs, 'menu_position'); + $menuIcon = $this->getArg($assocArgs, 'menu_icon'); + $pluralLabel = $this->getArg($assocArgs, 'plural_label'); // Get full class name. $className = $this->getFileName($slug); @@ -165,27 +164,27 @@ public function __invoke(array $args, array $assocArgs) ->renameNamespace($assocArgs) ->renameUse($assocArgs) ->renameTextDomain($assocArgs) - ->searchReplaceString('example-slug', $slug) - ->searchReplaceString('example-url-slug', $rewriteUrl) - ->searchReplaceString('example-endpoint-slug', $restEndpointSlug) - ->searchReplaceString('Singular Name', $label) - ->searchReplaceString('singular name', \strtolower($label)) - ->searchReplaceString('Plural Name', $pluralLabel) - ->searchReplaceString('plural name', \strtolower($pluralLabel)); + ->searchReplaceString($this->getArgTemplate('slug'), $slug) + ->searchReplaceString($this->getArgTemplate('rewrite_url'), $rewriteUrl) + ->searchReplaceString($this->getArgTemplate('rest_endpoint_slug'), $restEndpointSlug) + ->searchReplaceString($this->getArgTemplate('label'), $label) + ->searchReplaceString($this->getArgTemplate('label_lowercaps'), \strtolower($label)) + ->searchReplaceString($this->getArgTemplate('plural_label'), $pluralLabel) + ->searchReplaceString($this->getArgTemplate('plural_label_lowecaps'), \strtolower($pluralLabel)); if (!empty($capability)) { - $class->searchReplaceString("'post'", "'{$capability}'"); + $class->searchReplaceString($this->getArgTemplate('capability'), $capability); } if (!empty($menuPosition)) { - $class->searchReplaceString('20', $menuPosition); + $class->searchReplaceString($this->getDefaultArg('menu_position'), $menuPosition); } if (!empty($menuIcon)) { - $class->searchReplaceString('dashicons-analytics', $menuIcon); + $class->searchReplaceString($this->getArgTemplate('menu_icon'), $menuIcon); } // Output final class to new file/folder and finish. - $class->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + $class->outputWrite(Components::getProjectPaths('srcDestination', 'CustomPostType'), "{$className}.php", $assocArgs); } } diff --git a/src/CustomPostType/PostTypeExample.php b/src/CustomPostType/PostTypeExample.php index c7309b1b4..8fb5e23b1 100644 --- a/src/CustomPostType/PostTypeExample.php +++ b/src/CustomPostType/PostTypeExample.php @@ -22,28 +22,28 @@ class PostTypeExample extends AbstractPostType * * @var string */ - public const POST_TYPE_SLUG = 'example-slug'; + public const POST_TYPE_SLUG = '%slug%'; /** * URL slug for the custom post type. * * @var string */ - public const POST_TYPE_URL_SLUG = 'example-url-slug'; + public const POST_TYPE_URL_SLUG = '%rewrite_url%'; /** * Rest API Endpoint slug constant. * * @var string */ - public const REST_API_ENDPOINT_SLUG = 'example-endpoint-slug'; + public const REST_API_ENDPOINT_SLUG = '%rest_endpoint_slug%'; /** * Capability type for projects post type. * * @var string */ - public const POST_CAPABILITY_TYPE = 'post'; + public const POST_CAPABILITY_TYPE = '%capability%'; /** * Location of menu in sidebar. @@ -57,7 +57,7 @@ class PostTypeExample extends AbstractPostType * * @var string */ - public const MENU_ICON = 'dashicons-analytics'; + public const MENU_ICON = '%menu_icon%'; /** * Get the slug to use for the Projects custom post type. @@ -78,22 +78,22 @@ protected function getPostTypeArguments(): array { $nouns = [ \esc_html_x( - 'Singular Name', + '%label%', 'post type upper case singular name', 'eightshift-libs' ), \esc_html_x( - 'singular name', + '%label_lowercaps%', 'post type lower case singular name', 'eightshift-libs' ), \esc_html_x( - 'Plural Name', + '%plural_label%', 'post type upper case plural name', 'eightshift-libs' ), \esc_html_x( - 'plural name', + '%plural_label_lowecaps%', 'post type lower case plural name', 'eightshift-libs' ), diff --git a/src/CustomTaxonomy/TaxonomyCli.php b/src/CustomTaxonomy/TaxonomyCli.php index 25a60afb0..9b7e38baa 100644 --- a/src/CustomTaxonomy/TaxonomyCli.php +++ b/src/CustomTaxonomy/TaxonomyCli.php @@ -10,22 +10,15 @@ namespace EightshiftLibs\CustomTaxonomy; -use EightshiftBoilerplate\CustomTaxonomy\TaxonomyExample; use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class TaxonomyCli */ class TaxonomyCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'CustomTaxonomy'; - /** * Get WPCLI command parent name * @@ -47,20 +40,18 @@ public function getCommandName(): string } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'label' => $args[1] ?? 'Location', - 'slug' => $args[2] ?? 'location', - 'rest_endpoint_slug' => $args[3] ?? 'locations', - 'post_type_slug' => $args[4] ?? 'post', - 'plural_label' => $args[5] ?? 'Locations', + 'label' => 'Location', + 'plural_label' => 'Locations', + 'slug' => 'location', + 'rest_endpoint_slug' => 'locations', + 'post_type_slug' => 'post', ]; } @@ -80,6 +71,12 @@ public function getDoc(): array 'description' => 'The label of the custom taxonomy to show in WP admin.', 'optional' => false, ], + [ + 'type' => 'assoc', + 'name' => 'plural_label', + 'description' => 'The label of the custom taxonomy to show in WP admin but as a plural version.', + 'optional' => false, + ], [ 'type' => 'assoc', 'name' => 'slug', @@ -120,12 +117,14 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Props. - $label = $assocArgs['label'] ?? 'Custom Taxonomy'; - $slug = $this->prepareSlug($assocArgs['slug'] ?? TaxonomyExample::TAXONOMY_SLUG); - $restEndpointSlug = $this->prepareSlug($assocArgs['rest_endpoint_slug'] ?? TaxonomyExample::REST_API_ENDPOINT_SLUG); - $postTypeSlug = $this->prepareSlug($assocArgs['post_type_slug'] ?? TaxonomyExample::TAXONOMY_POST_TYPE_SLUG); - $pluralLabel = $assocArgs['plural_label'] ?? $label . 's'; + $label = $this->getArg($assocArgs, 'label'); + $pluralLabel = $this->getArg($assocArgs, 'plural_label'); + $slug = $this->prepareSlug($this->getArg($assocArgs, 'slug')); + $restEndpointSlug = $this->prepareSlug($this->getArg($assocArgs, 'rest_endpoint_slug')); + $postTypeSlug = $this->prepareSlug($this->getArg($assocArgs, 'post_type_slug')); // Get full class name. $className = $this->getFileName($slug); @@ -137,14 +136,13 @@ public function __invoke(array $args, array $assocArgs) ->renameNamespace($assocArgs) ->renameUse($assocArgs) ->renameTextDomain($assocArgs) - ->searchReplaceString('example-slug', $slug) - ->searchReplaceString('example-endpoint-slug', $restEndpointSlug) - ->searchReplaceString("'post'", "'{$postTypeSlug}'") - ->searchReplaceString('Blog_Taxonomy', $className) - ->searchReplaceString('Singular Name', $label) - ->searchReplaceString('singular name', \strtolower($label)) - ->searchReplaceString('Plural Name', $pluralLabel) - ->searchReplaceString('plural name', \strtolower($pluralLabel)) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->searchReplaceString($this->getArgTemplate('slug'), $slug) + ->searchReplaceString($this->getArgTemplate('rest_endpoint_slug'), $restEndpointSlug) + ->searchReplaceString($this->getArgTemplate('post_type_slug'), $postTypeSlug) + ->searchReplaceString($this->getArgTemplate('label'), $label) + ->searchReplaceString($this->getArgTemplate('label_lowercaps'), \strtolower($label)) + ->searchReplaceString($this->getArgTemplate('plural_label'), $pluralLabel) + ->searchReplaceString($this->getArgTemplate('plural_label_lowecaps'), \strtolower($pluralLabel)) + ->outputWrite(Components::getProjectPaths('srcDestination', 'CustomTaxonomy'), "{$className}.php", $assocArgs); } } diff --git a/src/CustomTaxonomy/TaxonomyExample.php b/src/CustomTaxonomy/TaxonomyExample.php index 4a5450654..eb26c6d66 100644 --- a/src/CustomTaxonomy/TaxonomyExample.php +++ b/src/CustomTaxonomy/TaxonomyExample.php @@ -22,21 +22,21 @@ class TaxonomyExample extends AbstractTaxonomy * * @var string */ - public const TAXONOMY_SLUG = 'example-slug'; + public const TAXONOMY_SLUG = '%slug%'; /** * Taxonomy post type slug constant. * * @var string */ - public const TAXONOMY_POST_TYPE_SLUG = 'post'; + public const TAXONOMY_POST_TYPE_SLUG = '%post_type_slug%'; /** * Rest API Endpoint slug constant. * * @var string */ - public const REST_API_ENDPOINT_SLUG = 'example-endpoint-slug'; + public const REST_API_ENDPOINT_SLUG = '%rest_endpoint_slug%'; /** * Get the slug of the custom taxonomy @@ -67,22 +67,22 @@ protected function getTaxonomyArguments(): array { $nouns = [ \esc_html_x( - 'Singular Name', + '%label%', 'taxonomy upper case singular name', 'eightshift-libs' ), \esc_html_x( - 'singular name', + '%label_lowercaps%', 'taxonomy lower case singular name', 'eightshift-libs' ), \esc_html_x( - 'Plural Name', + '%plural_label%', 'taxonomy upper case plural name', 'eightshift-libs' ), \esc_html_x( - 'plural name', + '%plural_label_lowecaps%', 'taxonomy lower case plural name', 'eightshift-libs' ), diff --git a/src/Db/DbExport.php b/src/Db/DbExport.php index c97f33ffc..2ca2d93a8 100644 --- a/src/Db/DbExport.php +++ b/src/Db/DbExport.php @@ -76,7 +76,7 @@ function dbExport(string $projectRootPath, array $args = []) } // Finishing. - WP_CLI::success("Export complete! File {$exportFileName} is located in {$projectRootPath} folder."); + WP_CLI::success("Export complete! File `{$exportFileName}` is located in `{$projectRootPath}` folder."); WP_CLI::log('--------------------------------------------------'); // Remove old db export file if it exists. diff --git a/src/Db/DbImport.php b/src/Db/DbImport.php index 7dcc0c439..a273689b1 100644 --- a/src/Db/DbImport.php +++ b/src/Db/DbImport.php @@ -15,36 +15,28 @@ /** * Importing database. * - * @param string $projectRootPath Root of the project where config is located. + * @param string $setupFile Setup file path. * @param array $args Optional arguments. - * @param string $setupFile Define setup file name. * * @return void */ - function dbImport(string $projectRootPath, array $args = [], string $setupFile = 'setup.json') + function dbImport(string $setupFile, array $args = []) { // Check if mandatory parameters exists. $from = $args['from'] ?? ''; $to = $args['to'] ?? ''; if (empty($from)) { - CliHelpers::cliError("--from parameter is mandatory. Please provide one url key from {$setupFile} file."); + CliHelpers::cliError("--from parameter is mandatory. Please provide one url key from setup.json file."); } if (empty($to)) { - CliHelpers::cliError("--to parameter is mandatory. Please provide one url key from {$setupFile} file."); + CliHelpers::cliError("--to parameter is mandatory. Please provide one url key from setup.json file."); } - // Change execution folder. - if (!is_dir($projectRootPath)) { - CliHelpers::cliError("Folder doesn't exist on this path: {$projectRootPath}."); - } - - chdir($projectRootPath); - - // Check if setup exists. - if (!file_exists($setupFile)) { - CliHelpers::cliError("setup.json is missing at this path: {$setupFile}."); + // Check if file exists. + if (is_dir($setupFile) && !file_exists($setupFile)) { + CliHelpers::cliError("Setup file doesn't exist on this path: {$setupFile}."); } // Parse json file to array. @@ -52,7 +44,7 @@ function dbImport(string $projectRootPath, array $args = [], string $setupFile = // Check if $data is empty. if (empty($data)) { - CliHelpers::cliError("{$setupFile} is empty."); + CliHelpers::cliError("Setup file is empty on this path: {$setupFile}."); } // Check if urls key exists. @@ -86,63 +78,65 @@ function dbImport(string $projectRootPath, array $args = [], string $setupFile = $toScheme = $to['scheme']; } - // Define db export file name. - $dbFileName = 'latest.sql'; + if (!getenv('ES_TEST')) { + // Define db export file name. + $dbFileName = 'latest.sql'; + + // Define export file name. + $exportFileName = 'latest_dump.tar.gz'; - // Define export file name. - $exportFileName = 'latest_dump.tar.gz'; + // Define export folder name. + $exportFolderName = 'latest_dump'; - // Define export folder name. - $exportFolderName = 'latest_dump'; + // Remove old db export folder if it exists. + if (file_exists($exportFolderName)) { + WP_CLI::log((string)shell_exec("rm -rf {$exportFolderName}")); + WP_CLI::log("Removed old temp {$exportFolderName} folder."); + WP_CLI::log('--------------------------------------------------'); + } - // Remove old db export folder if it exists. - if (file_exists($exportFolderName)) { - WP_CLI::log((string)shell_exec("rm -rf {$exportFolderName}")); - WP_CLI::log("Removed old temp {$exportFolderName} folder."); + // Create new temp folder. + mkdir($exportFolderName); + WP_CLI::log("Created temp {$exportFolderName} folder."); WP_CLI::log('--------------------------------------------------'); - } - // Create new temp folder. - mkdir($exportFolderName); - WP_CLI::log("Created temp {$exportFolderName} folder."); - WP_CLI::log('--------------------------------------------------'); - - // Export files to new temp folder. - WP_CLI::log((string)shell_exec("tar zxf {$exportFileName} -C {$exportFolderName}")); - WP_CLI::log("Exported {$exportFileName} to {$exportFolderName} folder."); - WP_CLI::log('--------------------------------------------------'); - - // Execute db export. - WP_CLI::runcommand('db export'); - WP_CLI::log('Db exported successfully.'); - WP_CLI::log('--------------------------------------------------'); - - WP_CLI::runcommand('db reset'); - WP_CLI::log('--------------------------------------------------'); - - // Import new database. - WP_CLI::runcommand("db import {$exportFolderName}/{$dbFileName}"); - WP_CLI::log('Database import done.'); - WP_CLI::log('--------------------------------------------------'); - - // Search and replace url host. - WP_CLI::runcommand("search-replace {$fromHost} {$toHost} --url={$fromHost} --all-tables --network"); - WP_CLI::log('Database search replace for host successfully finished.'); - WP_CLI::log('--------------------------------------------------'); - - // Search and replace url scheme. - if ($toScheme !== $fromScheme) { - WP_CLI::runcommand("search-replace {$fromScheme}://{$toHost} {$toScheme}://{$toHost} --all-tables --network"); - WP_CLI::log('Database search replace for scheme successfully finished.'); + // Export files to new temp folder. + WP_CLI::log((string)shell_exec("tar zxf {$exportFileName} -C {$exportFolderName}")); + WP_CLI::log("Exported {$exportFileName} to {$exportFolderName} folder."); + WP_CLI::log('--------------------------------------------------'); + + // Execute db export. + WP_CLI::runcommand('db export'); + WP_CLI::log('Db exported successfully.'); WP_CLI::log('--------------------------------------------------'); - } - // Clean up. - WP_CLI::runcommand('cache flush'); - WP_CLI::runcommand('transient delete --all'); - WP_CLI::runcommand('rewrite flush'); - WP_CLI::log('Flushing cache, removing transients and resetting permalinks!'); - WP_CLI::log('--------------------------------------------------'); + WP_CLI::runcommand('db reset'); + WP_CLI::log('--------------------------------------------------'); + + // Import new database. + WP_CLI::runcommand("db import {$exportFolderName}/{$dbFileName}"); + WP_CLI::log('Database import done.'); + WP_CLI::log('--------------------------------------------------'); + + // Search and replace url host. + WP_CLI::runcommand("search-replace {$fromHost} {$toHost} --url={$fromHost} --all-tables --network"); + WP_CLI::log('Database search replace for host successfully finished.'); + WP_CLI::log('--------------------------------------------------'); + + // Search and replace url scheme. + if ($toScheme !== $fromScheme) { + WP_CLI::runcommand("search-replace {$fromScheme}://{$toHost} {$toScheme}://{$toHost} --all-tables --network"); + WP_CLI::log('Database search replace for scheme successfully finished.'); + WP_CLI::log('--------------------------------------------------'); + } + + // Clean up. + WP_CLI::runcommand('cache flush'); + WP_CLI::runcommand('transient delete --all'); + WP_CLI::runcommand('rewrite flush'); + WP_CLI::log('Flushing cache, removing transients and resetting permalinks!'); + WP_CLI::log('--------------------------------------------------'); + } WP_CLI::success('Finished! Success!'); } diff --git a/src/Db/ExportCli.php b/src/Db/ExportCli.php index 7284edb81..efb3e308b 100644 --- a/src/Db/ExportCli.php +++ b/src/Db/ExportCli.php @@ -12,6 +12,7 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliRun; +use EightshiftLibs\Helpers\Components; use WP_CLI\ExitException; /** @@ -39,6 +40,19 @@ public function getCommandName(): string return 'export'; } + /** + * Define default arguments. + * + * @return array + */ + public function getDefaultArgs(): array + { + return [ + 'skip_db' => 'false', + 'skip_uploads' => 'false', + ]; + } + /** * Get WPCLI command doc * @@ -54,6 +68,7 @@ public function getDoc(): array 'name' => 'skip_db', 'description' => 'If you want to skip exporting database.', 'optional' => true, + 'default' => $this->getDefaultArg('skip_db'), 'options' => [ 'true', 'false', @@ -64,6 +79,7 @@ public function getDoc(): array 'name' => 'skip_uploads', 'description' => 'If you want to skip exporting images.', 'optional' => true, + 'default' => $this->getDefaultArg('skip_uploads'), ], ], 'longdesc' => $this->prepareLongDesc(" @@ -91,14 +107,16 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { - require $this->getLibsPath('src/Db/DbExport.php'); + $this->getIntroText($assocArgs); + + require Components::getProjectPaths('libs', 'src/Db/DbExport.php'); try { dbExport( // phpcs:ignore - $this->getProjectConfigRootPath(), + Components::getProjectPaths('projectRoot'), [ - 'skip_db' => $assocArgs['skip_db'] ?? false, - 'skip_uploads' => $assocArgs['skip_uploads'] ?? false, + 'skip_db' => $this->getArg($assocArgs, 'skip_db'), + 'skip_uploads' => $this->getArg($assocArgs, 'skip_uploads'), ] ); } catch (ExitException $e) { diff --git a/src/Db/ImportCli.php b/src/Db/ImportCli.php index fbfa40b89..472fc8235 100644 --- a/src/Db/ImportCli.php +++ b/src/Db/ImportCli.php @@ -12,6 +12,7 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliRun; +use EightshiftLibs\Helpers\Components; use WP_CLI\ExitException; /** @@ -39,6 +40,22 @@ public function getCommandName(): string return 'import'; } + /** + * Define default arguments. + * + * @return array + */ + public function getDefaultArgs(): array + { + $sep = \DIRECTORY_SEPARATOR; + + return [ + 'from' => '', + 'to' => '', + 'setup_file' => Components::getProjectPaths('cliOutput', "setup{$sep}setup.json"), + ]; + } + /** * Get WPCLI command doc * @@ -83,14 +100,16 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { - require $this->getLibsPath('src/Db/DbImport.php'); + $this->getIntroText($assocArgs); + + require Components::getProjectPaths('libs', 'src/Db/DbImport.php'); try { dbImport( // phpcs:ignore - $this->getProjectConfigRootPath(), + $this->getArg($assocArgs, 'setup_file'), [ - 'from' => $assocArgs['from'] ?? '', - 'to' => $assocArgs['to'] ?? '', + 'from' => $this->getArg($assocArgs, 'from'), + 'to' => $this->getArg($assocArgs, 'to'), ] ); } catch (ExitException $e) { diff --git a/src/Enqueue/Admin/EnqueueAdminCli.php b/src/Enqueue/Admin/EnqueueAdminCli.php index f75451ef9..11ba25d35 100644 --- a/src/Enqueue/Admin/EnqueueAdminCli.php +++ b/src/Enqueue/Admin/EnqueueAdminCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class EnqueueAdminCli */ class EnqueueAdminCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Enqueue' . \DIRECTORY_SEPARATOR . 'Admin'; - /** * Get WPCLI command parent name * @@ -73,6 +69,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. @@ -80,6 +78,6 @@ public function __invoke(array $args, array $assocArgs) ->renameClassName($className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'Enqueue' . \DIRECTORY_SEPARATOR . 'Admin'), "{$className}.php", $assocArgs); } } diff --git a/src/Enqueue/Blocks/EnqueueBlocksCli.php b/src/Enqueue/Blocks/EnqueueBlocksCli.php index 2fd1d7ccf..7169de556 100644 --- a/src/Enqueue/Blocks/EnqueueBlocksCli.php +++ b/src/Enqueue/Blocks/EnqueueBlocksCli.php @@ -12,19 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class EnqueueBlocksCli */ class EnqueueBlocksCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Enqueue' . \DIRECTORY_SEPARATOR . 'Blocks'; - /** * Get WPCLI command parent name * @@ -75,6 +69,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. @@ -82,6 +78,6 @@ public function __invoke(array $args, array $assocArgs) ->renameClassName($className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'Enqueue' . \DIRECTORY_SEPARATOR . 'Blocks'), "{$className}.php", $assocArgs); } } diff --git a/src/Enqueue/Theme/EnqueueThemeCli.php b/src/Enqueue/Theme/EnqueueThemeCli.php index a788abff0..04ef5241c 100644 --- a/src/Enqueue/Theme/EnqueueThemeCli.php +++ b/src/Enqueue/Theme/EnqueueThemeCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class EnqueueThemeCli */ class EnqueueThemeCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Enqueue' . \DIRECTORY_SEPARATOR . 'Theme'; - /** * Get WPCLI command parent name * @@ -73,6 +69,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. @@ -80,6 +78,6 @@ public function __invoke(array $args, array $assocArgs) ->renameClassName($className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'Enqueue' . \DIRECTORY_SEPARATOR . 'Theme'), "{$className}.php", $assocArgs); } } diff --git a/src/Geolocation/GeolocationCli.php b/src/Geolocation/GeolocationCli.php index 6f69f1126..172b1ef04 100644 --- a/src/Geolocation/GeolocationCli.php +++ b/src/Geolocation/GeolocationCli.php @@ -14,19 +14,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class GeolocationCli */ class GeolocationCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Geolocation'; - /** * Get WPCLI command parent name * @@ -47,20 +41,6 @@ public function getCommandName(): string return 'geolocation'; } - /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. - * - * @return array - */ - public function getDevelopArgs(array $args): array - { - return [ - 'cookie_name' => 'es-geolocation-test', - ]; - } - /** * Define default arguments. * @@ -116,8 +96,10 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Arguments. - $cookie_name = $this->getArg($assocArgs, 'cookie_name'); + $cookieName = $this->getArg($assocArgs, 'cookie_name'); // Get full class name. $className = $this->getClassShortName(); @@ -128,9 +110,9 @@ public function __invoke(array $args, array $assocArgs) ->renameNamespace($assocArgs) ->renameUse($assocArgs) ->renameTextDomain($assocArgs) - ->searchReplaceString($this->getArgTemplate('cookie_name'), $cookie_name); + ->searchReplaceString($this->getArgTemplate('cookie_name'), $cookieName); // Output final class to new file/folder and finish. - $class->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + $class->outputWrite(Components::getProjectPaths('srcDestination', 'Geolocation'), "{$className}.php", $assocArgs); } } diff --git a/src/GitIgnore/GitIgnoreCli.php b/src/GitIgnore/GitIgnoreCli.php index fb0772cb5..83eacf89a 100644 --- a/src/GitIgnore/GitIgnoreCli.php +++ b/src/GitIgnore/GitIgnoreCli.php @@ -11,20 +11,14 @@ namespace EightshiftLibs\GitIgnore; use EightshiftLibs\Cli\AbstractCli; -use EightshiftLibs\Cli\ParentGroups\CliProject; +use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class GitIgnoreCli */ class GitIgnoreCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR; - /** * Get WPCLI command parent name * @@ -32,7 +26,7 @@ class GitIgnoreCli extends AbstractCli */ public function getCommandParentName(): string { - return CliProject::COMMAND_NAME; + return CliCreate::COMMAND_NAME; } /** @@ -46,16 +40,14 @@ public function getCommandName(): string } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'root' => $args[1] ?? './', + 'path' => Components::getProjectPaths('projectRoot'), ]; } @@ -71,9 +63,10 @@ public function getDoc(): array 'synopsis' => [ [ 'type' => 'assoc', - 'name' => 'root', - 'description' => 'Define project root relative to initialization file of WP CLI.', + 'name' => 'path', + 'description' => 'Define absolute folder path where gitignore file file will be created.', 'optional' => true, + 'default' => $this->getDefaultArg('path'), ], ], 'longdesc' => $this->prepareLongDesc(" @@ -98,11 +91,13 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Props. - $root = $assocArgs['root'] ?? static::OUTPUT_DIR; + $path = $this->getArg($assocArgs, 'path'); // Read the template contents, and replace the placeholders with provided variables. $this->getExampleTemplate(__DIR__, '.gitignore') - ->outputWrite($root, '.gitignore', $assocArgs); + ->outputWrite($path, '.gitignore', $assocArgs); } } diff --git a/src/Helpers/Components.php b/src/Helpers/Components.php index c4b713445..f7874a722 100644 --- a/src/Helpers/Components.php +++ b/src/Helpers/Components.php @@ -10,7 +10,6 @@ namespace EightshiftLibs\Helpers; -use EightshiftLibs\Blocks\AbstractBlocks; use EightshiftLibs\Exception\ComponentException; /** @@ -84,12 +83,13 @@ public static function render(string $component, array $attributes = [], string { $sep = \DIRECTORY_SEPARATOR; - if (empty($parentPath)) { - $parentPath = \dirname(__DIR__, 5); - - if (\getenv('ES_TEST')) { - $parentPath = \dirname(__DIR__, 2); - } + // If parent path is missing provide project root. + if (!$parentPath) { + $parentPath = Components::getProjectPaths('root'); + } else { + // Remove slash. + $parentPath = \trim($parentPath, $sep); + $parentPath = "{$sep}{$parentPath}{$sep}"; } /** @@ -105,21 +105,14 @@ public static function render(string $component, array $attributes = [], string * parentClass__componentName.php */ if (\strpos($component, '.php') !== false) { - $parentPath = \rtrim($parentPath, '/'); - $parentPath = \ltrim($parentPath, '/'); - $component = \ltrim($component, '/'); - $componentPath = "{$sep}{$parentPath}{$sep}{$component}"; + $component = \ltrim($component, $sep); + $componentPath = $component; } else { - $blocksPath = AbstractBlocks::PATH_BLOCKS_PARENT; - - if (\getenv('ES_TEST')) { - $blocksPath = AbstractBlocks::PATH_BLOCKS_PARENT_TESTS; - } - - $componentsFolderName = AbstractBlocks::PATH_COMPONENTS; - $componentPath = "{$parentPath}{$blocksPath}{$componentsFolderName}{$sep}{$component}{$sep}{$component}.php"; + $componentPath = Components::getProjectPaths('blocksDestinationComponents', "{$component}{$sep}{$component}.php", $sep); } + $componentPath = "{$parentPath}{$componentPath}"; + if ($useComponentDefaults) { $manifest = Components::getManifest($componentPath); } @@ -173,50 +166,36 @@ public static function renderPartial( ): string { $sep = \DIRECTORY_SEPARATOR; - $parentPath = \dirname(__DIR__, 5); - - if (\getenv('ES_TEST')) { - $parentPath = \dirname(__DIR__, 2); + // If no extension is provided use php. + if (\strpos($name, '.php') === false) { + $name = "{$name}.php"; } - $blocksPath = AbstractBlocks::PATH_BLOCKS_PARENT; - - if (\getenv('ES_TEST')) { - $blocksPath = AbstractBlocks::PATH_BLOCKS_PARENT_TESTS; - } + $partialPath = "{$parent}{$sep}{$partialFolderName}{$sep}{$name}"; // Detect folder based on the name. switch ($type) { case 'block': case 'blocks': case 'custom': - $folderName = AbstractBlocks::PATH_BLOCKS; + $path = Components::getProjectPaths('blocksDestinationCustom', $partialPath); break; case 'component': case 'components': - $folderName = AbstractBlocks::PATH_COMPONENTS; + $path = Components::getProjectPaths('blocksDestinationComponents', $partialPath); break; case 'variation': case 'variations': - $folderName = AbstractBlocks::PATH_VARIATIONS; + $path = Components::getProjectPaths('blocksDestinationVariations', $partialPath); break; case 'wrapper': - case '': - $folderName = AbstractBlocks::PATH_WRAPPER; + $path = Components::getProjectPaths('blocksDestinationWrapper', $partialPath); break; default: - $folderName = $type; + $path = Components::getProjectPaths('root', $partialPath); break; } - // If no extension is provided use php. - if (\strpos($name, '.php') === false) { - $name = "{$name}.php"; - } - - // Set full path. - $path = "{$parentPath}{$blocksPath}{$folderName}{$sep}{$parent}{$sep}{$partialFolderName}{$sep}{$name}"; - // Bailout if file is missing. if (!\file_exists($path)) { throw ComponentException::throwUnableToLocatePartial($path); @@ -296,18 +275,252 @@ public static function getManifest(string $path, string $name = ''): array public static function getManifestDirect(string $path): array { $sep = \DIRECTORY_SEPARATOR; - $path = \trim($path, $sep); + $path = \rtrim($path, $sep); $manifest = "{$path}{$sep}manifest.json"; - if ($sep === '/') { - $manifest = "{$sep}{$manifest}"; - } - if (!\file_exists($manifest)) { throw ComponentException::throwUnableToLocateComponent($manifest); } return \json_decode(\implode(' ', (array)\file($manifest)), true); } + + /** + * Get all project paths for store. + * + * @var array + */ + public const PROJECT_PATHS = [ + 'projectRoot', + 'srcDestination', + 'cliOutput', + 'wpContent', + 'libs', + + 'blocksGlobalAssetsSource', + 'blocksAssetsSource', + 'blocksStorybookSource', + 'blocksSource', + 'blocksSourceCustom', + 'blocksSourceComponents', + 'blocksSourceVariations', + 'blocksSourceWrapper', + + 'blocksGlobalAssetsDestination', + 'blocksAssetsDestination', + 'blocksStorybookDestination', + 'blocksDestination', + 'blocksDestinationCustom', + 'blocksDestinationComponents', + 'blocksDestinationVariations', + 'blocksDestinationWrapper', + ]; + + /** + * Internal helper for getting all project paths for easy mocking in tests. + * + * @param string $type Type fo path to return. + * @param string $sufix Additional sufix path to add. + * @param string $prefix Additional prefix insted of dirname path. + * + * @return string + */ + public static function getProjectPaths(string $type = '', string $sufix = '', string $prefix = ''): string + { + $sep = \DIRECTORY_SEPARATOR; + + $path = ''; + $internalPrefix = \dirname(__FILE__, 6); + + if (\getenv('ES_TEST')) { + $internalPrefix = \dirname(__FILE__, 3); + } + + $flibsPath = ["node_modules", "@eightshift", "frontend-libs", "blocks", "init"]; + $libsPath = ["vendor", "infinum", "eightshift-libs"]; + $testsDataPath = ["tests", "data"]; + $srcPath = "src"; + $blocksPath = [$srcPath, "Blocks"]; + $storybookPath = "storybook"; + $assetsPath = "assets"; + $cliOutputPath = "cliOutput"; + + $name = ''; + + switch ($type) { + case 'projectRoot': + $internalPrefix = \dirname(__FILE__, 9); + + if (\getenv('ES_TEST')) { + $internalPrefix = \dirname(__FILE__, 3); + } + break; + case 'testsData': + if (\getenv('ES_TEST')) { + $internalPrefix = \dirname(__FILE__, 3); + $path = self::joinPaths([...$testsDataPath]); + } + + break; + case 'srcDestination': + $path = $srcPath; + + if (\getenv('ES_TEST')) { + $internalPrefix = \dirname(__FILE__, 3); + $path = self::joinPaths([$cliOutputPath, $srcPath]); + } + + break; + case 'cliOutput': + if (\getenv('ES_TEST')) { + $internalPrefix = \dirname(__FILE__, 3); + $path = $cliOutputPath; + } + + break; + case 'wpContent': + $internalPrefix = \dirname(__FILE__, 7); + + if (\getenv('ES_TEST')) { + $internalPrefix = \dirname(__FILE__, 3); + } + break; + case 'libs': + $path = self::joinPaths($libsPath); + + if (\getenv('ES_TEST')) { + $path = ''; + } + break; + case 'blocksGlobalAssetsSource': + $path = self::joinPaths([...$flibsPath, $assetsPath]); + + if (\getenv('ES_TEST')) { + $path = self::joinPaths([...$testsDataPath, $assetsPath]); + } + break; + case 'blocksAssetsSource': + $path = self::joinPaths([...$flibsPath, ...$blocksPath, $assetsPath]); + + if (\getenv('ES_TEST')) { + $path = self::joinPaths([...$testsDataPath, ...$blocksPath, $assetsPath]); + } + break; + case 'blocksStorybookSource': + $path = self::joinPaths([...$flibsPath, $storybookPath]); + + if (\getenv('ES_TEST')) { + $path = self::joinPaths([...$testsDataPath, $storybookPath]); + } + break; + case 'blocksSource': + $path = self::joinPaths([...$flibsPath, ...$blocksPath]); + + if (\getenv('ES_TEST')) { + $path = self::joinPaths([...$testsDataPath, ...$blocksPath]); + } + break; + case 'blocksSourceCustom': + $name = 'custom'; + break; + case 'blocksSourceComponents': + $name = 'components'; + break; + case 'blocksSourceVariations': + $name = 'variations'; + break; + case 'blocksSourceWrapper': + $name = 'wrapper'; + break; + + case 'blocksGlobalAssetsDestination': + $path = self::joinPaths([$assetsPath]); + + if (\getenv('ES_TEST')) { + $path = self::joinPaths([$cliOutputPath, $assetsPath]); + } + break; + case 'blocksAssetsDestination': + $path = self::joinPaths([...$blocksPath, $assetsPath]); + + if (\getenv('ES_TEST')) { + $path = self::joinPaths([$cliOutputPath, ...$blocksPath, $assetsPath]); + } + break; + case 'blocksStorybookDestination': + $path = self::joinPaths([".{$storybookPath}"]); + + if (\getenv('ES_TEST')) { + $path = self::joinPaths([$cliOutputPath, ".{$storybookPath}"]); + } + break; + case 'blocksDestination': + $path = self::joinPaths($blocksPath); + + if (\getenv('ES_TEST')) { + $path = self::joinPaths([$cliOutputPath, ...$blocksPath]); + } + break; + case 'blocksDestinationCustom': + $name = 'custom'; + break; + case 'blocksDestinationComponents': + $name = 'components'; + break; + case 'blocksDestinationVariations': + $name = 'variations'; + break; + case 'blocksDestinationWrapper': + $name = 'wrapper'; + break; + } + + switch ($type) { + case 'blocksSourceCustom': + case 'blocksSourceComponents': + case 'blocksSourceVariations': + case 'blocksSourceWrapper': + $path = self::joinPaths([...$flibsPath, ...$blocksPath, $name]); + + if (\getenv('ES_TEST')) { + $path = self::joinPaths([...$testsDataPath, ...$blocksPath, $name]); + } + break; + + case 'blocksDestinationCustom': + case 'blocksDestinationComponents': + case 'blocksDestinationVariations': + case 'blocksDestinationWrapper': + $path = self::joinPaths([...$blocksPath, $name]); + + if (\getenv('ES_TEST')) { + $path = self::joinPaths([$cliOutputPath, ...$blocksPath, $name]); + } + break; + } + + if (!$prefix) { + $prefix = $internalPrefix; + } + + $path = self::joinPaths([$prefix, $path, $sufix]); + + return \str_replace("{$sep}{$sep}", $sep, $path); + } + + /** + * Paths join + * + * @param array $paths Paths to join. + * + * @return string + */ + public static function joinPaths(array $paths): string + { + $sep = \DIRECTORY_SEPARATOR; + $path = \implode($sep, $paths); + + return \str_replace("{$sep}{$sep}", $sep, $path); + } } diff --git a/src/Helpers/StoreTrait.php b/src/Helpers/StoreTrait.php index 7e366a959..2eb42b285 100644 --- a/src/Helpers/StoreTrait.php +++ b/src/Helpers/StoreTrait.php @@ -34,6 +34,7 @@ trait StoreTrait 'variations' => [], 'settings' => [], 'styles' => [], + 'paths' => [], ]; /** @@ -43,7 +44,7 @@ trait StoreTrait */ public static function getStoreName(): string { - return \basename(\dirname(__DIR__, 5)); + return \basename(Components::getProjectPaths('root')); } /** @@ -573,4 +574,30 @@ public static function getStyles(): array { return self::getStore()['styles'] ?? []; } + + /** + * Set paths details. + * + * @return void + */ + public static function setPaths(): void + { + global $esBlocks; + + if (self::getStore()) { + foreach (Components::PROJECT_PATHS as $value) { + $esBlocks[self::getStoreName()]['paths'][$value] = Components::getProjectPaths($value); + } + } + } + + /** + * Get path details. + * + * @return array + */ + public static function getPaths(): array + { + return self::getStore()['paths'] ?? []; + } } diff --git a/src/I18n/I18nCli.php b/src/I18n/I18nCli.php index 7392d66c2..a31e551c9 100644 --- a/src/I18n/I18nCli.php +++ b/src/I18n/I18nCli.php @@ -12,19 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class I18nCli */ class I18nCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'I18n'; - /** * Get WPCLI command parent name * @@ -75,6 +69,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. @@ -82,6 +78,6 @@ public function __invoke(array $args, array $assocArgs) ->renameClassName($className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'I18n'), "{$className}.php", $assocArgs); } } diff --git a/src/Init/InitBlocksCli.php b/src/Init/InitBlocksCli.php new file mode 100644 index 000000000..c2fc8ef32 --- /dev/null +++ b/src/Init/InitBlocksCli.php @@ -0,0 +1,175 @@ + [], + UseAssetsCli::class => [], + UseStorybookCli::class => [], + UseGlobalAssetsCli::class => [], + UseWrapperCli::class => [], + UseManifestCli::class => [], + UseBlockCli::class => [ + 'default' => [ + 'button', + 'card', + 'group', + 'heading', + 'image', + 'lists', + 'paragraph', + ], + 'test' => [ + 'button', + 'heading', + ], + ], + UseComponentCli::class => [ + 'default' => [ + 'button', + 'card', + 'copyright', + 'drawer', + 'footer', + 'hamburger', + 'head', + 'header', + 'heading', + 'icon', + 'image', + 'layout-three-columns', + 'lists', + 'logo', + 'menu', + 'paragraph', + 'tracking-before-body-end', + 'tracking-head', + ], + 'test' => [ + 'button', + 'button-false', + 'heading', + 'layout', + 'responsiveVariables', + 'typography', + 'variables', + ], + ], + ]; + + /** + * Get WPCLI command parent name + * + * @return string + */ + public function getCommandParentName(): string + { + return CliInit::COMMAND_NAME; + } + + /** + * Get WPCLI command name + * + * @return string + */ + public function getCommandName(): string + { + return 'blocks'; + } + + /** + * Get WPCLI command doc + * + * @return array>|string> + */ + public function getDoc(): array + { + return [ + 'shortdesc' => 'Create all files for blocks to work.', + 'longdesc' => " + This command will copy all initial block, componens, manifests na service classes to you project in order to start using block editor. + + ## EXAMPLES + $ wp boilerplate create blocks_init + ", + ]; + } + + /* @phpstan-ignore-next-line */ + public function __invoke(array $args, array $assocArgs) + { + $groupOutput = $assocArgs['groupOutput'] ?? false; + + if (!$groupOutput) { + $this->getIntroText(); + } + + $this->cliLog(\esc_html__('Setting block editor files:', 'eightshift-libs'), 'C'); + + foreach (static::COMMANDS as $className => $items) { + $reflectionClass = new ReflectionClass($className); + $class = $reflectionClass->newInstanceArgs([$this->commandParentName]); + + if ($items) { + $innerItems = $items['default']; + + if (\getenv('ES_TEST')) { + $innerItems = $items['test']; + } + + $class->__invoke([], \array_merge( + $assocArgs, + [ + 'name' => \implode(",", $innerItems), + 'groupOutput' => true, + 'introOutput' => false, + 'checkDependency' => false, + ] + )); + } else { + $class->__invoke([], \array_merge( + $assocArgs, + [ + 'groupOutput' => true, + 'introOutput' => false, + 'checkDependency' => false, + ] + )); + } + } + + if (!$groupOutput) { + $this->cliLog('--------------------------------------------------'); + $this->cliLog('We have moved everything you need to start creating WordPress blocks. Please type `npm start` in your terminal to kickstart your assets bundle process.', "M"); + $this->cliLog('Happy developing!', "M"); + } + } +} diff --git a/src/Init/InitProjectCli.php b/src/Init/InitProjectCli.php new file mode 100644 index 000000000..0f41a6cef --- /dev/null +++ b/src/Init/InitProjectCli.php @@ -0,0 +1,138 @@ + + */ + public const COMMANDS = [ + [ + 'type' => 'theme', + 'label' => '', + 'items' => [ + InitThemeCli::class, + ], + ], + [ + 'type' => 'files', + 'label' => 'Setting project specific files:', + 'items' => [ + GitIgnoreCli::class, + SetupCli::class, + CiExcludeCli::class, + BuildCli::class, + ReadmeCli::class, + ConfigProjectCli::class, + ], + ], + ]; + + /** + * Get WPCLI command parent name + * + * @return string + */ + public function getCommandParentName(): string + { + return CliInit::COMMAND_NAME; + } + + /** + * Get WPCLI command name + * + * @return string + */ + public function getCommandName(): string + { + return 'project'; + } + + /** + * Get WPCLI command doc + * + * @return array>|string> + */ + public function getDoc(): array + { + return [ + 'shortdesc' => 'Kickstart your WordPress project with this simple command.', + 'longdesc' => $this->prepareLongDesc(" + ## USAGE + + Generates initial project setup with all files to run on the client project. + For example: gitignore file for the full WordPress project, continuous integration exclude files, etc. + + ## EXAMPLES + + # Setup project: + $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + "), + ]; + } + + /* @phpstan-ignore-next-line */ + public function __invoke(array $args, array $assocArgs) + { + $groupOutput = $assocArgs['groupOutput'] ?? false; + + if (!$groupOutput) { + $this->getIntroText(); + } + + foreach (static::COMMANDS as $item) { + $label = $item['label'] ?? ''; + $items = $item['items'] ?? []; + $type = $item['type'] ?? ''; + + if ($label) { + $this->cliLog($label, 'C'); + } + + if ($items) { + foreach ($items as $className) { + $reflectionClass = new ReflectionClass($className); + $class = $reflectionClass->newInstanceArgs([$this->commandParentName]); + + $class->__invoke([], \array_merge( + $assocArgs, + [ + 'groupOutput' => $type === 'theme', + 'introOutput' => false, + ] + )); + } + } + } + + if (!$groupOutput) { + $this->cliLog('--------------------------------------------------'); + $this->cliLog('We have moved everything you need, to start creating your awesome WordPress project. Please type `npm start` in your terminal to kickstart your assets bundle process.', "M"); + $this->cliLog('Happy developing!', "M"); + } + } +} diff --git a/src/Init/InitThemeCli.php b/src/Init/InitThemeCli.php new file mode 100644 index 000000000..7c5a6112b --- /dev/null +++ b/src/Init/InitThemeCli.php @@ -0,0 +1,140 @@ + + */ + public const COMMANDS = [ + [ + 'type' => 'sc', + 'label' => 'Setting service classes:', + 'items' => [ + ConfigCli::class, + MainCli::class, + ManifestCli::class, + EnqueueAdminCli::class, + EnqueueBlocksCli::class, + EnqueueThemeCli::class, + MenuCli::class, + ], + ], + [ + 'type' => 'blocks', + 'label' => '', + 'items' => [ + InitBlocksCli::class, + ], + ], + ]; + + /** + * Get WPCLI command parent name + * + * @return string + */ + public function getCommandParentName(): string + { + return CliInit::COMMAND_NAME; + } + + /** + * Get WPCLI command name + * + * @return string + */ + public function getCommandName(): string + { + return 'theme'; + } + + /** + * Get WPCLI command doc + * + * @return array>|string> + */ + public function getDoc(): array + { + return [ + 'shortdesc' => 'Kickstart your WordPress theme with this simple command.', + 'longdesc' => $this->prepareLongDesc(" + ## USAGE + + Generates initial theme setup with all files to create a custom theme. + + ## EXAMPLES + + # Setup theme: + $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + "), + ]; + } + + /* @phpstan-ignore-next-line */ + public function __invoke(array $args, array $assocArgs) + { + $groupOutput = $assocArgs['groupOutput'] ?? false; + + if (!$groupOutput) { + $this->getIntroText(); + } + + foreach (static::COMMANDS as $item) { + $label = $item['label'] ?? ''; + $items = $item['items'] ?? []; + $type = $item['type'] ?? ''; + + if ($label) { + $this->cliLog($label, 'C'); + } + + if ($items) { + foreach ($items as $className) { + $reflectionClass = new ReflectionClass($className); + $class = $reflectionClass->newInstanceArgs([$this->commandParentName]); + + $class->__invoke([], \array_merge( + $assocArgs, + [ + 'groupOutput' => $type === 'blocks', + 'introOutput' => false, + ] + )); + } + } + + $this->cliLog('--------------------------------------------------'); + } + + if (!$groupOutput) { + $this->cliLog('We have moved everything you need, to start creating your awesome WordPress theme. Please type `npm start` in your terminal to kickstart your assets bundle process.', "M"); + $this->cliLog('Happy developing!', "M"); + } + } +} diff --git a/src/Login/LoginCli.php b/src/Login/LoginCli.php index c7073ca30..19d181a6f 100644 --- a/src/Login/LoginCli.php +++ b/src/Login/LoginCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class LoginCli */ class LoginCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Login'; - /** * Get WPCLI command parent name * @@ -73,6 +69,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. @@ -80,6 +78,6 @@ public function __invoke(array $args, array $assocArgs) ->renameClassName($className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'Login'), "{$className}.php", $assocArgs); } } diff --git a/src/Main/MainCli.php b/src/Main/MainCli.php index 6008d0fef..3f68adbcb 100644 --- a/src/Main/MainCli.php +++ b/src/Main/MainCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class MainCli */ class MainCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Main'; - /** * Get WPCLI command parent name * @@ -74,11 +70,15 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + + $className = $this->getClassShortName(); + // Read the template contents, and replace the placeholders with provided variables. - $this->getExampleTemplate(__DIR__, $this->getClassShortName()) - ->renameClassName($this->getClassShortName()) + $this->getExampleTemplate(__DIR__, $className) + ->renameClassName($className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $this->getClassShortName(), $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'Main'), "{$className}.php", $assocArgs); } } diff --git a/src/Manifest/AbstractManifest.php b/src/Manifest/AbstractManifest.php index d05f8d350..0e4dab372 100644 --- a/src/Manifest/AbstractManifest.php +++ b/src/Manifest/AbstractManifest.php @@ -37,7 +37,7 @@ abstract class AbstractManifest implements ServiceInterface, ManifestInterface */ public function setAssetsManifestRaw(): void { - if (\defined('WP_CLI') && !\getenv('ES_TEST')) { + if (\defined('WP_CLI')) { return; } @@ -73,7 +73,7 @@ function ($manifestItem) { */ public function getAssetsManifestItem(string $key): string { - if (\defined('WP_CLI') && !\getenv('ES_TEST')) { + if (\defined('WP_CLI')) { return ''; } diff --git a/src/Manifest/ManifestCli.php b/src/Manifest/ManifestCli.php index fc43017b5..bc3bba400 100644 --- a/src/Manifest/ManifestCli.php +++ b/src/Manifest/ManifestCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class ManifestCli */ class ManifestCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Manifest'; - /** * Get WPCLI command parent name * @@ -73,6 +69,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. @@ -80,6 +78,6 @@ public function __invoke(array $args, array $assocArgs) ->renameClassName($className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'Manifest'), "{$className}.php", $assocArgs); } } diff --git a/src/Media/MediaCli.php b/src/Media/MediaCli.php index f540f24e0..ca68c8b92 100644 --- a/src/Media/MediaCli.php +++ b/src/Media/MediaCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class MediaCli */ class MediaCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Media'; - /** * Get WPCLI command parent name * @@ -73,6 +69,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. @@ -80,6 +78,6 @@ public function __invoke(array $args, array $assocArgs) ->renameClassName($className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'Media'), "{$className}.php", $assocArgs); } } diff --git a/src/Media/RegenerateWebPMediaCli.php b/src/Media/RegenerateWebPMediaCli.php index 66fe11ccb..b635828b0 100644 --- a/src/Media/RegenerateWebPMediaCli.php +++ b/src/Media/RegenerateWebPMediaCli.php @@ -11,7 +11,7 @@ namespace EightshiftLibs\Media; use EightshiftLibs\Cli\AbstractCli; -use EightshiftLibs\Cli\ParentGroups\CliWebp; +use EightshiftLibs\Cli\ParentGroups\CliRun; use WP_CLI; use WP_Query; @@ -32,7 +32,7 @@ class RegenerateWebPMediaCli extends AbstractCli */ public function getCommandParentName(): string { - return CliWebp::COMMAND_NAME; + return CliRun::COMMAND_NAME; } /** @@ -45,6 +45,21 @@ public function getCommandName(): string return 'regenerate_media'; } + /** + * Define default arguments. + * + * @return array + */ + public function getDefaultArgs(): array + { + return [ + 'action' => 'generate', + 'quality' => '80', + 'ids' => '', + 'force' => 'false', + ]; + } + /** * Get WPCLI command doc * @@ -60,6 +75,7 @@ public function getDoc(): array 'name' => 'action', 'description' => 'Action to use "generate" or "delete". Default: generate', 'optional' => true, + 'default' => $this->getDefaultArg('action'), 'options' => [ 'generate', 'delete', @@ -70,18 +86,21 @@ public function getDoc(): array 'name' => 'quality', 'description' => 'Quality of conversion 0-100. Default: 80', 'optional' => true, + 'default' => $this->getDefaultArg('quality'), ], [ 'type' => 'assoc', 'name' => 'ids', 'description' => 'Ids of attachment separated by comma.', 'optional' => true, + 'default' => $this->getDefaultArg('ids'), ], [ 'type' => 'assoc', 'name' => 'force', 'description' => 'Force generation no matter if the file exists. Default: false', 'optional' => true, + 'default' => $this->getDefaultArg('force'), 'options' => [ 'true', 'false', @@ -124,10 +143,12 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { - $quality = $assocArgs['quality'] ?? '80'; - $action = $assocArgs['action'] ?? 'generate'; - $ids = $assocArgs['ids'] ?? ''; - $force = isset($assocArgs['force']) ?: 'false'; // phpcs:ignore WordPress.PHP.DisallowShortTernary.Found + $this->getIntroText($assocArgs); + + $quality = $this->getArg($assocArgs, 'quality'); + $action = $this->getArg($assocArgs, 'action'); + $ids = $this->getArg($assocArgs, 'ids'); + $force = $this->getArg($assocArgs, 'force'); $args = []; diff --git a/src/Media/UseWebPMediaCli.php b/src/Media/UseWebPMediaCli.php index 5b55f38cb..7eb204ba9 100644 --- a/src/Media/UseWebPMediaCli.php +++ b/src/Media/UseWebPMediaCli.php @@ -11,7 +11,7 @@ namespace EightshiftLibs\Media; use EightshiftLibs\Cli\AbstractCli; -use EightshiftLibs\Cli\ParentGroups\CliWebp; +use EightshiftLibs\Cli\ParentGroups\CliRun; use WP_CLI; /** @@ -38,7 +38,7 @@ class UseWebPMediaCli extends AbstractCli */ public function getCommandParentName(): string { - return CliWebp::COMMAND_NAME; + return CliRun::COMMAND_NAME; } /** @@ -76,6 +76,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + if (\get_option(self::USE_WEBP_MEDIA_OPTION_NAME)) { \update_option(self::USE_WEBP_MEDIA_OPTION_NAME, false, true); diff --git a/src/Menu/MenuCli.php b/src/Menu/MenuCli.php index b95c5b0a5..0863edbcc 100644 --- a/src/Menu/MenuCli.php +++ b/src/Menu/MenuCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class MenuCli */ class MenuCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Menu'; - /** * Get WPCLI command parent name * @@ -73,6 +69,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. @@ -81,6 +79,6 @@ public function __invoke(array $args, array $assocArgs) ->renameNamespace($assocArgs) ->renameUse($assocArgs) ->renameTextDomain($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'Menu'), "{$className}.php", $assocArgs); } } diff --git a/src/ModifyAdminAppearance/ModifyAdminAppearanceCli.php b/src/ModifyAdminAppearance/ModifyAdminAppearanceCli.php index 42125c559..0a9a430d7 100644 --- a/src/ModifyAdminAppearance/ModifyAdminAppearanceCli.php +++ b/src/ModifyAdminAppearance/ModifyAdminAppearanceCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class ModifyAdminAppearanceCli */ class ModifyAdminAppearanceCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'ModifyAdminAppearance'; - /** * Get WPCLI command parent name * @@ -73,6 +69,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. @@ -80,6 +78,6 @@ public function __invoke(array $args, array $assocArgs) ->renameClassName($className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'ModifyAdminAppearance'), "{$className}.php", $assocArgs); } } diff --git a/src/Readme/ReadmeCli.php b/src/Readme/ReadmeCli.php index 50e97f618..5701fd19e 100644 --- a/src/Readme/ReadmeCli.php +++ b/src/Readme/ReadmeCli.php @@ -11,20 +11,14 @@ namespace EightshiftLibs\Readme; use EightshiftLibs\Cli\AbstractCli; -use EightshiftLibs\Cli\ParentGroups\CliProject; +use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class ReadmeCli */ class ReadmeCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR; - /** * Get WPCLI command parent name * @@ -32,7 +26,7 @@ class ReadmeCli extends AbstractCli */ public function getCommandParentName(): string { - return CliProject::COMMAND_NAME; + return CliCreate::COMMAND_NAME; } /** @@ -46,16 +40,14 @@ public function getCommandName(): string } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'root' => $args[1] ?? './', + 'path' => Components::getProjectPaths('projectRoot'), ]; } @@ -71,9 +63,10 @@ public function getDoc(): array 'synopsis' => [ [ 'type' => 'assoc', - 'name' => 'root', - 'description' => 'Define project root relative to initialization file of WP CLI.', + 'name' => 'path', + 'description' => 'Define absolute folder path where readme file will be created.', 'optional' => true, + 'default' => $this->getDefaultArg('path'), ], ], 'longdesc' => $this->prepareLongDesc(" @@ -98,11 +91,13 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Props. - $root = $assocArgs['root'] ?? static::OUTPUT_DIR; + $path = $this->getArg($assocArgs, 'path'); // Read the template contents, and replace the placeholders with provided variables. $this->getExampleTemplate(__DIR__, 'README.md') - ->outputWrite($root, 'README.md', $assocArgs); + ->outputWrite($path, 'README.md', $assocArgs); } } diff --git a/src/Rest/Fields/FieldCli.php b/src/Rest/Fields/FieldCli.php index 08e94484f..c80194248 100644 --- a/src/Rest/Fields/FieldCli.php +++ b/src/Rest/Fields/FieldCli.php @@ -12,20 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; -use WP_CLI; +use EightshiftLibs\Helpers\Components; /** * Class FieldCli */ class FieldCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Rest' . \DIRECTORY_SEPARATOR . 'Fields'; - /** * Get WPCLI command parent name * @@ -47,17 +40,15 @@ public function getCommandName(): string } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'field_name' => $args[1] ?? 'title', - 'object_type' => $args[2] ?? 'post', + 'field_name' => 'title', + 'object_type' => 'post', ]; } @@ -82,6 +73,7 @@ public function getDoc(): array 'name' => 'object_type', 'description' => 'Object(s) the field is being registered to. Example: post.', 'optional' => true, + 'default' => $this->getDefaultArg('object_type'), ], ], 'longdesc' => $this->prepareLongDesc(" @@ -105,15 +97,11 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { - // Get Props. - $fieldName = $this->prepareSlug($assocArgs['field_name'] ?? 'title'); + $this->getIntroText($assocArgs); - // If field name is empty throw error. - if (empty($fieldName)) { - WP_CLI::error("Empty slug provided, please set the slug using --endpoint_slug=\"slug-name\""); - } - - $objectType = $this->prepareSlug($assocArgs['object_type'] ?? 'post'); + // Get Props. + $fieldName = $this->getArg($assocArgs, 'field_name'); + $objectType = $this->prepareSlug($this->getArg($assocArgs, 'object_type')); // Get full class name. $className = $this->getFileName($fieldName); @@ -124,8 +112,8 @@ public function __invoke(array $args, array $assocArgs) ->renameClassNameWithPrefix($this->getClassShortName(), $className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->searchReplaceString('example-post-type', $objectType) - ->searchReplaceString('example-field', $fieldName) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->searchReplaceString($this->getArgTemplate('object_type'), $objectType) + ->searchReplaceString($this->getArgTemplate('field_name'), $fieldName) + ->outputWrite(Components::getProjectPaths('srcDestination', 'Rest' . \DIRECTORY_SEPARATOR . 'Fields'), "{$className}.php", $assocArgs); } } diff --git a/src/Rest/Fields/FieldExample.php b/src/Rest/Fields/FieldExample.php index cc86bb943..394cb56a5 100644 --- a/src/Rest/Fields/FieldExample.php +++ b/src/Rest/Fields/FieldExample.php @@ -27,7 +27,7 @@ class FieldExample extends AbstractField implements CallableFieldInterface */ protected function getObjectType() { - return 'example-post-type'; + return '%object_type%'; } /** @@ -37,7 +37,7 @@ protected function getObjectType() */ protected function getFieldName(): string { - return 'example-field'; + return '%field_name%'; } /** diff --git a/src/Rest/Routes/LoadMore/LoadMoreRouteCli.php b/src/Rest/Routes/LoadMore/LoadMoreRouteCli.php index 34ec31f4c..12d878eea 100644 --- a/src/Rest/Routes/LoadMore/LoadMoreRouteCli.php +++ b/src/Rest/Routes/LoadMore/LoadMoreRouteCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class LoadMoreRouteCli */ class LoadMoreRouteCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Rest' . \DIRECTORY_SEPARATOR . 'Routes'; - /** * Get WPCLI command parent name * @@ -43,18 +39,6 @@ public function getCommandName(): string return 'rest_route_load_more'; } - /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. - * - * @return array - */ - public function getDevelopArgs(array $args): array - { - return []; - } - /** * Get WPCLI command doc * @@ -85,16 +69,16 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. - $class = $this->getExampleTemplate(__DIR__, $className) + $this->getExampleTemplate(__DIR__, $className) ->renameClassName($className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->renameTextDomain($assocArgs); - - // Output final class to new file/folder and finish. - $class->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->renameTextDomain($assocArgs) + ->outputWrite(Components::getProjectPaths('srcDestination', 'Rest' . \DIRECTORY_SEPARATOR . 'Routes'), "{$className}.php", $assocArgs); } } diff --git a/src/Rest/Routes/RouteCli.php b/src/Rest/Routes/RouteCli.php index 3591842cf..8fbce1365 100644 --- a/src/Rest/Routes/RouteCli.php +++ b/src/Rest/Routes/RouteCli.php @@ -12,6 +12,7 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; use WP_CLI; /** @@ -19,13 +20,6 @@ */ class RouteCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'Rest' . \DIRECTORY_SEPARATOR . 'Routes'; - /** * Route method enum. * @@ -60,17 +54,15 @@ public function getCommandName(): string } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'endpoint_slug' => $args[1] ?? 'test', - 'method' => $args[2] ?? 'get', + 'endpoint_slug' => 'test', + 'method' => 'get', ]; } @@ -95,6 +87,7 @@ public function getDoc(): array 'name' => 'method', 'description' => 'HTTP verb must be one of: GET, POST, PATCH, PUT, or DELETE.', 'optional' => true, + 'default' => $this->getDefaultArg('method'), 'options' => [ 'GET', 'POST', @@ -125,15 +118,11 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { - // Get Props. - $endpointSlug = $this->prepareSlug($assocArgs['endpoint_slug'] ?? 'test-route'); - - // If slug is empty throw error. - if (empty($endpointSlug)) { - WP_CLI::error("Empty slug provided, please set the slug using --endpoint_slug=\"slug-name\""); - } + $this->getIntroText($assocArgs); - $method = \strtoupper($assocArgs['method'] ?? 'get'); + // Get Props. + $endpointSlug = $this->prepareSlug($this->getArg($assocArgs, 'endpoint_slug')); + $method = \strtoupper($this->getArg($assocArgs, 'method')); // Get full class name. $className = $this->getFileName($endpointSlug); @@ -151,8 +140,8 @@ public function __invoke(array $args, array $assocArgs) ->renameClassNameWithPrefix($this->getClassShortName(), $className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->searchReplaceString('/example-route', "/{$endpointSlug}") - ->searchReplaceString('static::READABLE', static::VERB_ENUM[$method]) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->searchReplaceString($this->getArgTemplate('endpoint_slug'), $endpointSlug) + ->searchReplaceString("'{$this->getArgTemplate('method')}'", static::VERB_ENUM[$method]) + ->outputWrite(Components::getProjectPaths('srcDestination', 'Rest' . \DIRECTORY_SEPARATOR . 'Routes'), "{$className}.php", $assocArgs); } } diff --git a/src/Rest/Routes/RouteExample.php b/src/Rest/Routes/RouteExample.php index 790f4e220..f56bf3c81 100644 --- a/src/Rest/Routes/RouteExample.php +++ b/src/Rest/Routes/RouteExample.php @@ -47,7 +47,7 @@ protected function getVersion(): string */ protected function getRouteName(): string { - return '/example-route'; + return '/%endpoint_slug%'; } /** @@ -58,7 +58,7 @@ protected function getRouteName(): string protected function getCallbackArguments(): array { return [ - 'methods' => static::READABLE, + 'methods' => '%method%', 'callback' => [$this, 'routeCallback'], 'permission_callback' => '__return_true' ]; diff --git a/src/Services/ServiceExampleCli.php b/src/Services/ServiceExampleCli.php index c284da3d2..5b6af6953 100644 --- a/src/Services/ServiceExampleCli.php +++ b/src/Services/ServiceExampleCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class ServiceExampleCli */ class ServiceExampleCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src'; - /** * Template name. */ @@ -49,17 +45,15 @@ public function getCommandName(): string } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'folder' => $args[1] ?? 'TestFolder/TMP', - 'file_name' => $args[2] ?? 'TestTest', + 'folder' => 'TestFolder/TMP', + 'file_name' => 'TestTest', ]; } @@ -107,9 +101,11 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Props. - $folder = $assocArgs['folder'] ?? ''; - $fileName = $this->prepareSlug($assocArgs['file_name'] ?? ''); + $folder = $this->getArg($assocArgs, 'folder'); + $fileName = $this->prepareSlug($this->getArg($assocArgs, 'file_name')); // Get full class name. $className = $this->getClassShortName(); @@ -132,6 +128,6 @@ function ($item) { ->renameNamespace($assocArgs) ->renameUse($assocArgs) ->searchReplaceString('\\Services;', "{$newNamespace};") - ->outputWrite(static::OUTPUT_DIR . $ds . $folder, $classNameNew, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', $folder), "{$classNameNew}.php", $assocArgs); } } diff --git a/src/Setup/SetupCli.php b/src/Setup/SetupCli.php index f7c5fad34..ef61cadf2 100644 --- a/src/Setup/SetupCli.php +++ b/src/Setup/SetupCli.php @@ -11,21 +11,14 @@ namespace EightshiftLibs\Setup; use EightshiftLibs\Cli\AbstractCli; -use EightshiftLibs\Cli\ParentGroups\CliProject; -use EightshiftLibs\Cli\ParentGroups\CliSetup; +use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class SetupCli */ class SetupCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR; - /** * Get WPCLI command parent name * @@ -33,7 +26,7 @@ class SetupCli extends AbstractCli */ public function getCommandParentName(): string { - return CliProject::COMMAND_NAME; + return CliCreate::COMMAND_NAME; } /** @@ -43,20 +36,20 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return CliSetup::COMMAND_NAME; + return 'setup'; } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'root' => $args[1] ?? './', + 'path' => Components::getProjectPaths('projectRoot'), + 'file_name' => 'setup.json', + 'source_path' => __DIR__, ]; } @@ -72,9 +65,17 @@ public function getDoc(): array 'synopsis' => [ [ 'type' => 'assoc', - 'name' => 'root', - 'description' => 'Define project root relative to initialization file of WP CLI.', + 'name' => 'path', + 'description' => 'Define absolute folder path where setup file will be created.', 'optional' => true, + 'default' => $this->getDefaultArg('path'), + ], + [ + 'type' => 'assoc', + 'name' => 'file_name', + 'description' => 'Define file that will be created in the path location.', + 'optional' => true, + 'default' => $this->getDefaultArg('file_name'), ], ], 'longdesc' => $this->prepareLongDesc(" @@ -99,11 +100,15 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Props. - $root = $assocArgs['root'] ?? static::OUTPUT_DIR; + $path = $this->getArg($assocArgs, 'path'); + $fileName = $this->getArg($assocArgs, 'file_name'); + $sourcePath = $this->getArg($assocArgs, 'source_path'); // Get setup.json example file, and create the one in the project. - $this->getExampleTemplate(__DIR__, 'setup.json') - ->outputWrite($root, 'setup.json', $assocArgs); + $this->getExampleTemplate($sourcePath, $fileName) + ->outputWrite($path, $fileName, $assocArgs); } } diff --git a/src/Setup/UpdateCli.php b/src/Setup/UpdateCli.php index cb1b934cf..903470944 100644 --- a/src/Setup/UpdateCli.php +++ b/src/Setup/UpdateCli.php @@ -13,6 +13,7 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\CliHelpers; use EightshiftLibs\Cli\ParentGroups\CliRun; +use EightshiftLibs\Helpers\Components; use WP_CLI; use WP_CLI\ExitException; @@ -41,6 +42,22 @@ public function getCommandName(): string return 'update'; } + /** + * Define default arguments. + * + * @return array + */ + public function getDefaultArgs(): array + { + return [ + 'skip_core' => 'false', + 'skip_plugins' => 'false', + 'skip_plugins_core' => 'false', + 'skip_plugins_github' => 'false', + 'skip_themes' => 'false', + ]; + } + /** * Get WPCLI command doc * @@ -56,6 +73,7 @@ public function getDoc(): array 'name' => 'skip_core', 'description' => 'If you want to skip core update/installation, provide bool on this attr.', 'optional' => true, + 'default' => $this->getDefaultArg('skip_core'), 'options' => [ 'true', 'false', @@ -66,6 +84,7 @@ public function getDoc(): array 'name' => 'skip_plugins', 'description' => 'If you want to skip all plugins update/installation, provide bool on this attr.', 'optional' => true, + 'default' => $this->getDefaultArg('skip_plugins'), 'options' => [ 'true', 'false', @@ -121,22 +140,19 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); $setupFilename = 'setup.json'; - if (\getenv('ES_TEST') !== false) { - $setupFilename = $this->getProjectConfigRootPath() . '/cliOutput/setup.json'; - } - try { $this->setup( - $this->getProjectConfigRootPath(), + Components::getProjectPaths('projectRoot'), [ - 'skip_core' => $assocArgs['skip_core'] ?? false, - 'skip_plugins' => $assocArgs['skip_plugins'] ?? false, - 'skip_plugins_core' => $assocArgs['skip_plugins_core'] ?? false, - 'skip_plugins_github' => $assocArgs['skip_plugins_github'] ?? false, - 'skip_themes' => $assocArgs['skip_themes'] ?? false, + 'skip_core' => $this->getArg($assocArgs, 'skip_core'), + 'skip_plugins' => $this->getArg($assocArgs, 'skip_plugins'), + 'skip_plugins_core' => $this->getArg($assocArgs, 'skip_plugins_core'), + 'skip_plugins_github' => $this->getArg($assocArgs, 'skip_plugins_github'), + 'skip_themes' => $this->getArg($assocArgs, 'skip_themes'), ], $setupFilename ); @@ -158,11 +174,11 @@ public function __invoke(array $args, array $assocArgs) private function setup(string $projectRootPath, array $args = [], string $setupFile = 'setup.json') { // Check if optional parameters exists. - $skipCore = $args['skip_core'] ?? false; - $skipPlugins = $args['skip_plugins'] ?? false; - $skipPluginsCore = $args['skip_plugins_core'] ?? false; - $skipPluginsGithub = $args['skip_plugins_github'] ?? false; - $skipThemes = $args['skip_themes'] ?? false; + $skipCore = $this->getArg($args, 'skip_core'); + $skipPlugins = $this->getArg($args, 'skip_plugins'); + $skipPluginsCore = $this->getArg($args, 'skip_plugins_core'); + $skipPluginsGithub = $this->getArg($args, 'skip_plugins_github'); + $skipThemes = $this->getArg($args, 'skip_themes'); // Change execution folder. if (!\is_dir($projectRootPath)) { diff --git a/src/ThemeOptions/ThemeOptionsCli.php b/src/ThemeOptions/ThemeOptionsCli.php index b64965712..75bb5a34a 100644 --- a/src/ThemeOptions/ThemeOptionsCli.php +++ b/src/ThemeOptions/ThemeOptionsCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class ThemeOptionsCli */ class ThemeOptionsCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'ThemeOptions'; - /** * Get WPCLI command parent name * @@ -77,6 +73,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. @@ -85,6 +83,6 @@ public function __invoke(array $args, array $assocArgs) ->renameNamespace($assocArgs) ->renameUse($assocArgs) ->renameTextDomain($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'ThemeOptions'), "{$className}.php", $assocArgs); } } diff --git a/src/View/EscapedViewCli.php b/src/View/EscapedViewCli.php index 2f2f6fa0b..468f0387c 100644 --- a/src/View/EscapedViewCli.php +++ b/src/View/EscapedViewCli.php @@ -12,17 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class EscapedViewCli */ class EscapedViewCli extends AbstractCli { - /** - * Output dir relative path. - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'View'; - /** * Get WPCLI command parent name * @@ -73,6 +69,8 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + $className = $this->getClassShortName(); // Read the template contents, and replace the placeholders with provided variables. @@ -80,6 +78,6 @@ public function __invoke(array $args, array $assocArgs) ->renameClassName($className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->outputWrite(Components::getProjectPaths('srcDestination', 'View'), "{$className}.php", $assocArgs); } } diff --git a/src/WpCli/WpCli.php b/src/WpCli/WpCli.php index ebcc695c3..c200b86f0 100644 --- a/src/WpCli/WpCli.php +++ b/src/WpCli/WpCli.php @@ -12,19 +12,13 @@ use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; /** * Class WpCli */ class WpCli extends AbstractCli { - /** - * Output dir relative path. - * - * @var string - */ - public const OUTPUT_DIR = 'src' . \DIRECTORY_SEPARATOR . 'WpCli'; - /** * Get WPCLI command parent name * @@ -46,16 +40,14 @@ public function getCommandName(): string } /** - * Define default develop props. - * - * @param string[] $args WPCLI eval-file arguments. + * Define default arguments. * * @return array */ - public function getDevelopArgs(array $args): array + public function getDefaultArgs(): array { return [ - 'command_name' => $args[1] ?? 'test', + 'command_name' => 'test', ]; } @@ -100,8 +92,10 @@ public function getDoc(): array /* @phpstan-ignore-next-line */ public function __invoke(array $args, array $assocArgs) { + $this->getIntroText($assocArgs); + // Get Props. - $commandName = $assocArgs['command_name'] ?? 'custom-command'; + $commandName = $this->getArg($assocArgs, 'command_name'); // Get full class name. $className = $this->getFileName($commandName); @@ -112,7 +106,7 @@ public function __invoke(array $args, array $assocArgs) ->renameClassNameWithPrefix($this->getClassShortName(true), $className) ->renameNamespace($assocArgs) ->renameUse($assocArgs) - ->searchReplaceString('command_name', $commandName) - ->outputWrite(static::OUTPUT_DIR, $className, $assocArgs); + ->searchReplaceString($this->getArgTemplate('command_name'), $commandName) + ->outputWrite(Components::getProjectPaths('srcDestination', 'WpCli'), "{$className}.php", $assocArgs); } } diff --git a/src/WpCli/WpCliExample.php b/src/WpCli/WpCliExample.php index 83cb71add..d7978d5a9 100644 --- a/src/WpCli/WpCliExample.php +++ b/src/WpCli/WpCliExample.php @@ -24,7 +24,7 @@ class WpCliExample implements ServiceCliInterface * * @var string */ - public const COMMAND_NAME = 'command_name'; + public const COMMAND_NAME = '%command_name%'; /** * Register method for WPCLI command diff --git a/tests/AdminMenus/AdminMenuCliTest.php b/tests/AdminMenus/AdminMenuCliTest.php index 37ac8a3de..9ed6ec739 100644 --- a/tests/AdminMenus/AdminMenuCliTest.php +++ b/tests/AdminMenus/AdminMenuCliTest.php @@ -3,6 +3,8 @@ namespace Tests\Unit\CustomPostType; use EightshiftLibs\AdminMenus\AdminMenuCli; +use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; use function Tests\setAfterEach; use function Tests\setBeforeEach; @@ -10,44 +12,120 @@ beforeEach(function () { setBeforeEach(); - $this->adminMenuCli = new AdminMenuCli('boilerplate'); + $this->mock = new AdminMenuCli('boilerplate'); }); afterEach(function () { setAfterEach(); + + unset($this->mock); +}); + +//---------------------------------------------------------------------------------// + +test('getCommandParentName will return correct value', function () { + expect($this->mock->getCommandParentName()) + ->toBeString() + ->toEqual(CliCreate::COMMAND_NAME); +}); + +//---------------------------------------------------------------------------------// + +test('getCommandName will return correct value', function () { + expect($this->mock->getCommandName()) + ->toBeString() + ->toEqual('admin_menu'); +}); + +//---------------------------------------------------------------------------------// + +test('getDefaultArgs will return correct array', function () { + expect($this->mock->getDefaultArgs()) + ->toBeArray() + ->toMatchArray([ + 'title' => 'Admin Title', + 'menu_title' => 'Admin Menu Title', + 'capability' => 'edit_posts', + 'menu_slug' => 'example-menu-slug', + 'menu_icon' => 'dashicons-admin-generic', + 'menu_position' => 100, + ]); +}); + +//---------------------------------------------------------------------------------// + +test('getDoc will return correct array', function () { + $docs = $this->mock->getDoc(); + + expect($docs) + ->toBeArray() + ->toHaveKeys(['shortdesc', 'synopsis', 'longdesc']) + ->and(count($docs['synopsis']))->toEqual(6) + ->and($docs['synopsis'][0]['name'])->toEqual('title') + ->and($docs['synopsis'][1]['name'])->toEqual('menu_title') + ->and($docs['synopsis'][2]['name'])->toEqual('capability') + ->and($docs['synopsis'][3]['name'])->toEqual('menu_slug') + ->and($docs['synopsis'][4]['name'])->toEqual('menu_icon') + ->and($docs['synopsis'][5]['name'])->toEqual('menu_position'); }); +//---------------------------------------------------------------------------------// -test('Admin menu CLI command will correctly copy the admin menu example class with defaults', function () { - $mock = $this->adminMenuCli; - $mock([], $mock->getDevelopArgs([])); +test('__invoke will will correctly copy example class with default args', function () { + $mock = $this->mock; + $mock([], $this->mock->getDefaultArgs([])); - // Check the output dir if the generated method is correctly generated. - $output = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/AdminMenus/TestTitleAdminMenu.php'); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('srcDestination', "AdminMenus{$sep}ExampleMenuSlugAdminMenu.php")); expect($output) - ->toContain('class TestTitleAdminMenu extends AbstractAdminMenu', 'Test Title') - ->not->toContain('product'); + ->toContain( + 'class ExampleMenuSlugAdminMenu', + 'Admin Title', + 'Admin Menu Title', + 'edit_posts', + 'example-menu-slug', + 'dashicons-admin-generic', + ) + ->not->toContain( + 'class AdminMenuExample', + '%title%', + '%menu_title%', + '%capability%', + '%menu_slug%', + '%menu_icon%', + ); }); -test('Admin menu CLI command will correctly copy the admin menu class with set arguments', function () { - $mock = $this->adminMenuCli; +test('__invoke will will correctly copy example class with custom args', function () { + $mock = $this->mock; $mock([], [ - 'title' => 'Reusable Blocks', - 'menu_title' => 'Reusable Blocks', - 'capability' => 'edit_reusable_blocks', - 'menu_slug' => 'reusable-blocks', - 'menu_icon' => 'dashicons-editor-table', + 'title' => 'Admin Title Test', + 'menu_title' => 'Admin Menu Title Test', + 'capability' => 'edit_posts_test', + 'menu_slug' => 'example-menu-slug-test', + 'menu_icon' => 'dashicons-admin-generic-test', + 'menu_position' => 200, ]); - // Check the output dir if the generated method is correctly generated. - $output = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/AdminMenus/ReusableBlocksAdminMenu.php'); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('srcDestination', "AdminMenus{$sep}ExampleMenuSlugTestAdminMenu.php")); expect($output) - ->toContain('class ReusableBlocksAdminMenu extends AbstractAdminMenu', 'Reusable Blocks', 'edit_reusable_blocks', '100', 'dashicons-editor-table') - ->not->toContain('dashicons-analytics'); -}); - -test('Admin menu CLI documentation is correct', function () { - expect($this->adminMenuCli->getDoc())->toBeArray(); + ->toContain( + 'class ExampleMenuSlugTestAdminMenu', + 'Admin Title Test', + 'Admin Menu Title Test', + 'edit_posts_test', + 'example-menu-slug-test', + 'dashicons-admin-generic-test', + ) + ->not->toContain( + 'class AdminMenuExample', + '%title%', + '%menu_title%', + '%capability%', + '%menu_slug%', + '%menu_icon%', + ); }); diff --git a/tests/AdminMenus/AdminMenuExampleTest.php b/tests/AdminMenus/AdminMenuExampleTest.php index 5da7b2fb4..45c9d6fc0 100644 --- a/tests/AdminMenus/AdminMenuExampleTest.php +++ b/tests/AdminMenus/AdminMenuExampleTest.php @@ -2,39 +2,55 @@ namespace Tests\Unit\AdminMenus; -use Brain\Monkey; -use Brain\Monkey\Actions; use Brain\Monkey\Functions; use EightshiftBoilerplate\AdminMenus\AdminMenuExample; -use function Tests\setupMocks; +use function Tests\buildTestBlocks; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -beforeEach(function() { - Monkey\setUp(); - setupMocks(); +beforeEach(function () { + setBeforeEach(); - $this->example = new AdminMenuExample(); + $this->mock = new AdminMenuExample(); }); -afterEach(function() { - Monkey\tearDown(); +afterEach(function () { + setAfterEach(); + + unset($this->mock); +}); + +//---------------------------------------------------------------------------------// + +test('register will load all hooks', function () { + + $this->mock->register(); + + expect(has_action('admin_menu', 'EightshiftBoilerplate\AdminMenus\AdminMenuExample->callback()')) + ->toBe(10); }); +//---------------------------------------------------------------------------------// -test('Register method will call admin_menu hook', function () { - Actions\expectAdded('admin_menu')->with(\Mockery::type('Closure')); +test('callback will load correct method', function () { - $this->example->register(); + $action = 'add_menu_page'; + Functions\when($action)->justReturn(putenv("ES_SIDEAFFECT_1={$action}")); - $this->assertSame(10, has_action('admin_menu', 'function()')); + $this->mock->callback(); + + expect(getenv('ES_SIDEAFFECT_1'))->toEqual($action); }); +//---------------------------------------------------------------------------------// + +test('processAdminMenu will echo component view', function () { -test('processAdminMenu will render the component', function() { - Functions\when('wp_nonce_field')->justReturn('nonce'); + buildTestBlocks(); ob_start(); - $this->example->processAdminMenu([]); + $this->mock->processAdminMenu([]); $contents = ob_get_clean(); expect($contents) @@ -42,18 +58,18 @@ ->toBe('
Hi!
'); }); -test('processAdminMenu will render the error if the component is missing', function() { - Functions\when('wp_nonce_field')->justReturn('nonce'); - - $faultyExample = new class extends AdminMenuExample { +test('processAdminMenu will echo error if component is missing', function () { + $mock = new class extends AdminMenuExample { protected function getViewComponent(): string { - return 'test'; + return 'missing'; } }; + buildTestBlocks(); + ob_start(); - $faultyExample->processAdminMenu([]); + $mock->processAdminMenu([]); $contents = ob_get_clean(); expect($contents) @@ -61,14 +77,33 @@ protected function getViewComponent(): string ->toContain('
Unable to locate component by path:');
 });
 
+// test('processAdminMenu will render the error if the component is missing', function() {
+// 	Functions\when('wp_nonce_field')->justReturn('nonce');
 
-test('getIcon will return the default icon', function() {
+// 	$faultyExample = new class extends AdminMenuExample {
+// 		protected function getViewComponent(): string
+// 		{
+// 			return 'test';
+// 		}
+// 	};
 
-	// We shouldn't do this, but the add_menu_page is called in a closure.
-	$method = new \ReflectionMethod('EightshiftBoilerplate\\AdminMenus\\AdminMenuExample', 'getIcon');
-	$method->setAccessible(true);
+// 	ob_start();
+// 	$faultyExample->processAdminMenu([]);
+// 	$contents = ob_get_clean();
 
-	expect($method->invoke(new AdminMenuExample()))
-		->not->toBeEmpty()
-		->toBe('%menu_icon%');
-});
+// 	expect($contents)
+// 		->not->toBeEmpty()
+// 		->toContain('
Unable to locate component by path:');
+// });
+
+
+// test('getIcon will return the default icon', function() {
+
+// 	// We shouldn't do this, but the add_menu_page is called in a closure.
+// 	$method = new \ReflectionMethod('EightshiftBoilerplate\\AdminMenus\\AdminMenuExample', 'getIcon');
+// 	$method->setAccessible(true);
+
+// 	expect($method->invoke(new AdminMenuExample()))
+// 		->not->toBeEmpty()
+// 		->toBe('%menu_icon%');
+// });
diff --git a/tests/AdminMenus/AdminReusableBlocksMenuCliTest.php b/tests/AdminMenus/AdminReusableBlocksMenuCliTest.php
index d9fa3b12f..19724f003 100644
--- a/tests/AdminMenus/AdminReusableBlocksMenuCliTest.php
+++ b/tests/AdminMenus/AdminReusableBlocksMenuCliTest.php
@@ -3,6 +3,8 @@
 namespace Tests\Unit\CustomPostType;
 
 use EightshiftLibs\AdminMenus\AdminReusableBlocksMenuCli;
+use EightshiftLibs\Cli\ParentGroups\CliCreate;
+use EightshiftLibs\Helpers\Components;
 
 use function Tests\setAfterEach;
 use function Tests\setBeforeEach;
@@ -10,50 +12,115 @@
 beforeEach(function () {
 	setBeforeEach();
 
-	$this->adminReusableBlocksMenuCli = new AdminReusableBlocksMenuCli('boilerplate');
+	$this->mock = new AdminReusableBlocksMenuCli('boilerplate');
 });
 
 afterEach(function () {
 	setAfterEach();
+
+	unset($this->mock);
 });
 
-test('Admin reusable blocks menu CLI command will correctly copy the admin reusable blocks menu example class with defaults', function () {
-	$mock = $this->adminReusableBlocksMenuCli;
-	$mock([], $mock->getDevelopArgs([]));
+//---------------------------------------------------------------------------------//
+
+test('getCommandParentName will return correct value', function () {
+	expect($this->mock->getCommandParentName())
+		->toBeString()
+		->toEqual(CliCreate::COMMAND_NAME);
+});
+
+//---------------------------------------------------------------------------------//
+
+test('getCommandName will return correct value', function () {
+	expect($this->mock->getCommandName())
+		->toBeString()
+		->toEqual('admin_reusable_blocks_menu');
+});
+
+//---------------------------------------------------------------------------------//
+
+test('getDefaultArgs will return correct array', function () {
+	expect($this->mock->getDefaultArgs())
+		->toBeArray()
+		->toMatchArray([
+			'title' => 'Reusable Blocks',
+			'menu_title' => 'Reusable Blocks',
+			'capability' => 'edit_posts',
+			'menu_icon' => 'dashicons-admin-table',
+			'menu_position' => 4,
+		]);
+});
 
-	// Check the output dir if the generated method is correctly generated.
-	$output = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/AdminMenus/AdminReusableBlocksMenu.php');
+//---------------------------------------------------------------------------------//
+
+test('getDoc will return correct array', function () {
+	$docs = $this->mock->getDoc();
+
+	expect($docs)
+		->toBeArray()
+		->toHaveKeys(['shortdesc', 'synopsis', 'longdesc'])
+		->and(count($docs['synopsis']))->toEqual(5)
+		->and($docs['synopsis'][0]['name'])->toEqual('title')
+		->and($docs['synopsis'][1]['name'])->toEqual('menu_title')
+		->and($docs['synopsis'][2]['name'])->toEqual('capability')
+		->and($docs['synopsis'][3]['name'])->toEqual('menu_icon')
+		->and($docs['synopsis'][4]['name'])->toEqual('menu_position');
+});
+
+//---------------------------------------------------------------------------------//
+
+test('__invoke will will correctly copy example class with default args', function () {
+	$mock = $this->mock;
+	$mock([], $this->mock->getDefaultArgs([]));
+
+	$sep = \DIRECTORY_SEPARATOR;
+	$output = \file_get_contents(Components::getProjectPaths('srcDestination', "AdminMenus{$sep}AdminReusableBlocksMenu.php"));
 
 	expect($output)
-		->not->toBeEmpty()
-		->toContain('class AdminReusableBlocksMenu extends AbstractAdminMenu')
-		->toContain('Reusable Blocks')
-		->not->toContain('product');
+		->toContain(
+			'class AdminReusableBlocksMenu',
+			'Reusable Blocks',
+			'Reusable Blocks',
+			'edit_posts',
+			'dashicons-admin-table',
+		)
+		->not->toContain(
+			'class AdminReusableBlocksMenuExample',
+			'%title%',
+			'%menu_title%',
+			'%capability%',
+			'%menu_icon%',
+			'%menu_position%',
+		);
 });
 
-test('Admin reusable blocks menu CLI command will correctly copy the admin reusable blocks menu class with set arguments', function () {
-	$mock = $this->adminReusableBlocksMenuCli;
+test('__invoke will will correctly copy example class with custom args', function () {
+	$mock = $this->mock;
 	$mock([], [
-		'title' => 'Reusable Blocks',
-		'menu_title' => 'Reusable Blocks',
-		'capability' => 'edit_posts',
-		'menu_slug' => 'edit.php?post_type=wp_block',
-		'menu_icon' => 'dashicons-editor-table',
+		'title' => 'Reusable Blocks Test',
+		'menu_title' => 'Reusable Blocks Test',
+		'capability' => 'edit_posts_test',
+		'menu_icon' => 'dashicons-admin-table-test',
+		'menu_position' => 5,
 	]);
 
-	// Check the output dir if the generated method is correctly generated.
-	$output = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/AdminMenus/AdminReusableBlocksMenu.php');
+	$sep = \DIRECTORY_SEPARATOR;
+	$output = \file_get_contents(Components::getProjectPaths('srcDestination', "AdminMenus{$sep}AdminReusableBlocksMenu.php"));
 
 	expect($output)
-		->not->toBeEmpty()
-		->toContain('class AdminReusableBlocksMenu extends AbstractAdminMenu')
-		->toContain('Reusable Blocks')
-		->toContain('edit_posts')
-		->toContain('4')
-		->toContain('dashicons-editor-table')
-		->not->toContain('dashicons-analytics');
-});
-
-test('Admin reusable blocks menu CLI documentation is correct', function () {
-	expect($this->adminReusableBlocksMenuCli->getDoc())->toBeArray();
+		->toContain(
+			'class AdminReusableBlocksMenu',
+			'Reusable Blocks Test',
+			'Reusable Blocks Test',
+			'edit_posts_test',
+			'dashicons-admin-table-test',
+		)
+		->not->toContain(
+			'class AdminReusableBlocksMenuExample',
+			'%title%',
+			'%menu_title%',
+			'%capability%',
+			'%menu_icon%',
+			'%menu_position%',
+		);
 });
diff --git a/tests/AdminMenus/AdminSubMenuCliTest.php b/tests/AdminMenus/AdminSubMenuCliTest.php
index 60e2c9780..29967c52d 100644
--- a/tests/AdminMenus/AdminSubMenuCliTest.php
+++ b/tests/AdminMenus/AdminSubMenuCliTest.php
@@ -3,6 +3,8 @@
 namespace Tests\Unit\CustomPostType;
 
 use EightshiftLibs\AdminMenus\AdminSubMenuCli;
+use EightshiftLibs\Cli\ParentGroups\CliCreate;
+use EightshiftLibs\Helpers\Components;
 
 use function Tests\setAfterEach;
 use function Tests\setBeforeEach;
@@ -10,43 +12,117 @@
 beforeEach(function () {
 	setBeforeEach();
 
-	$this->adminSubMenuCli = new AdminSubMenuCli('boilerplate');
+	$this->mock = new AdminSubMenuCli('boilerplate');
 });
 
 afterEach(function () {
 	setAfterEach();
+
+	unset($this->mock);
 });
 
-test('Admin submenu CLI command will correctly copy the admin menu example class with defaults', function () {
-	$mock = $this->adminSubMenuCli;
-	$mock([], $mock->getDevelopArgs([]));
+//---------------------------------------------------------------------------------//
+
+test('getCommandParentName will return correct value', function () {
+	expect($this->mock->getCommandParentName())
+		->toBeString()
+		->toEqual(CliCreate::COMMAND_NAME);
+});
+
+//---------------------------------------------------------------------------------//
+
+test('getCommandName will return correct value', function () {
+	expect($this->mock->getCommandName())
+		->toBeString()
+		->toEqual('admin_sub_menu');
+});
+
+//---------------------------------------------------------------------------------//
+
+test('getDefaultArgs will return correct array', function () {
+	expect($this->mock->getDefaultArgs())
+		->toBeArray()
+		->toMatchArray([
+			'parent_slug' => 'example-parent-slug',
+			'title' => 'Admin Title',
+			'menu_title' => 'Admin Sub Menu Title',
+			'capability' => 'edit_posts',
+			'menu_slug' => 'example-menu-slug',
+		]);
+});
 
-	// Check the output dir if the generated method is correctly generated.
-	$output = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/AdminMenus/TestAdminTitleAdminSubMenu.php');
+//---------------------------------------------------------------------------------//
+
+test('getDoc will return correct array', function () {
+	$docs = $this->mock->getDoc();
+
+	expect($docs)
+		->toBeArray()
+		->toHaveKeys(['shortdesc', 'synopsis', 'longdesc'])
+		->and(count($docs['synopsis']))->toEqual(5)
+		->and($docs['synopsis'][0]['name'])->toEqual('parent_slug')
+		->and($docs['synopsis'][1]['name'])->toEqual('title')
+		->and($docs['synopsis'][2]['name'])->toEqual('menu_title')
+		->and($docs['synopsis'][3]['name'])->toEqual('capability')
+		->and($docs['synopsis'][4]['name'])->toEqual('menu_slug');
+});
+
+//---------------------------------------------------------------------------------//
+
+test('__invoke will will correctly copy example class with default args', function () {
+	$mock = $this->mock;
+	$mock([], $this->mock->getDefaultArgs([]));
+
+	$sep = \DIRECTORY_SEPARATOR;
+	$output = \file_get_contents(Components::getProjectPaths('srcDestination', "AdminMenus{$sep}ExampleMenuSlugAdminSubMenu.php"));
 
 	expect($output)
-		->toContain('class TestAdminTitleAdminSubMenu extends AbstractAdminSubMenu', 'Test Admin Title')
-		->not->toContain('product');
+		->toContain(
+			'class ExampleMenuSlugAdminSubMenu',
+			'example-parent-slug',
+			'Admin Title',
+			'Admin Sub Menu Title',
+			'edit_posts',
+			'example-menu-slug',
+		)
+		->not->toContain(
+			'class AdminSubMenuExample',
+			'%parent_slug%',
+			'%title%',
+			'%menu_title%',
+			'%capability%',
+			'%menu_slug%',
+		);
 });
 
-test('Admin submenu CLI command will correctly copy the admin menu class with set arguments', function () {
-	$mock = $this->adminSubMenuCli;
+test('__invoke will will correctly copy example class with custom args', function () {
+	$mock = $this->mock;
 	$mock([], [
-		'parent_slug' => 'reusable-blocks',
-		'title' => 'Options',
-		'menu_title' => 'Options',
-		'capability' => 'edit_reusable_blocks',
-		'menu_slug' => 'reusable-block-options',
+		'parent_slug' => 'example-parent-slug-test',
+		'title' => 'Admin Title Test',
+		'menu_title' => 'Admin Sub Menu Title Test',
+		'capability' => 'edit_posts_test',
+		'menu_slug' => 'example-menu-slug-test',
 	]);
 
-	// Check the output dir if the generated method is correctly generated.
-	$output = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/AdminMenus/ReusableBlockOptionsAdminSubMenu.php');
+	$sep = \DIRECTORY_SEPARATOR;
+	$output = \file_get_contents(Components::getProjectPaths('srcDestination', "AdminMenus{$sep}ExampleMenuSlugTestAdminSubMenu.php"));
 
 	expect($output)
-		->toContain('class ReusableBlockOptionsAdminSubMenu extends AbstractAdminSubMenu', 'Options', 'edit_reusable_blocks')
-		->not->toContain('dashicons-analytics');
-});
-
-test('Admin submenu CLI documentation is correct', function () {
-	expect($this->adminSubMenuCli->getDoc())->toBeArray();
+		->toContain(
+			'class ExampleMenuSlugTestAdminSubMenu',
+			'example-parent-slug-test',
+			'Admin Title Test',
+			'Admin Sub Menu Title Test',
+			'edit_posts_test',
+			'example-menu-slug-test',
+		)
+		->not->toContain(
+			'class AdminSubMenuExample',
+			'%parent_slug%',
+			'%title%',
+			'%menu_title%',
+			'%capability%',
+			'%menu_slug%',
+		);
 });
diff --git a/tests/AnalyticsGdpr/AnalyticsGdprCliTest.php b/tests/AnalyticsGdpr/AnalyticsGdprCliTest.php
index d669bbd46..662085a70 100644
--- a/tests/AnalyticsGdpr/AnalyticsGdprCliTest.php
+++ b/tests/AnalyticsGdpr/AnalyticsGdprCliTest.php
@@ -4,38 +4,24 @@
 
 use EightshiftLibs\AnalyticsGdpr\AnalyticsGdprCli;
 
-use function Tests\deleteCliOutput;
-use function Tests\mock;
+use function Tests\setAfterEach;
+use function Tests\setBeforeEach;
 
-/**
- * Mock before tests.
- */
 beforeEach(function () {
-	$wpCliMock = mock('alias:WP_CLI');
+	setBeforeEach();
 
-	$wpCliMock
-		->shouldReceive('success')
-		->andReturnArg(0);
-
-	$wpCliMock
-		->shouldReceive('error')
-		->andReturnArg(0);
-
-	$this->analyticsGdpr = new AnalyticsGdprCli('boilerplate');
+	$this->mock = new AnalyticsGdprCli('boilerplate');
 });
 
-/**
- * Cleanup after tests.
- */
 afterEach(function () {
-	$output = dirname(__FILE__, 3) . '/cliOutput';
+	setAfterEach();
 
-	deleteCliOutput($output);
+	unset($this->mock);
 });
 
 
 test('Custom Analytics & GDPR Settings CLI command will correctly copy the AnalyticsGdpr class with defaults', function () {
-	$analyticsGdpr = $this->analyticsGdpr;
+	$analyticsGdpr = $this->mock;
 	$analyticsGdpr([], []);
 
 	// Check the output dir if the generated method is correctly generated.
@@ -55,7 +41,7 @@
 });
 
 test('Custom GDPR settings CLI documentation is correct', function () {
-	$analyticsGdpr = $this->analyticsGdpr;
+	$analyticsGdpr = $this->mock;
 
 	$documentation = $analyticsGdpr->getDoc();
 
diff --git a/tests/BlockPatterns/BlockPatternCliTest.php b/tests/BlockPatterns/BlockPatternCliTest.php
index f7713378d..7d9d3c938 100644
--- a/tests/BlockPatterns/BlockPatternCliTest.php
+++ b/tests/BlockPatterns/BlockPatternCliTest.php
@@ -4,95 +4,115 @@
 
 use EightshiftLibs\BlockPatterns\BlockPatternCli;
 
-use function Tests\deleteCliOutput;
-use function Tests\mock;
+use function Tests\setAfterEach;
+use function Tests\setBeforeEach;
+use function Tests\getCliOutputPath;
 
-/**
- * Mock before tests.
- */
 beforeEach(function () {
-	$wpCliMock = mock('alias:WP_CLI');
+	setBeforeEach();
 
-	$wpCliMock
-		->shouldReceive('success')
-		->andReturnArg(0);
-
-	$wpCliMock
-		->shouldReceive('error')
-		->andReturnArg(0);
-
-	$this->blockPattern = new BlockPatternCli('boilerplate');
+	$this->mock = new BlockPatternCli('boilerplate');
 });
 
-/**
- * Cleanup after tests.
- */
 afterEach(function () {
-	deleteCliOutput();
+	setAfterEach();
+
+	unset($this->mock);
 });
 
+//---------------------------------------------------------------------------------//
 
 test('Block pattern CLI command will correctly copy the Block Pattern class with defaults', function () {
-	$blockPattern = $this->blockPattern;
-	$developArgs = $blockPattern->getDevelopArgs([]);
-	$blockPattern([], $developArgs);
+	$mock = $this->mock;
+	$mock([], $this->mock->getDefaultArgs());
 
 	// Check the output dir if the generated method is correctly generated.
-	$generatedBlockPattern = \file_get_contents(\dirname(__FILE__, 3) . "/cliOutput/src/BlockPatterns/SomethingBlockPattern.php");
-
-	$this->assertStringContainsString('class SomethingBlockPattern extends AbstractBlockPattern', $generatedBlockPattern);
-
-	foreach ($developArgs as $developArg) {
-		$this->assertStringContainsString($developArg, $generatedBlockPattern);
-	}
-
-	$this->assertStringNotContainsString('example-content', $generatedBlockPattern);
-	$this->assertStringNotContainsString('example-description', $generatedBlockPattern);
-	$this->assertStringNotContainsString('example-title', $generatedBlockPattern);
-	$this->assertStringNotContainsString('example-name', $generatedBlockPattern);
+	$output = \file_get_contents(getCliOutputPath('src/BlockPatterns/ExampleTitleBlockPattern.php'));
+
+	expect($output)
+		->toContain(
+			'class ExampleTitleBlockPattern',
+			'example-title',
+			'example-name',
+			'example-description',
+			'example-content'
+		)
+		->not->toContain(
+			'class BlockPatternExample',
+			'%title%',
+			'%name%',
+			'%description%',
+			'%content%'
+		);
 });
 
 
 test('Block pattern CLI command will correctly copy the Block pattern class with set arguments', function () {
-	$blockPattern = $this->blockPattern;
-	$cliArgs = [
+	$mock = $this->mock;
+	$mock([], [
 		'title' => 'Your Own Thing',
 		'name' => 'eightshift-boilerplate/your-own-thing',
 		'description' => 'Description of the your own thing pattern',
 		'content' => 'this-one-has-some-content',
-	];
-	$blockPattern([], $cliArgs);
+	]);
 
 	// Check the output dir if the generated method is correctly generated.
-	$generatedBlockPattern = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/BlockPatterns/YourOwnThingBlockPattern.php');
-
-	$this->assertStringContainsString('class YourOwnThingBlockPattern extends AbstractBlockPattern', $generatedBlockPattern);
-	foreach ($cliArgs as $cliArg) {
-		$this->assertStringContainsString($cliArg, $generatedBlockPattern);
-	}
-
-	$this->assertStringNotContainsString('example-content', $generatedBlockPattern);
-	$this->assertStringNotContainsString('example-description', $generatedBlockPattern);
-	$this->assertStringNotContainsString('example-title', $generatedBlockPattern);
-	$this->assertStringNotContainsString('example-name', $generatedBlockPattern);
+	$output = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/BlockPatterns/YourOwnThingBlockPattern.php');
+
+	expect($output)
+	->toContain(
+		'class YourOwnThingBlockPattern',
+		'Your Own Thing',
+		'eightshift-boilerplate/your-own-thing',
+		'Description of the your own thing pattern',
+		'this-one-has-some-content'
+	)
+	->not->toContain(
+		'class BlockPatternExample',
+		'%title%',
+		'%name%',
+		'%description%',
+		'%content%'
+	);
 });
 
 test('Block pattern CLI command will generate a name from title if "name" argument is not provided', function () {
-	$blockPattern = $this->blockPattern;
-	$cliArgs = [
+	$mock = $this->mock;
+	$mock([], [
 		'title' => 'Your Own Thing',
+		'name' => '',
 		'description' => 'Description of the your own thing pattern',
 		'content' => 'this-one-has-some-content',
-	];
-	$blockPattern([], $cliArgs);
-
-	// Check the output dir if the generated method is correctly generated.
-	$generatedBlockPattern = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/BlockPatterns/YourOwnThingBlockPattern.php');
-
-	$this->assertStringContainsString('eightshift-boilerplate/your-own-thing', $generatedBlockPattern);
+	]);
+
+	$output = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/BlockPatterns/YourOwnThingBlockPattern.php');
+
+	expect($output)
+	->toContain(
+		'class YourOwnThingBlockPattern',
+		'Your Own Thing',
+		'eightshift-boilerplate/your-own-thing',
+		'Description of the your own thing pattern',
+		'this-one-has-some-content'
+	)
+	->not->toContain(
+		'class BlockPatternExample',
+		'%title%',
+		'%name%',
+		'%description%',
+		'%content%'
+	);
 });
 
-
-test('Block Pattern documentation is correct', function () {
-	expect($this->blockPattern->getDoc())->toBeArray();
+test('getDoc will return correct array', function () {
+	$docs = $this->mock->getDoc();
+
+	expect($docs)
+		->toBeArray()
+		->toHaveKeys(['shortdesc', 'synopsis', 'longdesc'])
+		->and(count($docs['synopsis']))->toEqual(4)
+		->and($docs['synopsis'][0]['name'])->toEqual('title')
+		->and($docs['synopsis'][1]['name'])->toEqual('name')
+		->and($docs['synopsis'][2]['name'])->toEqual('description')
+		->and($docs['synopsis'][3]['name'])->toEqual('content');
 });
diff --git a/tests/Blocks/BlockCliTest.php b/tests/Blocks/BlockCliTest.php
index 53cd5cbd9..bf9d749f8 100644
--- a/tests/Blocks/BlockCliTest.php
+++ b/tests/Blocks/BlockCliTest.php
@@ -2,71 +2,55 @@
 
 namespace Tests\Unit\Block;
 
-use EightshiftLibs\Blocks\BlockCli;
+use EightshiftLibs\Blocks\UseBlockCli;
+
+use EightshiftLibs\Helpers\Components;
+use Exception;
 
-use EightshiftLibs\Exception\InvalidBlock;
-use function Tests\mock;
 use function Tests\setAfterEach;
 use function Tests\setBeforeEach;
 
-/**
- * Mock before tests.
- */
 beforeEach(function () {
 	setBeforeEach();
 
-	$this->block = new BlockCli('boilerplate');
+	$this->mock = new UseBlockCli('boilerplate');
 });
 
-/**
- * Cleanup after tests.
- */
 afterEach(function () {
 	setAfterEach();
 
-	unset($this->block);
+	unset($this->mock);
 });
 
 test('Block CLI command will correctly copy the Block class with defaults', function () {
-	$blockMock = mock(BlockCli::class)
-		->makePartial()
-		->shouldReceive('getFrontendLibsBlockPath')
-		->andReturn(\dirname(__FILE__, 2) . '/data');
-
-	$mock = $blockMock->getMock();
-
-	$mock([], [$this->block->getDevelopArgs([])]);
-
-	$outputPath = \dirname(__FILE__, 3) . '/cliOutput/button/button.php';
+	$mock = $this->mock;
+	$mock([], $mock->getDefaultArgs());
 
-	// Check the output dir if the generated method is correctly generated.
-	$generatedBlock = \file_get_contents($outputPath);
+	$name = $this->mock->getDefaultArgs()['name'];
 
-	$this->assertStringContainsString('Template for the Button Block view.', $generatedBlock);
-	$this->assertStringContainsString('@package EightshiftBoilerplate', $generatedBlock);
-	$this->assertStringNotContainsString('Components::render(\'link\', $attributes)', $generatedBlock);
-	$this->assertFileExists($outputPath);
- });
+	$sep = \DIRECTORY_SEPARATOR;
+	$output = \file_get_contents(Components::getProjectPaths('blocksDestinationCustom', "{$name}{$sep}{$name}.php"));
 
-
-test('Block CLI command will run under custom command name', function () {
-	$block = $this->block;
-	$result = $block->getCommandName();
-
-	expect($result)->toContain('block');
+	expect($output)->toContain(
+		'Template for the Button Block view.',
+		'@package EightshiftLibs',
+	)
+	->not->toContain(
+		'@package EightshiftBoilerplate'
+	);
 });
 
 test('Block CLI documentation is correct', function () {
-	expect($this->block->getDoc())->toBeArray();
+	$mock = $this->mock;
+	expect($mock->getDoc())->toBeArray();
 });
 
 test('Block CLI command will fail if block doesn\'t exist', function () {
-	$blockMock = mock(BlockCli::class)
-		->makePartial()
-		->shouldReceive('getFrontendLibsBlockPath')
-		->andReturn(\dirname(__FILE__, 2) . '/data');
-
-	$mock = $blockMock->getMock();
-
-	$mock([], ['name' => 'testing']);
-})->expectException(InvalidBlock::class);
+	$mock = $this->mock;
+	$mock([], array_merge(
+		$mock->getDefaultArgs(),
+		[
+			'name' => 'testing'
+		]
+	));
+})->throws(Exception::class, 'You can find all available items on this list:');
diff --git a/tests/Blocks/BlockComponentCliTest.php b/tests/Blocks/BlockComponentCliTest.php
index 019f1eefc..fd79a20cf 100644
--- a/tests/Blocks/BlockComponentCliTest.php
+++ b/tests/Blocks/BlockComponentCliTest.php
@@ -2,69 +2,50 @@
 
 namespace Tests\Unit\Block;
 
-use EightshiftLibs\Blocks\BlockComponentCli;
+use EightshiftLibs\Blocks\UseComponentCli;
+use EightshiftLibs\Helpers\Components;
+use Exception;
 
-use EightshiftLibs\Exception\InvalidBlock;
-
-use function Tests\mock;
 use function Tests\setAfterEach;
 use function Tests\setBeforeEach;
 
-/**
- * Mock before tests.
- */
 beforeEach(function () {
 	setBeforeEach();
 
-	$this->component = new BlockComponentCli('boilerplate');
+	$this->mock = new UseComponentCli('boilerplate');
 });
 
-/**
- * Cleanup after tests.
- */
 afterEach(function () {
 	setAfterEach();
 
-	unset($this->component);
+	unset($this->mock);
 });
 
  test('Component CLI command will correctly copy the Component class with defaults', function () {
-	$componentMock = mock(BlockComponentCli::class)
-		->makePartial()
-		->shouldReceive('getFrontendLibsBlockPath')
-		->andReturn(\dirname(__FILE__, 2) . '/data');
-
-	$mock = $componentMock->getMock();
-
-	$mock([], [$this->component->getDevelopArgs([])]);
-
-	$outputPath = \dirname(__FILE__, 3) . '/cliOutput/button/button.php';
+	$mock = $this->mock;
+	$mock([], $this->mock->getDefaultArgs());
 
-	// Check the output dir if the generated method is correctly generated.
-	$generatedComponent = \file_get_contents($outputPath);
+	$name = $this->mock->getDefaultArgs()['name'];
 
-	$this->assertStringContainsString('
Hello!
', $generatedComponent); - $this->assertFileExists($outputPath); - }); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('blocksDestinationComponents', "{$name}{$sep}{$name}.php")); - test('Component CLI command will run under custom command name', function () { - $component = $this->component; - $result = $component->getCommandName(); - - $this->assertStringContainsString('component', $result); + expect($output)->toContain( + 'Fake component', + ); }); test('Component CLI documentation is correct', function () { - expect($this->component->getDoc())->toBeArray(); + $mock = $this->mock; + expect($mock->getDoc())->toBeArray(); }); test('Component CLI command will fail if Component doesn\'t exist', function () { - $componentMock = mock(BlockComponentCli::class) - ->makePartial() - ->shouldReceive('getFrontendLibsBlockPath') - ->andReturn(\dirname(__FILE__, 2) . '/data'); - - $mock = $componentMock->getMock(); - - $mock([], ['name' => 'testing']); -})->expectException(InvalidBlock::class); + $mock = $this->mock; + $mock([], array_merge( + $mock->getDefaultArgs(), + [ + 'name' => 'testing' + ] + )); +})->throws(Exception::class, 'Requested component with the name'); diff --git a/tests/Blocks/BlockVariationCliTest.php b/tests/Blocks/BlockVariationCliTest.php index 5e538e90e..14a49616c 100644 --- a/tests/Blocks/BlockVariationCliTest.php +++ b/tests/Blocks/BlockVariationCliTest.php @@ -2,70 +2,79 @@ namespace Tests\Unit\Block; -use EightshiftLibs\Blocks\BlockVariationCli; +use EightshiftLibs\Blocks\UseVariationCli; +use EightshiftLibs\Cli\ParentGroups\CliBlocks; +use EightshiftLibs\Helpers\Components; -use EightshiftLibs\Exception\InvalidBlock; - -use function Tests\mock; use function Tests\setAfterEach; use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { setBeforeEach(); - $this->variation = new BlockVariationCli('boilerplate'); + $this->mock = new UseVariationCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { setAfterEach(); - unset($this->variation); + unset($this->mock); }); - test('Variation CLI command will correctly copy the variation class with defaults', function () { - $variationMock = mock(BlockVariationCli::class) - ->makePartial() - ->shouldReceive('getFrontendLibsBlockPath') - ->andReturn(\dirname(__FILE__, 2) . '/data'); +//---------------------------------------------------------------------------------// + +test('getCommandParentName will return correct value', function () { + expect($this->mock->getCommandParentName()) + ->toBeString() + ->toEqual(CliBlocks::COMMAND_NAME); +}); - $mock = $variationMock->getMock(); +//---------------------------------------------------------------------------------// - $mock([], [$this->variation->getDevelopArgs([])]); +test('getCommandName will return correct value', function () { + expect($this->mock->getCommandName()) + ->toBeString() + ->toEqual('use_variation'); +}); - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/button-block/manifest.json'; +//---------------------------------------------------------------------------------// - // Check the output dir if the generated method is correctly generated. - $generatedVariation = \file_get_contents($outputPath); +test('getDefaultArgs will return correct array', function () { + expect($this->mock->getDefaultArgs()) + ->toBeArray() + ->toMatchArray([ + 'name' => 'button-block', + ]); +}); - $this->assertStringContainsString('"parentName": "button"', $generatedVariation); - $this->assertFileExists($outputPath); - }); +//---------------------------------------------------------------------------------// - test('Variation CLI command will run under custom command name', function () { - $variation = $this->variation; - $result = $variation->getCommandName(); +test('getDoc will return correct array', function () { + $docs = $this->mock->getDoc(); - expect($result) - ->toContain('variation'); + expect($docs) + ->toBeArray() + ->toHaveKeys(['shortdesc', 'synopsis', 'longdesc']) + ->and(count($docs['synopsis']))->toEqual(1) + ->and($docs['synopsis'][0]['name'])->toEqual('name'); }); -test('Variation CLI documentation is correct', function () { - expect($this->variation->getDoc())->toBeArray(); -}); +//---------------------------------------------------------------------------------// -test('Variation CLI command will fail if Variation doesn\'t exist', function () { - $variationMock = mock(BlockVariationCli::class) - ->makePartial() - ->shouldReceive('getFrontendLibsBlockPath') - ->andReturn(\dirname(__FILE__, 2) . '/data'); +test('__invoke will correctly copy example variation with default args', function () { + $mock = $this->mock; + $mock([], $mock->getDefaultArgs()); - $mock = $variationMock->getMock(); + $name = $this->mock->getDefaultArgs()['name']; - $mock([], ['name' => 'testing']); -})->expectException(InvalidBlock::class); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('blocksDestinationVariations', "{$name}{$sep}manifest.json")); + + expect($output) + ->toContain( + 'button', + 'button-full-width', + 'Button Full Width', + ) + ->and(\getenv('ES_CLI_LOG_HAPPENED'))->toContain('Please run'); +}); diff --git a/tests/Blocks/BlockWrapperCliTest.php b/tests/Blocks/BlockWrapperCliTest.php index d2268ebf3..93eefb65c 100644 --- a/tests/Blocks/BlockWrapperCliTest.php +++ b/tests/Blocks/BlockWrapperCliTest.php @@ -2,80 +2,40 @@ namespace Tests\Unit\Block; -use EightshiftLibs\Blocks\BlockWrapperCli; +use EightshiftLibs\Blocks\UseWrapperCli; +use EightshiftLibs\Helpers\Components; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); -$wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - -$wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - -$wpCliMock - ->shouldReceive('log') - ->andReturnArg(0); - -$this->wrapper = new BlockWrapperCli('boilerplate'); + $this->mock = new UseWrapperCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); -}); + setAfterEach(); - test('Wrapper CLI command will correctly copy the Wrapper class with defaults', function () { - $wrapperMock = mock(BlockWrapperCli::class) - ->makePartial() - ->shouldReceive('getFrontendLibsBlockPath') - ->andReturn(\dirname(__FILE__, 2) . '/data'); - - $mock = $wrapperMock->getMock(); - - $mock([], [$this->wrapper->getDevelopArgs([])]); + unset($this->mock); +}); - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/wrapper.php'; +test('Wrapper CLI command will correctly copy the Wrapper class with defaults', function () { + $mock = $this->mock; + $mock([], []); - // Check the output dir if the generated method is correctly generated. - $generatedWrapper = \file_get_contents($outputPath); + $output = \file_get_contents(Components::getProjectPaths('blocksDestinationWrapper', 'wrapper.php')); - $this->assertStringContainsString('
Wrapper!
', $generatedWrapper); - $this->assertFileExists($outputPath); + expect($output)->toContain('Fake wrapper'); }); test('Wrapper CLI command will run under custom command name', function () { - $wrapper = $this->wrapper; - $result = $wrapper->getCommandName(); + $mock = $this->mock; + $result = $mock->getCommandName(); expect($result)->toContain('wrapper'); }); test('Wrapper CLI documentation is correct', function () { - expect($this->wrapper->getDoc())->toBeArray(); -}); - -test('Wrapper CLI command will fail if Wrapper doesn\'t exist', function () { - $wrapperMock = mock(BlockWrapperCli::class) - ->makePartial() - ->shouldReceive('getFrontendLibsBlockPath') - ->andReturn(\dirname(__FILE__, 2) . '/data'); - - $mock = $wrapperMock->getMock(); - - $mock([], ['name' => 'testing']); - - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/testing/testing.php'; - - $this->assertFileDoesNotExist($outputPath); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/Blocks/BlocksAssetsCliTest.php b/tests/Blocks/BlocksAssetsCliTest.php new file mode 100644 index 000000000..f2b103fb3 --- /dev/null +++ b/tests/Blocks/BlocksAssetsCliTest.php @@ -0,0 +1,34 @@ +mock = new UseAssetsCli('boilerplate'); +}); + +afterEach(function () { + setAfterEach(); + + unset($this->mock); +}); + +test('Assets CLI command will correctly copy the Assets class with defaults', function () { + $mock = $this->mock; + $mock([], []); + + $output = \file_get_contents(Components::getProjectPaths('blocksAssetsDestination', 'assets.php')); + + expect($output)->toContain('Fake assets'); +}); + +test('Assets CLI documentation is correct', function () { + expect($this->mock->getDoc())->toBeArray(); +}); diff --git a/tests/Blocks/BlocksCliTest.php b/tests/Blocks/BlocksCliTest.php index 7b755ee93..2a67f0251 100644 --- a/tests/Blocks/BlocksCliTest.php +++ b/tests/Blocks/BlocksCliTest.php @@ -3,63 +3,46 @@ namespace Tests\Unit\Blocks; use EightshiftLibs\Blocks\BlocksCli; +use EightshiftLibs\Helpers\Components; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->blocks = new BlocksCli('boilerplate'); - $this->blocks->setTest(); + $this->mock = new BlocksCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); test('Blocks CLI command will correctly copy the Blocks class with defaults', function () { - $blocks = $this->blocks; - $blocks([], []); - - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/src/Blocks/Blocks.php'; + $mock = $this->mock; + $mock([], []); - // Check the output dir if the generated method is correctly generated. - $generatedBlocks = \file_get_contents($outputPath); + $output = \file_get_contents(Components::getProjectPaths('blocksDestination', "Blocks.php")); - $this->assertStringContainsString('class Blocks extends AbstractBlocks', $generatedBlocks); - $this->assertStringContainsString('@package EightshiftLibs\Blocks', $generatedBlocks); - $this->assertStringContainsString('namespace EightshiftLibs\Blocks', $generatedBlocks); - $this->assertStringNotContainsString('footer.php', $generatedBlocks); - $this->assertFileExists($outputPath); + $this->assertStringContainsString('class Blocks extends AbstractBlocks', $output); + $this->assertStringContainsString('@package EightshiftLibs\Blocks', $output); + $this->assertStringContainsString('namespace EightshiftLibs\Blocks', $output); + $this->assertStringNotContainsString('footer.php', $output); }); test('Blocks CLI command will correctly copy the Blocks class with set arguments', function () { - $blocks = $this->blocks; - $blocks([], [ + $mock = $this->mock; + $mock([], [ 'namespace' => 'CoolTheme', ]); - // Check the output dir if the generated method is correctly generated. - $generatedBlocks = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/Blocks/Blocks.php'); + $output = \file_get_contents(Components::getProjectPaths('blocksDestination', "Blocks.php")); - $this->assertStringContainsString('namespace CoolTheme\Blocks;', $generatedBlocks); + $this->assertStringContainsString('namespace CoolTheme\Blocks;', $output); }); test('Blocks CLI documentation is correct', function () { - expect($this->blocks->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/Blocks/BlocksExampleTest.php b/tests/Blocks/BlocksExampleTest.php index a3331b409..5ca292d4c 100644 --- a/tests/Blocks/BlocksExampleTest.php +++ b/tests/Blocks/BlocksExampleTest.php @@ -2,54 +2,35 @@ namespace Tests\Unit\Blocks; -use Brain\Monkey; use Brain\Monkey\Functions; use EightshiftBoilerplate\Blocks\BlocksExample; use EightshiftLibs\Exception\InvalidBlock; use EightshiftLibs\Helpers\Components; use WP_Block_Editor_Context; +use function Tests\buildTestBlocks; use function Tests\mock; -use function Tests\setupMocks; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; beforeEach(function() { - Monkey\setUp(); - setupMocks(); + setBeforeEach(); - $this->config = mock('alias:EightshiftBoilerplate\Config\Config'); - - Functions\when('is_wp_version_compatible')->justReturn(true); - - $this->blocksExample = new BlocksExample(); + $this->mock = new BlocksExample(); }); afterEach(function() { - Monkey\tearDown(); -}); - -test('Register method will call init hooks', function () { - - $this->config - ->shouldReceive('getProjectPath') - ->andReturn('tests/data'); + setAfterEach(); - $this->blocksExample->register(); - - expect(has_action('init', 'EightshiftBoilerplate\Blocks\BlocksExample->getBlocksDataFullRaw()'))->toBe(10); - expect(has_action('init', 'EightshiftBoilerplate\Blocks\BlocksExample->registerBlocks()'))->toBe(11); + unset($this->mock); }); -test('Register method will call block_categories_all hooks', function () { - - $this->blocksExample->register(); +test('Register method will call all register hooks', function () { + $this->mock->register(); expect(has_filter('block_categories_all', 'EightshiftBoilerplate\Blocks\BlocksExample->getCustomCategory()'))->toBe(10); -}); - -test('Register method will call after_setup_theme hooks', function () { - - $this->blocksExample->register(); - + expect(has_action('init', 'EightshiftBoilerplate\Blocks\BlocksExample->getBlocksDataFullRaw()'))->toBe(10); + expect(has_action('init', 'EightshiftBoilerplate\Blocks\BlocksExample->registerBlocks()'))->toBe(11); expect(has_action('after_setup_theme', 'EightshiftBoilerplate\Blocks\BlocksExample->addThemeSupport()'))->toBe(25); expect(has_action('after_setup_theme', 'EightshiftBoilerplate\Blocks\BlocksExample->changeEditorColorPalette()'))->toBe(11); }); @@ -62,7 +43,7 @@ putenv("{$envName}=true"); }); - $this->blocksExample->addThemeSupport(); + $this->mock->addThemeSupport(); expect(\getenv('ALIGN_WIDE'))->toBe('true'); }); @@ -73,11 +54,11 @@ $post = mock('WP_Post'); - $blocks = $this->blocksExample->getAllBlocksListOld(true, $post); + $blocks = $this->mock->getAllBlocksListOld(true, $post); expect($blocks)->toBeTrue(); - $blocks = $this->blocksExample->getAllBlocksListOld(false, $post); + $blocks = $this->mock->getAllBlocksListOld(false, $post); expect($blocks)->toBeFalse(); }); @@ -88,7 +69,7 @@ $blockContext->post = mock('WP_Post'); $blockContext->post->post_type = 'eightshift-forms'; - $blocks = $this->blocksExample->getAllBlocksList([], $blockContext); + $blocks = $this->mock->getAllBlocksList([], $blockContext); expect($blocks) ->toBeTrue(); @@ -100,7 +81,7 @@ $blockContext->post = mock('WP_Post'); $blockContext->post->post_type = 'post'; - $blocks = $this->blocksExample->getAllBlocksList(['test'], $blockContext); + $blocks = $this->mock->getAllBlocksList(['test'], $blockContext); expect($blocks) ->toBeArray() @@ -113,13 +94,11 @@ $post = mock(\WP_Post::class); - $this->config - ->shouldReceive('getProjectPath') - ->andReturn('tests/data'); + buildTestBlocks(); - $this->blocksExample->getBlocksDataFullRaw(); + $this->mock->getBlocksDataFullRaw(); - $list = $this->blocksExample->getAllBlocksListOld([], $post); + $list = $this->mock->getAllBlocksListOld([], $post); expect($list) ->toBeArray() @@ -134,11 +113,13 @@ $blockContext = mock(WP_Block_Editor_Context::class); $blockContext->post = null; + buildTestBlocks(); + (new BlocksExample())->getBlocksDataFullRaw(); Components::setConfigFlags(); - $blocks = $this->blocksExample->getAllBlocksList(false, $blockContext); + $blocks = $this->mock->getAllBlocksList(false, $blockContext); expect($blocks) ->toBeArray() @@ -151,11 +132,9 @@ 'blockName' => 'button', ]; - $this->config - ->shouldReceive('getProjectPath') - ->andReturn('tests/data'); + buildTestBlocks(); - $block = $this->blocksExample->render($blockManifest, ''); + $block = $this->mock->render($blockManifest, ''); expect($block) ->toBeString() @@ -169,11 +148,9 @@ 'blockName' => 'fake', ]; - $this->config - ->shouldReceive('getProjectPath') - ->andReturn('tests/data'); + buildTestBlocks(); - $this->blocksExample->render($blockManifest, ''); + $this->mock->render($blockManifest, ''); })->throws(InvalidBlock::class); test('Asserts that render will throw error if wrapper view is missing.', function () { @@ -182,20 +159,20 @@ 'blockName' => 'fake', ]; - $this->config - ->shouldReceive('getProjectPath') - ->andReturn('fake'); + buildTestBlocks(); - $this->blocksExample->render($blockManifest, ''); + $this->mock->render($blockManifest, ''); })->throws(InvalidBlock::class); test('Asserts that renderWrapperView will return a valid file.', function () { - $wrapperManifest = \dirname(__FILE__, 2) . '/data/src/Blocks/wrapper/wrapper.php'; + buildTestBlocks(); + + $wrapperFile = Components::getProjectPaths('blocksDestinationWrapper', 'wrapper.php'); \ob_start(); - $this->blocksExample->renderWrapperView($wrapperManifest, []); + $this->mock->renderWrapperView($wrapperFile, []); $content = \ob_get_clean(); expect(\trim($content)) @@ -204,13 +181,13 @@ }); test('Asserts that renderWrapperView will throw error if path is not valid.', function () { - $this->blocksExample->renderWrapperView('fake path', []); + $this->mock->renderWrapperView('fake path', []); })->throws(InvalidBlock::class); test('Asserts that getCustomCategory will return categories array.', function () { $blockContext = mock('WP_Block_Editor_Context'); - $category = $this->blocksExample->getCustomCategory([], $blockContext); + $category = $this->mock->getCustomCategory([], $blockContext); expect($category)->toBeArray(); @@ -222,7 +199,7 @@ test('Asserts that getCustomCategory will throw error if first argument is not array.', function () { $blockContext = mock('WP_Block_Editor_Context'); - $this->blocksExample->getCustomCategory('', $blockContext); + $this->mock->getCustomCategory('', $blockContext); })->throws(\TypeError::class); @@ -234,13 +211,11 @@ putenv("{$envName}=true"); }); - $this->config - ->shouldReceive('getProjectPath') - ->andReturn('tests/data'); + buildTestBlocks(); - $this->blocksExample->getBlocksDataFullRaw(); + $this->mock->getBlocksDataFullRaw(); - $this->blocksExample->changeEditorColorPalette(); + $this->mock->changeEditorColorPalette(); expect(\getenv('EDITOR_COLOR_PALETTE'))->toBe('true'); }); @@ -253,13 +228,11 @@ putenv('BLOCK_TYPE=true'); }); - $this->config - ->shouldReceive('getProjectPath') - ->andReturn('tests/data'); + buildTestBlocks(); - $this->blocksExample->getBlocksDataFullRaw(); + $this->mock->getBlocksDataFullRaw(); - $this->blocksExample->registerBlocks(); + $this->mock->registerBlocks(); expect(\getenv('BLOCK_TYPE'))->toBe('true'); }); @@ -267,7 +240,7 @@ test('getCustomCategoryOld method will return an array.', function () { $post = mock('WP_Post'); - $categoryList = $this->blocksExample->getCustomCategoryOld([], $post); + $categoryList = $this->mock->getCustomCategoryOld([], $post); expect($categoryList)->toBeArray(); @@ -279,9 +252,6 @@ }); test('filterBlocksContent method will return an array.', function () { - $this->config - ->shouldReceive('getProjectPath') - ->andReturn('tests/data'); $parsedBlock = [ 'blockName' => 'eightshift-boilerplate/jumbotron', @@ -350,15 +320,12 @@ ], ]; - $filteredBlockContent = $this->blocksExample->filterBlocksContent($parsedBlock, []); + $filteredBlockContent = $this->mock->filterBlocksContent($parsedBlock, []); expect($filteredBlockContent)->toBeArray(); }); test('filterBlocksContent method will not filter out the paragraph with content.', function () { - $this->config - ->shouldReceive('getProjectPath') - ->andReturn('tests/data'); $parsedBlock = [ 'blockName' => 'eightshift-boilerplate/paragraph', @@ -375,7 +342,7 @@ ], ]; - $filteredBlockContent = $this->blocksExample->filterBlocksContent($parsedBlock, []); + $filteredBlockContent = $this->mock->filterBlocksContent($parsedBlock, []); expect($filteredBlockContent) ->toBeArray() @@ -388,9 +355,6 @@ }); test('filterBlocksContent method will filter out the paragraph without content.', function () { - $this->config - ->shouldReceive('getProjectPath') - ->andReturn('tests/data'); $parsedBlock = [ 'blockName' => 'eightshift-boilerplate/paragraph', @@ -407,9 +371,10 @@ ]; // Set namespace data. - $this->blocksExample->getBlocksDataFullRaw(); + buildTestBlocks(); + $this->mock->getBlocksDataFullRaw(); - $filteredBlockContent = $this->blocksExample->filterBlocksContent($parsedBlock, []); + $filteredBlockContent = $this->mock->filterBlocksContent($parsedBlock, []); expect($filteredBlockContent) ->toBeArray() diff --git a/tests/Blocks/BlocksGlobalAssetsCliTest.php b/tests/Blocks/BlocksGlobalAssetsCliTest.php new file mode 100644 index 000000000..82a7b73c5 --- /dev/null +++ b/tests/Blocks/BlocksGlobalAssetsCliTest.php @@ -0,0 +1,34 @@ +mock = new UseGlobalAssetsCli('boilerplate'); +}); + +afterEach(function () { + setAfterEach(); + + unset($this->mock); +}); + +test('Assets CLI command will correctly copy the Global Assets class with defaults', function () { + $mock = $this->mock; + $mock([], []); + + $output = \file_get_contents(Components::getProjectPaths('blocksGlobalAssetsDestination', 'assets.php')); + + expect($output)->toContain('Global Assets example file.'); +}); + +test('Assets CLI documentation is correct', function () { + expect($this->mock->getDoc())->toBeArray(); +}); diff --git a/tests/Blocks/BlocksManifestCliTest.php b/tests/Blocks/BlocksManifestCliTest.php new file mode 100644 index 000000000..760bfe6b4 --- /dev/null +++ b/tests/Blocks/BlocksManifestCliTest.php @@ -0,0 +1,34 @@ +mock = new UseManifestCli('boilerplate'); +}); + +afterEach(function () { + setAfterEach(); + + unset($this->mock); +}); + +test('Manifest CLI command will correctly copy the manifest.json file with defaults', function () { + $mock = $this->mock; + $mock([], []); + + $output = \file_get_contents(Components::getProjectPaths('blocksSource', 'manifest.json')); + + expect($output)->toContain('namespace'); +}); + +test('Manifest CLI documentation is correct', function () { + expect($this->mock->getDoc())->toBeArray(); +}); diff --git a/tests/Blocks/BlocksStorybookCliTest.php b/tests/Blocks/BlocksStorybookCliTest.php new file mode 100644 index 000000000..1cbd998e8 --- /dev/null +++ b/tests/Blocks/BlocksStorybookCliTest.php @@ -0,0 +1,34 @@ +mock = new UseStorybookCli('boilerplate'); +}); + +afterEach(function () { + setAfterEach(); + + unset($this->mock); +}); + +test('Storybook CLI command will correctly copy the Storybook class with defaults', function () { + $mock = $this->mock; + $mock([], []); + + $output = \file_get_contents(Components::getProjectPaths('blocksStorybookDestination', 'storybook.php')); + + expect($output)->toContain('Storybook example file'); +}); + +test('Storybook CLI documentation is correct', function () { + expect($this->mock->getDoc())->toBeArray(); +}); diff --git a/tests/Build/BuildCliTest.php b/tests/Build/BuildCliTest.php index 16fe2fbd8..3ce94fa9c 100644 --- a/tests/Build/BuildCliTest.php +++ b/tests/Build/BuildCliTest.php @@ -3,66 +3,36 @@ namespace Tests\Unit\Build; use EightshiftLibs\Build\BuildCli; +use EightshiftLibs\Helpers\Components; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->buildCli = new BuildCli('boilerplate'); + $this->mock = new BuildCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); test('Build CLI will correctly copy the build script with defaults', function () { - $buildCli = $this->buildCli; - $buildCli([], [ - 'root' => './' - ]); - - // Check the output dir if the generated method is correctly generated. - $generatedFile = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/bin/build.sh'); - $this->assertStringNotContainsString('random string', $generatedFile); -}); + $sep = \DIRECTORY_SEPARATOR; -test('Build CLI will correctly copy the build script to a given folder', function () { - $buildCli = $this->buildCli; - $buildCli([], [ - 'root' => 'test/', + $mock = $this->mock; + $mock([], [ + 'path' => Components::getProjectPaths('cliOutput', 'bin'), ]); - // Check the output dir if the generated method is correctly generated. - $generatedFile = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/test/bin/build.sh'); - $this->assertStringNotContainsString('random string', $generatedFile); -}); + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "bin{$sep}build.sh")); -test('Build CLI documentation is correct', function () { - expect($this->buildCli->getDoc())->toBeArray(); + $this->assertStringNotContainsString('random string', $output); }); -test('getDevelopArgs correctly returns arguments', function() { - $buildCli = $this->buildCli; - - $arguments = $buildCli->getDevelopArgs([]); - - $this->assertIsArray($arguments); - $this->assertArrayHasKey('root', $arguments); - $this->assertSame($arguments['root'], './'); +test('Build CLI documentation is correct', function () { + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/CiExclude/CiExcludeCliTest.php b/tests/CiExclude/CiExcludeCliTest.php index 22a17b42f..a1c949fb0 100644 --- a/tests/CiExclude/CiExcludeCliTest.php +++ b/tests/CiExclude/CiExcludeCliTest.php @@ -3,79 +3,107 @@ namespace Tests\Unit\CiExclude; use EightshiftLibs\CiExclude\CiExcludeCli; +use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); -$wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - -$wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - -$this->ciexclude = new CiExcludeCli('boilerplate'); + $this->mock = new CiExcludeCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); -}); + setAfterEach(); -test('CiExclude CLI command will correctly copy the ci-exclude text file with defaults', function () { - $ciexclude = $this->ciexclude; - $ciexclude([], $ciexclude->getDevelopArgs([])); - - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/ci-exclude.txt'; + unset($this->mock); +}); - // Check the output dir if the generated method is correctly generated. - $generatedExclude = \file_get_contents($outputPath); +//---------------------------------------------------------------------------------// - $this->assertStringContainsString('eightshift-boilerplate', $generatedExclude); - $this->assertStringNotContainsString('footer.php', $generatedExclude); - $this->assertFileExists($outputPath); +test('getCommandParentName will return correct value', function () { + expect($this->mock->getCommandParentName()) + ->toBeString() + ->toEqual(CliCreate::COMMAND_NAME); }); -test('CiExclude CLI command will run under custom command name', function () { - $ciexclude = $this->ciexclude; - $result = $ciexclude->getCommandName(); +//---------------------------------------------------------------------------------// - expect($result)->toContain('ci_exclude'); +test('getCommandName will return correct value', function () { + expect($this->mock->getCommandName()) + ->toBeString() + ->toEqual('ci_exclude'); }); -test('CiExclude CLI command will correctly copy the ci-exclude file in the custom folder with set arguments', function () { - $ciexclude = $this->ciexclude; - $ciexclude([], [ - 'root' => './test', - ]); +//---------------------------------------------------------------------------------// - $this->assertFileExists(\dirname(__FILE__, 3) . '/cliOutput/test/ci-exclude.txt'); +test('getDefaultArgs will return correct array', function () { + $args = $this->mock->getDefaultArgs(); + + expect($args) + ->toBeArray() + ->toHaveKeys(['path', 'project_name', 'project_type']) + ->and($args['project_name'])->toEqual('eightshift-boilerplate') + ->and($args['project_type'])->toEqual('themes'); }); -test('CiExclude CLI command will correctly copy the ci-exclude file with set arguments', function () { - $ciexclude = $this->ciexclude; - $ciexclude([], [ - 'root' => './', - 'project_name' => 'coolPlugin', - 'project_type' => 'plugin', - ]); +//---------------------------------------------------------------------------------// - // Check the output dir if the generated method is correctly generated. - $generatedExclude = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/ci-exclude.txt'); +test('getDoc will return correct array', function () { + $docs = $this->mock->getDoc(); - $this->assertStringContainsString('/wp-content/plugin/coolPlugin/node_modules', $generatedExclude); + expect($docs) + ->toBeArray() + ->toHaveKeys(['shortdesc', 'synopsis', 'longdesc']) + ->and(count($docs['synopsis']))->toEqual(3) + ->and($docs['synopsis'][0]['name'])->toEqual('path') + ->and($docs['synopsis'][1]['name'])->toEqual('project_name') + ->and($docs['synopsis'][2]['name'])->toEqual('project_type'); }); +//---------------------------------------------------------------------------------// + +test('__invoke will will correctly copy example class with default args', function () { + $mock = $this->mock; + $mock([], array_merge( + $this->mock->getDefaultArgs(), + [ + 'path' => Components::getProjectPaths('cliOutput'), + ] + )); + + $output = \file_get_contents(Components::getProjectPaths('cliOutput', 'ci-exclude.txt')); + + expect($output) + ->toContain( + 'eightshift-boilerplate', + 'themes', + ) + ->not->toContain( + '%project_type%', + '%project_type%', + ); +}); + +test('__invoke will will correctly copy example class with custom args', function () { + $mock = $this->mock; + $mock([], [ + 'path' => Components::getProjectPaths('cliOutput'), + 'project_name' => 'test', + 'project_type' => 'plugins', + ]); -test('CiExclude CLI documentation is correct', function () { - expect($this->ciexclude->getDoc())->toBeArray(); + $output = \file_get_contents(Components::getProjectPaths('cliOutput', 'ci-exclude.txt')); + + expect($output) + ->toContain( + 'test', + 'plugins', + ) + ->not->toContain( + '%project_type%', + '%project_type%', + ); }); diff --git a/tests/Cli/AbstractCliTest.php b/tests/Cli/AbstractCliTest.php index 2dc118adc..d1d1e3449 100644 --- a/tests/Cli/AbstractCliTest.php +++ b/tests/Cli/AbstractCliTest.php @@ -97,6 +97,7 @@ public function getCommandName(): string 'name' => 'random', 'description' => 'Random description.', 'optional' => true, + 'default' => 'random', ], ], ]; @@ -148,63 +149,6 @@ public function getCommandName(): string $this->assertTrue(\array_key_exists('components/button-options.js', \array_flip($output)), 'components/button-options.js is missing.'); }); - -test('Getting frontend libs block path works', function() { - $abstractMock = new AbstractTest('test'); - - $output = $abstractMock->getFrontendLibsBlockPath(); - - $this->assertIsString($output); - $this->assertStringContainsString('node_modules/@eightshift/frontend-libs/blocks/init', $output); -}); - - -test('Getting frontend libs path works', function() { - $abstractMock = new AbstractTest('test'); - - $output = $abstractMock->getFrontendLibsPath('test'); - - $this->assertIsString($output); - $this->assertStringContainsString('node_modules/@eightshift/frontend-libs/test', $output); -}); - - -test('Getting libs path works', function() { - $abstractMock = new AbstractTest('test'); - - // The test one is covered. Let's see if we can get the one that will be used - putenv('ES_TEST'); - $output = $abstractMock->getLibsPath('test'); - - $this->assertIsString($output); - $this->assertStringContainsString('/vendor/infinum/eightshift-libs/test', $output); - - putenv('ES_TEST=1'); -}); - - -test('Project config root path works if dev is true', function() { - $abstractMock = new AbstractTest('test'); - - $outputDev = $abstractMock->getProjectConfigRootPath(true); - - $this->assertIsString($outputDev); -}); - - -test('Project config root path works if dev is false', function() { - putenv('ES_TEST'); - $abstractMock = new AbstractTest('test'); - - $outputProd = $abstractMock->getProjectConfigRootPath(false); - - $this->assertIsString($outputProd); - $this->assertSame('/', $outputProd); - - putenv('ES_TEST=1'); -}); - - test('Preparing slug works', function($slugs) { $abstractMock = new AbstractTest('test'); diff --git a/tests/Cli/CliInitProjectTest.php b/tests/Cli/CliInitProjectTest.php deleted file mode 100644 index f673ff4e4..000000000 --- a/tests/Cli/CliInitProjectTest.php +++ /dev/null @@ -1,85 +0,0 @@ -shouldReceive('success') - ->andReturnUsing(function ($message) { - putenv("SUCCESS={$message}"); - }); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('log') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('runcommand') - ->andReturn(putenv("INIT_CALLED=true")); - - $this->cliInitProject = new CliInitProject('setup_project'); -}); - -/** - * Cleanup after tests. - */ -afterEach(function () { - deleteCliOutput(); - - putenv('SHELL_CALLED'); - putenv('SUCCESS'); - putenv('INIT_CALLED'); - - Monkey\tearDown(); -}); - - -test('Initializing the project command returns correct command name', function () { - $commandName = $this->cliInitProject->getCommandName(); - - $this->assertIsString($commandName); - $this->assertSame('project', $commandName); -}); - - -test('CliInitProject CLI documentation is correct', function () { - expect($this->cliInitProject->getDoc())->toBeArray(); -}); - - -test('InitProject CLI command will correctly copy the project classes', function () { - $configProject = $this->cliInitProject; - $configProject([], []); - - $this->assertSame('true', \getenv('INIT_CALLED')); - $this->assertSame('All commands are finished.', \getenv('SUCCESS')); -}); - - -test('InitProject CLI command runs in case WP is not installed', function () { - redefine('shell_exec', always(true)); - redefine('function_exists', always(false)); - - $configProject = $this->cliInitProject; - $configProject([], []); - - $this->assertSame('true', \getenv('INIT_CALLED')); -}); diff --git a/tests/Cli/CliInitThemeTest.php b/tests/Cli/CliInitThemeTest.php deleted file mode 100644 index e189e2a5e..000000000 --- a/tests/Cli/CliInitThemeTest.php +++ /dev/null @@ -1,81 +0,0 @@ -shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('log') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('runcommand') - ->andReturn(putenv("THEME_INIT_CALLED=true")); - - $this->cliInitTheme = new CliInitTheme('setup_theme'); -}); - -/** - * Cleanup after tests. - */ -afterEach(function () { - deleteCliOutput(); - - Monkey\tearDown(); -}); - - -test('Initializing the project command returns correct command name', function () { - $commandName = $this->cliInitTheme->getCommandName(); - - $this->assertIsString($commandName); - $this->assertSame('theme', $commandName); -}); - - -test('CliInitTheme CLI documentation is correct', function () { - expect($this->cliInitTheme->getDoc())->toBeArray(); -}); - - -test('InitTheme CLI command will correctly copy the project classes', function () { - Functions\when('shell_exec')->returnArg(); - - $configProject = $this->cliInitTheme; - $configProject([], []); - - $this->assertSame('true', \getenv('THEME_INIT_CALLED')); -}); - - -test('InitTheme CLI command runs in case WP is not installed', function () { - redefine('shell_exec', always(true)); - redefine('function_exists', always(false)); - - $configProject = $this->cliInitTheme; - $configProject([], []); - - $this->assertSame('true', \getenv('THEME_INIT_CALLED')); -}); diff --git a/tests/Cli/CliResetTest.php b/tests/Cli/CliResetTest.php deleted file mode 100644 index 20e0f5bb6..000000000 --- a/tests/Cli/CliResetTest.php +++ /dev/null @@ -1,53 +0,0 @@ -shouldReceive('success') - ->andReturnUsing(function ($message) { - putenv("SUCCESS={$message}"); - }); - - $this->cliReset = new CliReset('boilerplate'); -}); - -/** - * Cleanup after tests. - */ -afterEach(function () { - putenv('SYSTEM_CALLED'); - putenv('SUCCESS'); - - Monkey\tearDown(); -}); - - -test('CliReset works', function () { - if (!\is_dir($this->cliReset->getOutputDir(''))) { - \mkdir($this->cliReset->getOutputDir('')); - } - - $cliReset = $this->cliReset; - $cliReset([], []); - - $this->assertDirectoryDoesNotExist($this->cliReset->getOutputDir('')); -}); - - -test('CliReset CLI documentation is correct', function () { - expect($this->cliReset->getDoc())->toBeArray(); -}); diff --git a/tests/Cli/CliRunAllTest.php b/tests/Cli/CliRunAllTest.php deleted file mode 100644 index 8a388a78f..000000000 --- a/tests/Cli/CliRunAllTest.php +++ /dev/null @@ -1,59 +0,0 @@ -shouldReceive('success') - ->andReturnUsing(function ($message) { - putenv("SUCCESS={$message}"); - }); - - $wpCliMock - ->shouldReceive('runcommand') - ->andReturnUsing(function ($message) { - putenv("RUNCOMMAND={$message}"); - }); - - $wpCliMock - ->shouldReceive('log') - ->andReturn('log'); - - $this->cliRunAll = new CliRunAll('boilerplate'); -}); - -/** - * Cleanup after tests. - */ -afterEach(function () { - putenv('SUCCESS'); - putenv('RUNCOMMAND'); - - Monkey\tearDown(); -}); - - -test('CliRunAll works', function () { - $cliRunAll = $this->cliRunAll; - $cliRunAll([], []); - - $this->assertSame('All commands are finished.', \getenv('SUCCESS')); -}); - - -test('CliRunAll CLI documentation is correct', function () { - expect($this->cliRunAll->getDoc())->toBeArray(); -}); diff --git a/tests/Cli/CliShowAllTest.php b/tests/Cli/CliShowAllTest.php deleted file mode 100644 index e4fef6872..000000000 --- a/tests/Cli/CliShowAllTest.php +++ /dev/null @@ -1,66 +0,0 @@ -shouldReceive('success') - ->andReturnUsing(function ($message) { - putenv("SUCCESS={$message}"); - }); - - $wpCliMock - ->shouldReceive('runcommand') - ->andReturnUsing(function ($message) { - putenv("RUNCOMMAND={$message}"); - }); - - $wpCliMock - ->shouldReceive('colorize') - ->andReturnUsing(function ($message) { - putenv("COLORIZE={$message}"); - }); - - $wpCliMock - ->shouldReceive('log') - ->andReturn('log'); - - $this->cliShowAll = new CliShowAll('boilerplate'); -}); - -/** - * Cleanup after tests. - */ -afterEach(function () { - putenv('SUCCESS'); - putenv('COLORIZE'); - putenv('RUNCOMMAND'); - - Monkey\tearDown(); -}); - - -test('CliShowAll works', function () { - $cliShowAll = $this->cliShowAll; - $cliShowAll([], []); - - $this->assertSame('All commands are outputted.', \getenv('SUCCESS')); - $this->assertSame('%mCommands for WP project only:%n', \getenv('COLORIZE')); // Last colorize command. -}); - - -test('CliShowAll CLI documentation is correct', function () { - expect($this->cliShowAll->getDoc())->toBeArray(); -}); diff --git a/tests/Cli/CliTest.php b/tests/Cli/CliTest.php index 1c8ad789b..a2623887a 100644 --- a/tests/Cli/CliTest.php +++ b/tests/Cli/CliTest.php @@ -2,18 +2,10 @@ namespace Tests\Unit\Cli; -use EightshiftLibs\Blocks\BlockCli; -use EightshiftLibs\Blocks\BlockComponentCli; -use EightshiftLibs\Blocks\BlocksStorybookCli; -use EightshiftLibs\Blocks\BlockVariationCli; -use EightshiftLibs\Blocks\BlockWrapperCli; use EightshiftLibs\Cli\Cli; use EightshiftLibs\Cli\CliReset; use EightshiftLibs\Cli\CliRunAll; use EightshiftLibs\Cli\CliShowAll; -use EightshiftLibs\Db\ExportCli; -use EightshiftLibs\Db\ImportCli; -use EightshiftLibs\Setup\UpdateCli; use function Tests\setAfterEach; use function Tests\setBeforeEach; @@ -34,29 +26,8 @@ setAfterEach(); }); - -test('Cli getDevelopClasses return correct class list', function () { - $developClasses = $this->cli->getDevelopClasses(); - - expect($developClasses) - ->toBeArray() - ->not->toHaveKey(BlockComponentCli::class) - ->not->toHaveKey(BlockWrapperCli::class) - ->not->toHaveKey(BlockVariationCli::class) - ->not->toHaveKey(BlockCli::class) - ->not->toHaveKey(BlocksStorybookCli::class) - ->not->toHaveKey(UpdateCli::class) - ->not->toHaveKey(ExportCli::class) - ->not->toHaveKey(ImportCli::class); - - expect(\count($developClasses)) - ->toBeInt() - ->toBe(42); // Dev classes count. -}); - - -test('Cli getPublicClasses return correct class list', function () { - $publicClasses = $this->cli->getPublicClasses(); +test('Cli getCommandsClasses return correct class list', function () { + $publicClasses = $this->cli->getCommandsClasses(); expect($publicClasses) ->toBeArray() @@ -66,27 +37,9 @@ expect(\count($publicClasses)) ->toBeInt() - ->toBe(48); // Public classes count. + ->toBe(51); // Public classes count. }); - -test('Running develop commands throws error if command name is not specified', function() { - $this->cli->loadDevelop(); - - $this->assertSame('First argument must be a valid command name.', \getenv('ES_CLI_ERROR_HAPPENED')); -}); - -test('Running develop commands runs a particular command successfully', function() { - $this->cli->loadDevelop(['create_menu']); - - // Check the output dir if the generated method is correctly generated. - $generatedMenu = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/Menu/Menu.php'); - $this->assertStringContainsString('class Menu extends AbstractMenu', $generatedMenu); - $this->assertStringContainsString('header_main_nav', $generatedMenu); - $this->assertStringNotContainsString('footer_main_nav', $generatedMenu); -}); - - test('Running load command works', function() { $this->cli->load('boilerplate'); diff --git a/tests/Columns/Media/WebPMediaColumnCliTest.php b/tests/Columns/Media/WebPMediaColumnCliTest.php index c5e36c2a8..23de82e26 100644 --- a/tests/Columns/Media/WebPMediaColumnCliTest.php +++ b/tests/Columns/Media/WebPMediaColumnCliTest.php @@ -34,7 +34,7 @@ test('Check if CLI command will correctly copy the WebPMediaColums class with defaults.', function () { $mock = $this->webPMediaColumnCliMock; - $mock([], $mock->getDevelopArgs([])); + $mock([], $mock->getDefaultArgs()); // Check the output dir if the generated method is correctly generated. $output = \file_get_contents(\dirname(__FILE__, 4) . '/cliOutput/src/Columns/Media/WebPMediaColumn.php'); diff --git a/tests/Config/ConfigCliTest.php b/tests/Config/ConfigCliTest.php index 86c22e810..0425f65bb 100644 --- a/tests/Config/ConfigCliTest.php +++ b/tests/Config/ConfigCliTest.php @@ -4,37 +4,24 @@ use EightshiftLibs\Config\ConfigCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->config = new ConfigCli('boilerplate'); + $this->mock = new ConfigCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); -}); + setAfterEach(); + unset($this->mock); +}); test('Custom acf meta CLI command will correctly copy the Config class with defaults', function () { - $config = $this->config; - $config([], $config->getDevelopArgs([])); + $config = $this->mock; + $config([], $config->getDefaultArgs()); // Check the output dir if the generated method is correctly generated. $generatedConfig = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/Config/Config.php'); @@ -47,7 +34,6 @@ $this->assertStringNotContainsString('someRandomMethod', $generatedConfig); }); - test('Custom acf meta CLI documentation is correct', function () { - expect($this->config->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/Config/ConfigExampleTest.php b/tests/Config/ConfigExampleTest.php index 3c9c3e809..9ce731147 100644 --- a/tests/Config/ConfigExampleTest.php +++ b/tests/Config/ConfigExampleTest.php @@ -2,54 +2,55 @@ namespace Tests\Unit\Config; -use Brain\Monkey; use EightshiftBoilerplate\Config\ConfigExample; -use function Tests\setupMocks; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; beforeEach(function() { - Monkey\setUp(); - setupMocks(); + setBeforeEach(); - $this->example = new ConfigExample(); + $this->mock = new ConfigExample(); }); -afterEach(function() { - Monkey\tearDown(); +afterEach(function () { + setAfterEach(); + + unset($this->mock); }); test('Is project name defined and a string', function () { - $this->assertNotEmpty($this->example::getProjectName()); - $this->assertIsString(\gettype($this->example::getProjectName())); + $this->assertNotEmpty($this->mock::getProjectName()); + $this->assertIsString(\gettype($this->mock::getProjectName())); }); test('Is project version defined and a string', function () { - $this->assertNotEmpty($this->example::getProjectVersion()); - $this->assertIsString(\gettype($this->example::getProjectVersion())); + $this->assertNotEmpty($this->mock::getProjectVersion()); + $this->assertIsString(\gettype($this->mock::getProjectVersion())); }); test('Is project REST namespace defined, a string and same as project name', function () { - $this->assertNotEmpty($this->example::getProjectRoutesNamespace()); - $this->assertIsString(\gettype($this->example::getProjectRoutesNamespace())); - $this->assertSame($this->example::getProjectName(), $this->example::getProjectRoutesNamespace()); + $this->assertNotEmpty($this->mock::getProjectRoutesNamespace()); + $this->assertIsString(\gettype($this->mock::getProjectRoutesNamespace())); + $this->assertSame($this->mock::getProjectName(), $this->mock::getProjectRoutesNamespace()); }); test('Is project REST route version defined and a string', function () { - $this->assertNotEmpty($this->example::getProjectRoutesVersion()); - $this->assertIsString(\gettype($this->example::getProjectRoutesVersion())); - $this->assertStringContainsString('v', $this->example::getProjectRoutesVersion()); + $this->assertNotEmpty($this->mock::getProjectRoutesVersion()); + $this->assertIsString(\gettype($this->mock::getProjectRoutesVersion())); + $this->assertStringContainsString('v', $this->mock::getProjectRoutesVersion()); }); test('Is project path defined and readable', function () { - $this->assertNotEmpty($this->example::getProjectPath()); - $this->assertDirectoryIsReadable($this->example::getProjectPath()); + $this->assertNotEmpty($this->mock::getProjectPath()); + $this->assertDirectoryIsReadable($this->mock::getProjectPath()); }); test('Is custom project path defined and readable', function () { - $this->assertNotEmpty($this->example::getProjectPath()); - $this->assertDirectoryIsReadable($this->example::getProjectPath('data/')); + $this->assertNotEmpty($this->mock::getProjectPath()); + $this->assertDirectoryIsReadable($this->mock::getProjectPath('tests')); }); test('If non-existent path throws exception', function () { - $this->example::getProjectPath('bla/'); + $this->mock::getProjectPath('bla/'); })->throws(\EightshiftLibs\Exception\InvalidPath::class); diff --git a/tests/ConfigProject/ConfigProjectCliTest.php b/tests/ConfigProject/ConfigProjectCliTest.php index f6bc6e566..ad73c1406 100644 --- a/tests/ConfigProject/ConfigProjectCliTest.php +++ b/tests/ConfigProject/ConfigProjectCliTest.php @@ -2,69 +2,76 @@ namespace Tests\Unit\ConfigProject; +use EightshiftLibs\Cli\ParentGroups\CliCreate; use EightshiftLibs\ConfigProject\ConfigProjectCli; +use EightshiftLibs\Helpers\Components; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->configProject = new ConfigProjectCli('boilerplate'); + $this->mock = new ConfigProjectCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); -test('ConfigProject CLI command will correctly copy the ConfigProject class with defaults', function () { - $configProject = $this->configProject; - $configProject([], $configProject->getDevelopArgs([])); +//---------------------------------------------------------------------------------// - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/wp-config-project.php'; +test('getCommandParentName will return correct value', function () { + expect($this->mock->getCommandParentName()) + ->toBeString() + ->toEqual(CliCreate::COMMAND_NAME); +}); - // Check the output dir if the generated method is correctly generated. - $generatedConfigProject = \file_get_contents($outputPath); +//---------------------------------------------------------------------------------// - $this->assertStringContainsString('!\defined(\'WP_ENVIRONMENT_TYPE\')', $generatedConfigProject); - $this->assertStringContainsString('@package EightshiftLibs', $generatedConfigProject); - $this->assertStringNotContainsString('footer.php', $generatedConfigProject); - $this->assertFileExists($outputPath); +test('getCommandName will return correct value', function () { + expect($this->mock->getCommandName()) + ->toBeString() + ->toEqual('config_project'); }); -test('ConfigProject CLI command will run under custom command name', function () { - $configProject = $this->configProject; - $result = $configProject->getCommandName(); +//---------------------------------------------------------------------------------// - $this->assertStringContainsString('config_project', $result); +test('getDefaultArgs will return correct array', function () { + expect($this->mock->getDefaultArgs()) + ->toBeArray() + ->toHaveKeys(['path']); }); -test('ConfigProject CLI command will correctly copy the ConfigProject class with set arguments', function () { - $configProject = $this->configProject; - $configProject([], [ - 'root' => './test', - ]); +//---------------------------------------------------------------------------------// - // Check the output dir if the generated method is correctly generated. - $generatedConfigProject = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/test/wp-config-project.php'); +test('getDoc will return correct array', function () { + $docs = $this->mock->getDoc(); - $this->assertStringContainsString('!\defined(\'WP_ENVIRONMENT_TYPE\')', $generatedConfigProject); + expect($docs) + ->toBeArray() + ->toHaveKeys(['shortdesc', 'synopsis', 'longdesc']) + ->and(count($docs['synopsis']))->toEqual(1) + ->and($docs['synopsis'][0]['name'])->toEqual('path'); }); -test('ConfigProject CLI documentation is correct', function () { - expect($this->configProject->getDoc())->toBeArray(); +//---------------------------------------------------------------------------------// + +test('__invoke will will correctly copy example class with default args', function () { + $mock = $this->mock; + $mock([], [ + 'path' => Components::getProjectPaths('cliOutput'), + ]); + + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "wp-config-project.php")); + + expect($output) + ->toContain( + 'WP_ENVIRONMENT_TYPE', + 'WP_POST_REVISIONS', + 'WP_DEBUG_DISPLAY', + ) + ->and(\getenv('ES_CLI_LOG_HAPPENED'))->toContain('Sets up WordPress vars and included files'); }); diff --git a/tests/CustomMeta/CustomMetaCliTest.php b/tests/CustomMeta/CustomMetaCliTest.php index ff4db5e28..52299be3a 100644 --- a/tests/CustomMeta/CustomMetaCliTest.php +++ b/tests/CustomMeta/CustomMetaCliTest.php @@ -4,37 +4,24 @@ use EightshiftLibs\CustomMeta\AcfMetaCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->customMeta = new AcfMetaCli('boilerplate'); + $this->mock = new AcfMetaCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); -}); + setAfterEach(); + unset($this->mock); +}); test('Custom acf meta CLI command will correctly copy the ACF meta class with defaults', function () { - $meta = $this->customMeta; - $meta([], $meta->getDevelopArgs([])); + $meta = $this->mock; + $meta([], $meta->getDefaultArgs()); // Check the output dir if the generated method is correctly generated. $generatedMeta = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/CustomMeta/TitleAcfMeta.php'); @@ -45,5 +32,5 @@ test('Custom acf meta CLI documentation is correct', function () { - expect($this->customMeta->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/CustomPostType/CustomPostTypeCliTest.php b/tests/CustomPostType/CustomPostTypeCliTest.php index 454156306..a3d815b89 100644 --- a/tests/CustomPostType/CustomPostTypeCliTest.php +++ b/tests/CustomPostType/CustomPostTypeCliTest.php @@ -2,183 +2,143 @@ namespace Tests\Unit\CustomPostType; +use EightshiftLibs\Cli\ParentGroups\CliCreate; use EightshiftLibs\CustomPostType\PostTypeCli; -use EightshiftLibs\Exception\InvalidNouns; -use function Tests\deleteCliOutput; -use function Tests\setupMocks; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; +use function Tests\getCliOutputFile; -/** - * Mock before tests. - */ beforeEach(function () { - setupMocks(); - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->cpt = new PostTypeCli('boilerplate'); + $this->mock = new PostTypeCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); -}); - -test('Custom post type CLI command will correctly copy the Custom post type class with defaults', function () { - $cpt = $this->cpt; - $cpt([], $cpt->getDevelopArgs([])); - - // Check the output dir if the generated method is correctly generated. - $generatedCPT = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/CustomPostType/ProductPostType.php'); + setAfterEach(); - expect($generatedCPT) - ->toContain('class ProductPostType extends AbstractPostType') - ->toContain('admin-settings') - ->not->toContain('dashicons-analytics'); + unset($this->mock); }); +//---------------------------------------------------------------------------------// -test('Custom post type CLI command will correctly copy the Custom post type class with set arguments', function () { - $cpt = $this->cpt; - $cpt([], [ - 'label' => 'Book', - 'slug' => 'book', - 'rewrite_url' => 'book', - 'rest_endpoint_slug' => 'books', - 'capability' => 'post', - 'menu_position' => 50, - 'menu_icon' => 'dashicons-book', - ]); - - // Check the output dir if the generated method is correctly generated. - $generatedCPT = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/CustomPostType/BookPostType.php'); - - $this->assertStringContainsString('class BookPostType extends AbstractPostType', $generatedCPT); - $this->assertStringContainsString('Book', $generatedCPT); - $this->assertStringContainsString('book', $generatedCPT); - $this->assertStringContainsString('book', $generatedCPT); - $this->assertStringContainsString('books', $generatedCPT); - $this->assertStringContainsString('post', $generatedCPT); - $this->assertStringContainsString('50', $generatedCPT); - $this->assertStringContainsString('dashicons-book', $generatedCPT); - $this->assertStringNotContainsString('dashicons-analytics', $generatedCPT); - - expect($generatedCPT) - ->toContain('class BookPostType extends AbstractPostType') - ->toContain('Book') - ->toContain('book') - ->toContain('books') - ->toContain('post') - ->toContain('50') - ->toContain('dashicons-book') - ->not->toContain('dashicons-analytics'); +test('getCommandParentName will return correct value', function () { + expect($this->mock->getCommandParentName()) + ->toBeString() + ->toEqual(CliCreate::COMMAND_NAME); }); +//---------------------------------------------------------------------------------// -test('Custom post type CLI documentation is correct', function () { - expect($this->cpt->getDoc())->toBeArray(); +test('getCommandName will return correct value', function () { + expect($this->mock->getCommandName()) + ->toBeString() + ->toEqual('post_type'); }); - -test('Registered post type will have properly created labels', function() { - - $cpt = $this->cpt; - $cpt([], [ - 'label' => 'Book', - 'slug' => 'book', - 'rewrite_url' => 'book', - 'rest_endpoint_slug' => 'books', - 'capability' => 'post', - 'menu_position' => 50, - 'menu_icon' => 'dashicons-book', - 'plural_label' => 'All books' - ]); - - // Check the output dir if the generated method is correctly generated. - $generatedCPT = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/CustomPostType/BookPostType.php'); - - expect($generatedCPT) - ->toContain('book') - ->toContain('books') - ->toContain('All books') - ->toContain('all books') - ->toContain('$labels') - ->toContain('$nouns[0]'); +//---------------------------------------------------------------------------------// + +test('getDefaultArgs will return correct array', function () { + expect($this->mock->getDefaultArgs()) + ->toBeArray() + ->toMatchArray([ + 'label' => 'Product', + 'plural_label' => 'Products', + 'slug' => 'product', + 'rewrite_url' => 'product', + 'rest_endpoint_slug' => 'products', + 'capability' => 'post', + 'menu_position' => 20, + 'menu_icon' => 'admin-settings', + ]); }); - -test('Registered post type will have properly created plural label if the plural is not defined', function() { - - $cpt = $this->cpt; - $cpt([], [ - 'label' => 'Book', - 'slug' => 'book', - 'rewrite_url' => 'book', - 'rest_endpoint_slug' => 'books', - 'capability' => 'post', - 'menu_position' => 50, - 'menu_icon' => 'dashicons-book', - ]); - - // Check the output dir if the generated method is correctly generated. - $generatedCPT = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/CustomPostType/BookPostType.php'); - - expect($generatedCPT) - ->toContain('book') - ->toContain('books') - ->toContain('Books'); +//---------------------------------------------------------------------------------// + +test('getDoc will return correct array', function () { + $docs = $this->mock->getDoc(); + + expect($docs) + ->toBeArray() + ->toHaveKeys(['shortdesc', 'synopsis', 'longdesc']) + ->and(count($docs['synopsis']))->toEqual(8) + ->and($docs['synopsis'][0]['name'])->toEqual('label') + ->and($docs['synopsis'][1]['name'])->toEqual('plural_label') + ->and($docs['synopsis'][2]['name'])->toEqual('slug') + ->and($docs['synopsis'][3]['name'])->toEqual('rewrite_url') + ->and($docs['synopsis'][4]['name'])->toEqual('rest_endpoint_slug') + ->and($docs['synopsis'][5]['name'])->toEqual('capability') + ->and($docs['synopsis'][6]['name'])->toEqual('menu_position') + ->and($docs['synopsis'][7]['name'])->toEqual('menu_icon'); }); +//---------------------------------------------------------------------------------// + +test('__invoke will will correctly copy example class with default args', function () { + $mock = $this->mock; + $mock([], $this->mock->getDefaultArgs()); + + expect(getCliOutputFile('src/CustomPostType/ProductPostType.php')) + ->toContain( + 'class ProductPostType', + 'Product', + 'Products', + 'product', + 'product', + 'products', + 'post', + '20', + 'admin-settings', + ) + ->not->toContain( + 'class PostTypeExample', + '%label%', + '%plural_label%', + '%slug%', + '%rewrite_url%', + '%rest_endpoint_slug%', + '%capability%', + '%menu_position%', + '%menu_icon%', + ); +}); -test('Missing required noun will trigger the invalid nouns exception', function() { - - $cpt = $this->cpt; - $cpt([], [ - 'label' => 'Book', - 'slug' => 'book', - 'rewrite_url' => 'book', - 'rest_endpoint_slug' => 'books', - 'capability' => 'post', - 'menu_position' => 50, - 'menu_icon' => 'dashicons-book', +test('__invoke will will correctly copy example class with custom args', function () { + $mock = $this->mock; + $mock([], [ + 'label' => 'Test', + 'plural_label' => 'Tests', + 'slug' => 'test', + 'rewrite_url' => 'test', + 'rest_endpoint_slug' => 'tests', + 'capability' => 'product', + 'menu_position' => 40, + 'menu_icon' => 'admin-panel', ]); - // Check the output dir if the generated method is correctly generated. - $generatedCPT = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/CustomPostType/BookPostType.php'); - - preg_match_all('/\$nouns\s=\s([^]]+)\]/m', $generatedCPT, $matches); - - $newClass = \str_replace($matches[0][0]. ';', '', $generatedCPT); - - /** - * This part is a bit of a dirty hack. - * - * We are accessing a protected method. We are doing this because it's being used - * in a CPT registration process, as a parameter generator. But we need to make sure that - * the correct exception will be thrown in case a noun array for label generation - * is missing or empty. - * Ideally this will never happen when using WP-CLI, because everything is set up - * for you, but if you manually copy class, and forget to add them, you'll get an - * error thrown. - * - * So we need to make sure that the error will indeed be thrown. - */ - require_once \dirname(__FILE__, 3) . '/cliOutput/src/CustomPostType/BookPostType.php'; - - $cptInstance = new \EightshiftLibs\CustomPostType\BookPostType(); - - $reflection = new \ReflectionMethod($cptInstance, 'getGeneratedLabels'); - $reflection->setAccessible(true); - $reflection->invoke($cptInstance, []); // This should trigger the error. -})->expectException(InvalidNouns::class); + expect(getCliOutputFile('src/CustomPostType/TestPostType.php')) + ->toContain( + 'class TestPostType', + 'Test', + 'Tests', + 'test', + 'test', + 'tests', + 'product', + '40', + 'admin-panel', + ) + ->not->toContain( + 'class PostTypeExample', + '%label%', + '%plural_label%', + '%slug%', + '%rewrite_url%', + '%rest_endpoint_slug%', + '%capability%', + '%menu_position%', + '%menu_icon%', + ); +}); diff --git a/tests/CustomTaxonomy/TaxonomyCliTest.php b/tests/CustomTaxonomy/TaxonomyCliTest.php index 5159be399..aca6844e7 100644 --- a/tests/CustomTaxonomy/TaxonomyCliTest.php +++ b/tests/CustomTaxonomy/TaxonomyCliTest.php @@ -2,167 +2,121 @@ namespace Tests\Unit\CustomTaxonomy; +use EightshiftLibs\Cli\ParentGroups\CliCreate; use EightshiftLibs\CustomTaxonomy\TaxonomyCli; -use EightshiftLibs\Exception\InvalidNouns; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; +use function Tests\getCliOutputFile; -use function Tests\deleteCliOutput; -use function Tests\setupMocks; -use function Tests\mock; - -/** - * Mock before tests. - */ beforeEach(function () { - setupMocks(); - $wpCliMock = mock('alias:WP_CLI'); - - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); + setBeforeEach(); - $this->tax = new TaxonomyCli('boilerplate'); + $this->mock = new TaxonomyCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); -}); + setAfterEach(); -test('Custom taxonomy CLI command will correctly copy the Custom taxonomy class with defaults', function () { - $tax = $this->tax; - $tax([], $tax->getDevelopArgs([])); + unset($this->mock); +}); - // Check the output dir if the generated method is correctly generated. - $generatedCPT = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/CustomTaxonomy/LocationTaxonomy.php'); +//---------------------------------------------------------------------------------// - expect($generatedCPT) - ->toContain('class LocationTaxonomy extends AbstractTaxonomy') - ->toContain('location') - ->toContain('post'); +test('getCommandParentName will return correct value', function () { + expect($this->mock->getCommandParentName()) + ->toBeString() + ->toEqual(CliCreate::COMMAND_NAME); }); -test('Custom taxonomy CLI command will correctly copy the Custom taxonomy class with set arguments', function () { - $tax = $this->tax; - $tax([], [ - 'label' => 'Book', - 'slug' => 'book', - 'rewrite_url' => 'book', - 'rest_endpoint_slug' => 'books', - 'capability' => 'post', - ]); - - // Check the output dir if the generated method is correctly generated. - $generatedCPT = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/CustomTaxonomy/BookTaxonomy.php'); +//---------------------------------------------------------------------------------// - expect($generatedCPT) - ->toContain('class BookTaxonomy extends AbstractTaxonom') - ->toContain('Book') - ->toContain('book') - ->toContain('books') - ->toContain('post') - ->not->toContain('dashicons-analytics'); +test('getCommandName will return correct value', function () { + expect($this->mock->getCommandName()) + ->toBeString() + ->toEqual('taxonomy'); }); -test('Custom taxonomy CLI documentation is correct', function () { - expect($this->tax->getDoc())->toBeArray(); +//---------------------------------------------------------------------------------// + +test('getDefaultArgs will return correct array', function () { + expect($this->mock->getDefaultArgs()) + ->toBeArray() + ->toMatchArray([ + 'label' => 'Location', + 'plural_label' => 'Locations', + 'slug' => 'location', + 'rest_endpoint_slug' => 'locations', + 'post_type_slug' => 'post', + ]); }); +//---------------------------------------------------------------------------------// -test('Registered taxonomy will have properly created labels', function() { - - $tax = $this->tax; - $tax([], [ - 'label' => 'Book', - 'slug' => 'book', - 'rewrite_url' => 'book', - 'rest_endpoint_slug' => 'books', - 'capability' => 'post', - 'menu_position' => 50, - 'menu_icon' => 'dashicons-book', - 'plural_label' => 'All books' - ]); - - // Check the output dir if the generated method is correctly generated. - $generatedCPT = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/CustomTaxonomy/BookTaxonomy.php'); +test('getDoc will return correct array', function () { + $docs = $this->mock->getDoc(); - expect($generatedCPT) - ->toContain('book') - ->toContain('books') - ->toContain('All books') - ->toContain('all books') - ->toContain('$labels') - ->toContain('$nouns[0]'); + expect($docs) + ->toBeArray() + ->toHaveKeys(['shortdesc', 'synopsis', 'longdesc']) + ->and(count($docs['synopsis']))->toEqual(5) + ->and($docs['synopsis'][0]['name'])->toEqual('label') + ->and($docs['synopsis'][1]['name'])->toEqual('plural_label') + ->and($docs['synopsis'][2]['name'])->toEqual('slug') + ->and($docs['synopsis'][3]['name'])->toEqual('rest_endpoint_slug') + ->and($docs['synopsis'][4]['name'])->toEqual('post_type_slug'); }); - -test('Registered taxonomy will have properly created plural label if the plural is not defined', function() { - - $tax = $this->tax; - $tax([], [ - 'label' => 'Book', - 'slug' => 'book', - 'rewrite_url' => 'book', - 'rest_endpoint_slug' => 'books', - 'capability' => 'post', - 'menu_position' => 50, - 'menu_icon' => 'dashicons-book', - ]); - - // Check the output dir if the generated method is correctly generated. - $generatedCPT = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/CustomTaxonomy/BookTaxonomy.php'); - - expect($generatedCPT) - ->toContain('book') - ->toContain('books') - ->toContain('Books'); +//---------------------------------------------------------------------------------// + +test('__invoke will will correctly copy example class with default args', function () { + $mock = $this->mock; + $mock([], $this->mock->getDefaultArgs()); + + expect(getCliOutputFile('src/CustomTaxonomy/LocationTaxonomy.php')) + ->toContain( + 'class LocationTaxonomy', + 'Location', + 'Locations', + 'location', + 'locations', + 'post' + ) + ->not->toContain( + 'class TaxonomyExample', + '%label%', + '%plural_label%', + '%slug%', + '%rest_endpoint_slug%', + '%post_type_slug%', + ); }); - -test('Missing required noun will trigger the invalid nouns exception', function() { - - $tax = $this->tax; - $tax([], [ - 'label' => 'Book', - 'slug' => 'book', - 'rewrite_url' => 'book', - 'rest_endpoint_slug' => 'books', - 'capability' => 'post', - 'menu_position' => 50, - 'menu_icon' => 'dashicons-book', +test('__invoke will will correctly copy example class with custom args', function () { + $mock = $this->mock; + $mock([], [ + 'label' => 'Test', + 'plural_label' => 'Tests', + 'slug' => 'test', + 'rest_endpoint_slug' => 'tests', + 'post_type_slug' => 'product', ]); - // Check the output dir if the generated method is correctly generated. - $generatedCPT = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/CustomTaxonomy/BookTaxonomy.php'); - - preg_match_all('/\$nouns\s=\s([^]]+)\]/m', $generatedCPT, $matches); - - $newClass = \str_replace($matches[0][0]. ';', '', $generatedCPT); - - /** - * This part is a bit of a dirty hack. - * - * We are accessing a protected method. We are doing this because it's being used - * in a CPT registration process, as a parameter generator. But we need to make sure that - * the correct exception will be thrown in case a noun array for label generation - * is missing or empty. - * Ideally this will never happen when using WP-CLI, because everything is set up - * for you, but if you manually copy class, and forget to add them, you'll get an - * error thrown. - * - * So we need to make sure that the error will indeed be thrown. - */ - require_once \dirname(__FILE__, 3) . '/cliOutput/src/CustomTaxonomy/BookTaxonomy.php'; - - $taxInstance = new \EightshiftLibs\CustomTaxonomy\BookTaxonomy(); - - $reflection = new \ReflectionMethod($taxInstance, 'getGeneratedLabels'); - $reflection->setAccessible(true); - $reflection->invoke($taxInstance, []); // This should trigger the error. -})->expectException(InvalidNouns::class); + expect(getCliOutputFile('src/CustomTaxonomy/TestTaxonomy.php')) + ->toContain( + 'class TestTaxonomy', + 'Test', + 'Tests', + 'test', + 'tests', + 'product' + ) + ->not->toContain( + 'class TaxonomyExample', + '%label%', + '%plural_label%', + '%slug%', + '%rest_endpoint_slug%', + '%post_type_slug%', + ); +}); diff --git a/tests/Db/DbExportTest.php b/tests/Db/DbExportTest.php index ce4fb2fa6..6b7f2aa42 100644 --- a/tests/Db/DbExportTest.php +++ b/tests/Db/DbExportTest.php @@ -4,45 +4,27 @@ use EightshiftLibs\Db\ExportCli; use Brain\Monkey\Functions; -use Exception; -use function Tests\setupMocks; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -beforeEach(function() { - $wpCliMock = mock('alias:WP_CLI'); +beforeEach(function () { + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('runcommand') - ->andReturn(putenv("INIT_CALLED=true")); - - $wpCliMock - ->shouldReceive('log') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnUsing( - function ($errorMessage) { - throw new Exception($errorMessage); - } - ); + $this->mock = new ExportCli('boilerplate'); +}); - setupMocks(); +afterEach(function () { + setAfterEach(); - $this->export = new ExportCli('boilerplate'); + unset($this->mock); }); - test('Exporting DB functionality fails if --skip_db parameter is not specified', function () { Functions\when('shell_exec')->returnArg(); - $dbExport = $this->export; + $dbExport = $this->mock; $dbExport([], []); - $this->assertSame('true', \getenv('INIT_CALLED')); + expect(\getenv('ES_CLI_SUCCESS_HAPPENED'))->toContain('Export complete!'); }); diff --git a/tests/Db/DbImportTest.php b/tests/Db/DbImportTest.php index ed05bdbf2..64a33cc61 100644 --- a/tests/Db/DbImportTest.php +++ b/tests/Db/DbImportTest.php @@ -2,54 +2,155 @@ namespace Tests\Unit\CustomPostType; +use EightshiftLibs\Cli\ParentGroups\CliRun; use EightshiftLibs\Db\ImportCli; +use EightshiftLibs\Helpers\Components; +use EightshiftLibs\Setup\SetupCli; use Exception; -use function Tests\setupMocks; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; beforeEach(function() { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); + $this->mock = new ImportCli('boilerplate'); +}); + +afterEach(function () { + setAfterEach(); - $wpCliMock - ->shouldReceive('error') - ->andReturnUsing( - function ($errorMessage) { - throw new Exception($errorMessage); - } - ); + unset($this->mock); +}); - setupMocks(); +//---------------------------------------------------------------------------------// - $this->import = new ImportCli('boilerplate'); +test('getCommandParentName will return correct value', function () { + expect($this->mock->getCommandParentName()) + ->toBeString() + ->toEqual(CliRun::COMMAND_NAME); }); +//---------------------------------------------------------------------------------// -test('Importing DB functionality fails if --from parameter is not specified', function () { - $dbImport = $this->import; +test('getCommandName will return correct value', function () { + expect($this->mock->getCommandName()) + ->toBeString() + ->toEqual('import'); +}); - $dbImport([], []); -})->throws(Exception::class, '--from parameter is mandatory. Please provide one url key from setup.json file.'); +//---------------------------------------------------------------------------------// +test('getDefaultArgs will return correct array', function () { + expect($this->mock->getDefaultArgs()) + ->toBeArray() + ->toHaveKeys(['from', 'to', 'setup_file']); +}); + +//---------------------------------------------------------------------------------// -test('Importing DB functionality fails if --to parameter is not specified', function () { - $dbImport = $this->import; +test('getDoc will return correct array', function () { + $docs = $this->mock->getDoc(); + + expect($docs) + ->toBeArray() + ->toHaveKeys(['shortdesc', 'synopsis', 'longdesc']) + ->and(count($docs['synopsis']))->toEqual(2) + ->and($docs['synopsis'][0]['name'])->toEqual('from') + ->and($docs['synopsis'][1]['name'])->toEqual('to'); +}); + +//---------------------------------------------------------------------------------// + +test('__invoke will log correct msg if import is success', function () { + (new SetupCli('boilerplate'))->__invoke([], [ + 'path' => Components::getProjectPaths('cliOutput', 'setup'), + 'source_path' => Components::getProjectPaths('testsData', 'setup'), + ]); + + $mock = $this->mock; + $mock([], array_merge( + $mock->getDefaultArgs(), + [ + 'from' => 'production', + 'to' => 'develop', + 'setup_file' => Components::getProjectPaths('cliOutput', 'setup' . \DIRECTORY_SEPARATOR . 'setup.json'), + ] + )); + + expect(\getenv('ES_CLI_SUCCESS_HAPPENED'))->toEqual('Finished! Success!'); +}); + +test('__invoke will fail if --from parameter is not specified', function () { + $mock = $this->mock; + $mock([], [ + 'to' => 'develop', + ]); +})->throws(Exception::class, '--from parameter is mandatory. Please provide one url key from setup.json file.'); - $dbImport([], [ +test('__invoke will fail if --to parameter is not specified', function () { + $mock = $this->mock; + $mock([], [ 'from' => 'staging' ]); })->throws(Exception::class, '--to parameter is mandatory. Please provide one url key from setup.json file.'); +test('__invoke will fail if setup.json is empty', function () { + (new SetupCli('boilerplate'))->__invoke([], [ + 'path' => Components::getProjectPaths('cliOutput', 'setup'), + 'file_name' => 'setup-empty.json', + 'source_path' => Components::getProjectPaths('testsData', 'setup'), + ]); + + $mock = $this->mock; + $mock([], [ + 'from' => 'production', + 'to' => 'develop', + 'setup_file' => Components::getProjectPaths('cliOutput', 'setup' . \DIRECTORY_SEPARATOR . 'setup-empty.json'), + ]); + +})->throws(Exception::class, 'Setup file is empty on this path: ' . Components::getProjectPaths('cliOutput', 'setup' . \DIRECTORY_SEPARATOR . 'setup-empty.json') . ''); + +test('__invoke will fail if setup.json is missing url keys', function () { + (new SetupCli('boilerplate'))->__invoke([], [ + 'path' => Components::getProjectPaths('cliOutput', 'setup'), + 'file_name' => 'setup-missing-urls.json', + 'source_path' => Components::getProjectPaths('testsData', 'setup'), + ]); + + $mock = $this->mock; + $mock([], [ + 'from' => 'production', + 'to' => 'develop', + 'setup_file' => Components::getProjectPaths('cliOutput', 'setup' . \DIRECTORY_SEPARATOR . 'setup-missing-urls.json'), + ]); -test('Importing DB functionality fails if setup.json is missing', function () { - $dbImport = $this->import; +})->throws(Exception::class, 'Urls key is missing or empty.'); - $dbImport([], [ - 'from' => 'staging', - 'to' => 'production' +test('__invoke will fail if setup.json is missing url "from" key', function () { + (new SetupCli('boilerplate'))->__invoke([], [ + 'path' => Components::getProjectPaths('cliOutput', 'setup'), + 'source_path' => Components::getProjectPaths('testsData', 'setup'), ]); -})->throws(Exception::class, 'setup.json is missing at this path: setup.json'); + + $mock = $this->mock; + $mock([], [ + 'from' => 'test', + 'to' => 'develop', + ]); + +})->throws(Exception::class, 'test key is missing or empty in urls.'); + +test('__invoke will fail if setup.json is missing url "to" key', function () { + (new SetupCli('boilerplate'))->__invoke([], [ + 'path' => Components::getProjectPaths('cliOutput', 'setup'), + 'source_path' => Components::getProjectPaths('testsData', 'setup'), + ]); + + $mock = $this->mock; + $mock([], [ + 'from' => 'production', + 'to' => 'test', + ]); + +})->throws(Exception::class, 'test key is missing or empty in urls.'); diff --git a/tests/Db/setup.json b/tests/Db/setup.json deleted file mode 100644 index 04a2dce84..000000000 --- a/tests/Db/setup.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "urls": { - "develop": "http://testing.test", - "staging": "https://testing-staging.com", - "production": "https://testing.com" - }, - "core": "5.6.1", - "plugins": { - "core": { - "query-monitor": "3.6.4", - }, - "github": { - "infinum/eightshift-gdpr": "1.0.1" - } - }, - "themes": {} -} diff --git a/tests/Enqueue/Admin/EnqueueAdminCliTest.php b/tests/Enqueue/Admin/EnqueueAdminCliTest.php index 1650df990..84e7de580 100644 --- a/tests/Enqueue/Admin/EnqueueAdminCliTest.php +++ b/tests/Enqueue/Admin/EnqueueAdminCliTest.php @@ -4,36 +4,24 @@ use EightshiftLibs\Enqueue\Admin\EnqueueAdminCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->enqueueAdmin = new EnqueueAdminCli('boilerplate'); + $this->mock = new EnqueueAdminCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(\dirname(__FILE__, 4) . '/cliOutput'); + setAfterEach(); + + unset($this->mock); }); test('Custom Enqueue Admin CLI command will correctly copy the Enqueue Admin class', function () { - $admin = $this->enqueueAdmin; - $admin([], $admin->getDevelopArgs([])); + $admin = $this->mock; + $admin([], $admin->getDefaultArgs()); // Check the output dir if the generated method is correctly generated. $generatedAdmin = \file_get_contents(\dirname(__FILE__, 4) . '/cliOutput/src/Enqueue/Admin/EnqueueAdmin.php'); @@ -45,5 +33,5 @@ test('Custom Enqueue Admin CLI documentation is correct', function () { - expect($this->enqueueAdmin->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/Enqueue/Blocks/EnqueueBlockCliTest.php b/tests/Enqueue/Blocks/EnqueueBlockCliTest.php index 252c0233b..08c2163d3 100644 --- a/tests/Enqueue/Blocks/EnqueueBlockCliTest.php +++ b/tests/Enqueue/Blocks/EnqueueBlockCliTest.php @@ -4,38 +4,26 @@ use EightshiftLibs\Enqueue\Blocks\EnqueueBlocksCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); - - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); + setBeforeEach(); - $this->ebc = new EnqueueBlocksCli('boilerplate'); + $this->mock = new EnqueueBlocksCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(\dirname(__FILE__, 4) . '/cliOutput'); + setAfterEach(); + + unset($this->mock); }); /** * Making an appropriate class with all it's key strings. */ test('Enqueue Block CLI command will make appropriate class.', function () { - $ebc = $this->ebc; + $ebc = $this->mock; $ebc([], []); $generatedEBC = \file_get_contents(\dirname(__FILE__, 4) . '/cliOutput/src/Enqueue/Blocks/EnqueueBlocks.php'); @@ -61,7 +49,7 @@ * Testing if correct namespace will be set. */ test('Enqueue Block CLI command will set correct namespace.', function () { - $ebc = $this->ebc; + $ebc = $this->mock; $ebc([],[ 'namespace' => 'NewTheme', ]); @@ -75,7 +63,7 @@ * Testing if correct functions will be generated. */ test('Enqueue Block CLI command will set correct functions.', function () { - $ebc = $this->ebc; + $ebc = $this->mock; $ebc([], []); $generatedEBC = \file_get_contents(\dirname(__FILE__, 4) . '/cliOutput/src/Enqueue/Blocks/EnqueueBlocks.php'); @@ -85,5 +73,5 @@ }); test('Custom Enqueue Blocks CLI documentation is correct', function () { - expect($this->ebc->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/Enqueue/Theme/EnqueueThemeCliTest.php b/tests/Enqueue/Theme/EnqueueThemeCliTest.php index efcadcf37..d390792fb 100644 --- a/tests/Enqueue/Theme/EnqueueThemeCliTest.php +++ b/tests/Enqueue/Theme/EnqueueThemeCliTest.php @@ -4,36 +4,24 @@ use EightshiftLibs\Enqueue\Theme\EnqueueThemeCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->enqueueTheme = new EnqueueThemeCli('boilerplate'); + $this->mock = new EnqueueThemeCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(\dirname(__FILE__, 4) . '/cliOutput'); + setAfterEach(); + + unset($this->mock); }); test('Custom enqueue theme CLI command will correctly copy the Enqueue Theme class', function () { - $theme = $this->enqueueTheme; - $theme([], $theme->getDevelopArgs([])); + $theme = $this->mock; + $theme([], $theme->getDefaultArgs()); // Check the output dir if the generated method is correctly generated. $generatedTheme = \file_get_contents(\dirname(__FILE__, 4) . '/cliOutput/src/Enqueue/Theme/EnqueueTheme.php'); @@ -45,5 +33,5 @@ test('Custom Enqueue Theme CLI documentation is correct', function () { - expect($this->enqueueTheme->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/Geolocation/AbstractGeolocationTest.php b/tests/Geolocation/AbstractGeolocationTest.php index a86463266..3eca21c5b 100644 --- a/tests/Geolocation/AbstractGeolocationTest.php +++ b/tests/Geolocation/AbstractGeolocationTest.php @@ -52,11 +52,11 @@ test('setLocationCookie will exit if is not frontend', function () { $action = 'is_admin'; - Functions\when($action)->justReturn(putenv("ES_SIDEAFFECT={$action}")); + Functions\when($action)->justReturn(putenv("ES_SIDEAFFECT_1={$action}")); $this->geolocation->setLocationCookie(); - expect(getenv('ES_SIDEAFFECT'))->toEqual($action); + expect(getenv('ES_SIDEAFFECT_1'))->toEqual($action); }); test('setLocationCookie will exit if useGeolocation is false', function () { @@ -65,11 +65,11 @@ $mock = mock(GeolocationExample::class)->makePartial(); $mock->shouldReceive('useGeolocation')->andReturn(false); - Functions\when($action)->justReturn(putenv("ES_SIDEAFFECT={$action}")); + Functions\when($action)->justReturn(putenv("ES_SIDEAFFECT_1={$action}")); $mock->setLocationCookie(); - expect(getenv('ES_SIDEAFFECT'))->toEqual($action); + expect(getenv('ES_SIDEAFFECT_1'))->toEqual($action); }); test('setLocationCookie will exit if cookie is set', function () { @@ -80,12 +80,12 @@ $_COOKIE[$cookieName] = 'HR'; if (isset($cookieName)) { - putenv("ES_SIDEAFFECT={$action}"); + putenv("ES_SIDEAFFECT_1={$action}"); } $this->geolocation->setLocationCookie(); - expect(getenv('ES_SIDEAFFECT'))->toEqual($action); + expect(getenv('ES_SIDEAFFECT_1'))->toEqual($action); unset($_COOKIE[$cookieName]); }); @@ -93,14 +93,14 @@ test('setLocationCookie will set cookie to localhost.', function () { $mock = mock(GeolocationExample::class)->makePartial(); $mock->shouldReceive('setCookie')->withArgs(function (string $name, string $value) { - putenv("ES_SIDEAFFECT={$name}"); - putenv("ES_SIDEAFFECT_ADDITIONAL={$value}"); + putenv("ES_SIDEAFFECT_1={$name}"); + putenv("ES_SIDEAFFECT_2={$value}"); }); $mock->setLocationCookie(); - expect(getenv('ES_SIDEAFFECT'))->toEqual($this->geolocation->getGeolocationCookieName()); - expect(getenv('ES_SIDEAFFECT_ADDITIONAL'))->toEqual('localhost'); + expect(getenv('ES_SIDEAFFECT_1'))->toEqual($this->geolocation->getGeolocationCookieName()); + expect(getenv('ES_SIDEAFFECT_2'))->toEqual('localhost'); }); test('setLocationCookie will set cookie based on the server location.', function () { @@ -108,15 +108,15 @@ $mock->shouldReceive('getGeolocationPharLocation')->andReturn(getDataPath('geolocation/geoip.phar')); $mock->shouldReceive('getGeolocationDbLocation')->andReturn(getDataPath('geolocation/geoip.mmdb')); $mock->shouldReceive('setCookie')->withArgs(function (string $name, string $value) { - putenv("ES_SIDEAFFECT={$name}"); - putenv("ES_SIDEAFFECT_ADDITIONAL={$value}"); + putenv("ES_SIDEAFFECT_1={$name}"); + putenv("ES_SIDEAFFECT_2={$value}"); }); $_SERVER['REMOTE_ADDR'] = $this->germanIp; $mock->setLocationCookie(); - expect(getenv('ES_SIDEAFFECT_ADDITIONAL'))->toEqual('DE'); + expect(getenv('ES_SIDEAFFECT_2'))->toEqual('DE'); unset($_SERVER['REMOTE_ADDR']); }); @@ -127,13 +127,13 @@ $mock->shouldReceive('getGeolocationDbLocation')->andReturn(getDataPath('geolocation/geoip.mmdb')); $mock->shouldReceive('getIpAddress')->andReturn($this->germanIp); $mock->shouldReceive('setCookie')->withArgs(function (string $name, string $value) { - putenv("ES_SIDEAFFECT={$name}"); - putenv("ES_SIDEAFFECT_ADDITIONAL={$value}"); + putenv("ES_SIDEAFFECT_1={$name}"); + putenv("ES_SIDEAFFECT_2={$value}"); }); $mock->setLocationCookie(); - expect(getenv('ES_SIDEAFFECT_ADDITIONAL'))->toEqual('DE'); + expect(getenv('ES_SIDEAFFECT_2'))->toEqual('DE'); }); test('setLocationCookie will throw and error if something is wrong.', function () { @@ -142,13 +142,13 @@ $mock->shouldReceive('getGeolocationDbLocation')->andThrow(new Exception('test')); $mock->shouldReceive('getIpAddress')->andReturn($this->germanIp); $mock->shouldReceive('setCookie')->withArgs(function (string $name, string $value) { - putenv("ES_SIDEAFFECT={$name}"); - putenv("ES_SIDEAFFECT_ADDITIONAL={$value}"); + putenv("ES_SIDEAFFECT_1={$name}"); + putenv("ES_SIDEAFFECT_2={$value}"); }); $mock->setLocationCookie(); - expect(getenv('ES_SIDEAFFECT_ADDITIONAL'))->toEqual('ERROR: test'); + expect(getenv('ES_SIDEAFFECT_2'))->toEqual('ERROR: test'); }); //---------------------------------------------------------------------------------// diff --git a/tests/Geolocation/GeolocationCliTest.php b/tests/Geolocation/GeolocationCliTest.php index b355020c0..5f93c0afc 100644 --- a/tests/Geolocation/GeolocationCliTest.php +++ b/tests/Geolocation/GeolocationCliTest.php @@ -34,7 +34,7 @@ test('Geolocation CLI command will correctly copy the geolocation example class with default args', function () { $mock = $this->geolocationCli; - $args = $mock->getDefaultArgs([]); + $args = $mock->getDefaultArgs(); $mock([], $args); // Check the output dir if the generated method is correctly generated. @@ -47,7 +47,7 @@ test('Geolocation CLI command will correctly copy the geolocation example class with develop args', function () { $mock = $this->geolocationCli; - $args = $mock->getDevelopArgs([]); + $args = $mock->getDefaultArgs(); $mock([], $args); // Check the output dir if the generated method is correctly generated. diff --git a/tests/GitIgnore/GitIgnoreCliTest.php b/tests/GitIgnore/GitIgnoreCliTest.php index 2713b5442..a842b63be 100644 --- a/tests/GitIgnore/GitIgnoreCliTest.php +++ b/tests/GitIgnore/GitIgnoreCliTest.php @@ -2,66 +2,76 @@ namespace Tests\Unit\GitIgnore; +use EightshiftLibs\Cli\ParentGroups\CliCreate; use EightshiftLibs\GitIgnore\GitIgnoreCli; +use EightshiftLibs\Helpers\Components; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); -$wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - -$wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - -$this->gitignore = new GitIgnoreCli('boilerplate'); + $this->mock = new GitIgnoreCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); -test('GitIgnore CLI command will correctly copy the .gitignore file with defaults', function () { - $gitignore = $this->gitignore; - $gitignore([], $gitignore->getDevelopArgs([])); +//---------------------------------------------------------------------------------// - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/.gitignore'; +test('getCommandParentName will return correct value', function () { + expect($this->mock->getCommandParentName()) + ->toBeString() + ->toEqual(CliCreate::COMMAND_NAME); +}); - // Check the output dir if the generated method is correctly generated. - $generatedIgnore = \file_get_contents($outputPath); +//---------------------------------------------------------------------------------// - $this->assertStringContainsString('wp-admin', $generatedIgnore); - $this->assertStringNotContainsString('footer.php', $generatedIgnore); - $this->assertFileExists($outputPath); +test('getCommandName will return correct value', function () { + expect($this->mock->getCommandName()) + ->toBeString() + ->toEqual('gitignore'); }); -test('GitIgnore CLI command will run under custom command name', function () { - $gitignore = $this->gitignore; - $result = $gitignore->getCommandName(); +//---------------------------------------------------------------------------------// - $this->assertStringContainsString('gitignore', $result); +test('getDefaultArgs will return correct array', function () { + expect($this->mock->getDefaultArgs()) + ->toBeArray() + ->toHaveKeys(['path']); }); -test('GitIgnore CLI command will correctly copy the .gitignore file in the custom folder with set arguments', function () { - $gitignore = $this->gitignore; - $gitignore([], [ - 'root' => './test', - ]); +//---------------------------------------------------------------------------------// - $this->assertFileExists(\dirname(__FILE__, 3) . '/cliOutput/test/.gitignore'); +test('getDoc will return correct array', function () { + $docs = $this->mock->getDoc(); + + expect($docs) + ->toBeArray() + ->toHaveKeys(['shortdesc', 'synopsis', 'longdesc']) + ->and(count($docs['synopsis']))->toEqual(1) + ->and($docs['synopsis'][0]['name'])->toEqual('path'); }); +//---------------------------------------------------------------------------------// + +test('__invoke will will correctly copy example class with default args', function () { + $mock = $this->mock; + $mock([], [ + 'path' => Components::getProjectPaths('cliOutput'), + ]); + + $output = \file_get_contents(Components::getProjectPaths('cliOutput', '.gitignore')); -test('GitIgnore CLI documentation is correct', function () { - expect($this->gitignore->getDoc())->toBeArray(); + expect($output) + ->toContain( + 'wp-admin', + '/index.php', + 'wp-content/*', + 'wp-content/themes/twenty*/', + ); }); diff --git a/tests/Helpers.php b/tests/Helpers.php index 0ab3c4383..3800e8cd2 100644 --- a/tests/Helpers.php +++ b/tests/Helpers.php @@ -5,6 +5,8 @@ use Brain\Monkey\Functions; use Mockery; use Brain\Monkey; +use EightshiftLibs\Init\InitBlocksCli; +use Exception; use Mockery\MockInterface; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; @@ -21,10 +23,10 @@ function setupMocks() { Functions\stubEscapeFunctions(); // Mock the template dir location. - Functions\when('get_template_directory')->justReturn(\dirname(__FILE__) . '/data'); + Functions\when('get_template_directory')->justReturn(\dirname(__FILE__) . \DIRECTORY_SEPARATOR . 'data'); // Mock the template dir location. - Functions\when('get_stylesheet_directory')->justReturn(\dirname(__FILE__) . '/'); + Functions\when('get_stylesheet_directory')->justReturn(\dirname(__FILE__) . \DIRECTORY_SEPARATOR); // Mock escaping function. Functions\when('wp_kses_post')->returnArg(); @@ -86,6 +88,13 @@ function setupMocks() { // Mock get_field function. Functions\when('get_field')->returnArg(); + // Mock wp_parse_url function. + Functions\when('wp_parse_url')->justReturn([ + 'scheme' => 'https', + 'host' => 'developer.wordpress.org', + 'path' => '/reference/functions/wp_parse_url/', + ]); + $wpCliMock = mock('alias:WP_CLI'); $wpCliMock @@ -96,8 +105,9 @@ function setupMocks() { $wpCliMock ->shouldReceive('error') - ->andReturnUsing(function ($message) { - putenv("ES_CLI_ERROR_HAPPENED={$message}"); + ->andReturnUsing(function ($errorMessage) { + putenv("ES_CLI_ERROR_HAPPENED={$errorMessage}"); + throw new Exception($errorMessage); }); $wpCliMock @@ -118,6 +128,12 @@ function setupMocks() { putenv("ES_CLI_ADD_COMMAND_HAPPENED={$message}"); }); + $wpCliMock + ->shouldReceive('colorize') + ->andReturnUsing(function ($message) { + return $message; + }); + // Mock attachment function. Functions\when('get_attached_file')->justReturn('test.jpg'); @@ -132,6 +148,14 @@ function setupMocks() { } Functions\when('is_admin')->justReturn(false); + + Functions\when('trailingslashit')->alias(function(string $string) { + return rtrim( $string, '/\\' ); + }); + + Functions\when('is_wp_version_compatible')->justReturn(true); + + Functions\when('wp_nonce_field')->justReturn('nonce'); } /** @@ -156,12 +180,18 @@ function setAfterEach($delete = true) { deleteCliOutput(); } - putenv('ES_SIDEAFFECT'); - putenv('ES_SIDEAFFECT_ADDITIONAL'); + for ($i = 1; $i <= 10; $i++ ) { + putenv("ES_SIDEAFFECT_{$i}"); + putenv("ES_SIDEAFFECT_1"); + } + putenv('ES_CLI_SUCCESS_HAPPENED'); putenv('ES_CLI_ERROR_HAPPENED'); putenv('ES_CLI_LOG_HAPPENED'); putenv('ES_CLI_RUNCOMMAND_HAPPENED'); + + global $esBlocks; + $esBlocks = null; } /** @@ -173,8 +203,9 @@ function setAfterEach($delete = true) { */ function deleteCliOutput(string $dir = '') : void { + $sep = \DIRECTORY_SEPARATOR; if (!$dir) { - $dir = \dirname(__FILE__, 2) . '/cliOutput'; + $dir = \dirname(__FILE__, 2) . "{$sep}cliOutput"; } if (!\is_dir($dir)) { @@ -204,9 +235,72 @@ function deleteCliOutput(string $dir = '') : void */ function getDataPath(string $path = ''): string { - $ds = \DIRECTORY_SEPARATOR; + $sep = \DIRECTORY_SEPARATOR; + $internalPath = __DIR__ . "{$sep}data"; + + if ($path) { + return "{$internalPath}{$sep}{$path}"; + } + + return $internalPath; +} + +/** + * Get path to cliOutput mocks. + * + * @param string $path Path to attach. + * + * @return string + */ +function getCliOutputPath(string $path = ''): string +{ + $sep = \DIRECTORY_SEPARATOR; + $internalPath = getProjectRootPath() . "{$sep}cliOutput"; + + if ($path) { + return "{$internalPath}{$sep}{$path}"; + } + + return $internalPath; +} + +/** + * Get projects root path for mocks. + * + * @return string + */ +function getProjectRootPath(): string +{ + return \dirname(__FILE__, 2); +} - return __DIR__ . "{$ds}data{$ds}{$path}"; +/** + * Get file in cliOutput folder. + * + * @param string $path Path to get. + * + * @throws Exception If file is missing. + * + * @return string + */ +function getCliOutputFile(string $path = ''): string +{ + $pathFile = getCliOutputPath($path); + + if (!file_exists($pathFile)) { + throw new Exception("File missing on this path: {$pathFile}"); + } + + return \file_get_contents($pathFile); +} + +/** + * Build all blocks setup output. + * + * @return void + */ +function buildTestBlocks() { + (new InitBlocksCli('boilerplate'))->__invoke([], []); } /** @@ -220,3 +314,4 @@ function mock(string $class): MockInterface { return Mockery::mock($class); } + diff --git a/tests/Helpers/AttributesTraitTest.php b/tests/Helpers/AttributesTraitTest.php index 330015395..67395648d 100644 --- a/tests/Helpers/AttributesTraitTest.php +++ b/tests/Helpers/AttributesTraitTest.php @@ -4,29 +4,23 @@ use EightshiftLibs\Helpers\Components; -use Brain\Monkey; use EightshiftBoilerplate\Blocks\BlocksExample; use Exception; -use function Tests\setupMocks; +use function Tests\buildTestBlocks; use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -beforeAll(function () { - Monkey\setUp(); - setupMocks(); -}); - -afterAll(function() { - Monkey\tearDown(); -}); +beforeEach(function () { + setBeforeEach(); -beforeEach(function() { + buildTestBlocks(); (new BlocksExample())->getBlocksDataFullRaw(); }); -afterEach(function() { - global $esBlocks; - $esBlocks = null; +afterEach(function () { + setAfterEach(); }); // ------------------------------------------ @@ -34,7 +28,7 @@ // ------------------------------------------ test('Asserts that checkAttr works in case attribute is string', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/button/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'variables')); $attributes['buttonAlign'] = 'right'; $results = Components::checkAttr('buttonAlign', $attributes, $manifest); @@ -45,7 +39,7 @@ }); test('checkAttr will throw an exception in the case that the block name is missing in the manifest', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/custom/button/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationCustom', 'button')); $attributes['buttonText'] = 'left'; Components::checkAttr('buttonAlign', $attributes, $manifest); @@ -64,7 +58,7 @@ }); test('Asserts that checkAttr returns false in case attribute is boolean and default is not set', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/button/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'button')); $attributes['buttonIsAnchor'] = true; $results = Components::checkAttr('buttonIsNewTab', $attributes, $manifest); @@ -75,7 +69,7 @@ }); test('Asserts that checkAttr returns null in case attribute is boolean, default is not set and undefined is allowed', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/button/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'button')); $attributes['buttonIsAnchor'] = true; $results = Components::checkAttr('buttonIsNewTab', $attributes, $manifest, true); @@ -86,7 +80,7 @@ }); test('Asserts that checkAttr works in case attribute is array', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/button/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'button')); $attributes['buttonAttrs'] = ['attr 1', 'attr 2']; $results = Components::checkAttr('buttonAttrs', $attributes, $manifest); @@ -101,7 +95,7 @@ }); test('Asserts that checkAttr returns empty array in case attribute is array or object and default is not set', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/button/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'button')); $attributes['buttonSize'] = 'large'; $results = Components::checkAttr('buttonAttrs', $attributes, $manifest); @@ -113,7 +107,7 @@ }); test('Asserts that checkAttr returns null in case attribute is array or object, default is not set, and undefined is allowed', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/button/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'button')); $attributes['buttonSize'] = 'large'; $results = Components::checkAttr('buttonAttrs', $attributes, $manifest, true); @@ -124,7 +118,7 @@ }); test('Asserts that checkAttr returns default value', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/button/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'button')); $attributes['title'] = 'Some attribute'; $results = Components::checkAttr('buttonAlign', $attributes, $manifest, 'button'); @@ -135,14 +129,14 @@ }); test('Asserts that checkAttr throws exception if manifest key is not set', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/button/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'button')); $attributes['title'] = 'Some attribute'; Components::checkAttr('bla', $attributes, $manifest, 'button'); })->throws(Exception::class, "bla key does not exist in the button component manifest. Please check your implementation."); test('Asserts that checkAttr returns attribute based on prefix if set', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/button/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'button')); $attributes = [ 'prefix' => 'prefixedMultipleTimesButton', 'prefixedMultipleTimesButtonAlign' => 'right' @@ -160,7 +154,7 @@ // ------------------------------------------ test('Asserts that checkAttrResponsive returns the correct output.', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/heading/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'heading')); $attributes = [ 'headingContentSpacingLarge' => '10', 'headingContentSpacingDesktop' => '5', @@ -179,7 +173,7 @@ }); test('Asserts that checkAttrResponsive returns empty values if attribute is not provided.', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/heading/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'heading')); $attributes = []; $results = Components::checkAttrResponsive('headingContentSpacing', $attributes, $manifest); @@ -193,7 +187,7 @@ }); test('Asserts that checkAttrResponsive returns null if default is not set and undefined is allowed.', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/heading/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'heading')); $attributes = [ 'headingContentSpacingDesktop' => '2' ]; @@ -215,21 +209,21 @@ }); test('Asserts that checkAttrResponsive throws error if responsiveAttribute key is missing', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/button/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'button')); $attributes = []; Components::checkAttrResponsive('headingContentSpacing', $attributes, $manifest, 'button'); })->throws(Exception::class, 'It looks like you are missing responsiveAttributes key in your button component manifest.'); test('Asserts that checkAttrResponsive throws error if keyName key is missing responsiveAttributes array', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/components/heading/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'heading')); $attributes = []; Components::checkAttrResponsive('testAttribute', $attributes, $manifest, 'button'); })->throws(Exception::class, 'It looks like you are missing the testAttribute key in your manifest responsiveAttributes array.'); test('Asserts that checkAttrResponsive throws error if keyName key is missing responsiveAttributes array for blockName', function () { - $manifest = Components::getManifest(\dirname(__FILE__, 2) . '/data/src/Blocks/custom/heading/'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationCustom', 'heading')); $attributes = []; Components::checkAttrResponsive('bla', $attributes, $manifest, 'button'); @@ -253,9 +247,9 @@ // ------------------------------------------ test('Asserts props for heading block will return only heading attributes', function () { - $headingBlock = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/custom/heading'); - $headingComponent = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/components/heading'); - $typographyComponent = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/components/typography'); + $headingBlock = Components::getManifest(Components::getProjectPaths('blocksDestinationCustom', 'heading')); + $headingComponent = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'heading')); + $typographyComponent = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'typography')); $attributes = array_merge( $headingBlock['attributes'], @@ -278,9 +272,9 @@ }); test('Asserts props for heading component will return only typography attributes', function () { - $headingBlock = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/custom/heading'); - $headingComponent = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/components/heading'); - $typographyComponent = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/components/typography'); + $headingBlock = Components::getManifest(Components::getProjectPaths('blocksDestinationCustom', 'heading')); + $headingComponent = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'heading')); + $typographyComponent = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'typography')); $attributes = array_merge( $headingBlock['attributes'], @@ -303,9 +297,9 @@ }); test('Asserts props will correctly build the prefix', function () { - $headingBlock = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/custom/heading'); - $headingComponent = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/components/heading'); - $typographyComponent = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/components/typography'); + $headingBlock = Components::getManifest(Components::getProjectPaths('blocksDestinationCustom', 'heading')); + $headingComponent = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'heading')); + $typographyComponent = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'typography')); $attributes = array_merge( $headingBlock['attributes'], diff --git a/tests/Helpers/ComponentHelpersTest.php b/tests/Helpers/ComponentHelpersTest.php index 9bd76b589..ed91ad4fd 100644 --- a/tests/Helpers/ComponentHelpersTest.php +++ b/tests/Helpers/ComponentHelpersTest.php @@ -5,27 +5,21 @@ use EightshiftLibs\Exception\ComponentException; use EightshiftLibs\Helpers\Components; -use Brain\Monkey; use EightshiftBoilerplate\Blocks\BlocksExample; -use function Tests\setupMocks; +use function Tests\buildTestBlocks; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -beforeAll(function () { - Monkey\setUp(); - setupMocks(); -}); - -afterAll(function() { - Monkey\tearDown(); -}); +beforeEach(function () { + setBeforeEach(); -beforeEach(function() { + buildTestBlocks(); (new BlocksExample())->getBlocksDataFullRaw(); }); -afterEach(function() { - global $esBlocks; - $esBlocks = null; +afterEach(function () { + setAfterEach(); }); // ------------------------------------------ diff --git a/tests/Helpers/CssVariablesTraitTest.php b/tests/Helpers/CssVariablesTraitTest.php index 75bca7222..aae5d3975 100644 --- a/tests/Helpers/CssVariablesTraitTest.php +++ b/tests/Helpers/CssVariablesTraitTest.php @@ -4,28 +4,22 @@ use EightshiftLibs\Helpers\Components; -use Brain\Monkey; use Brain\Monkey\Functions; use EightshiftBoilerplate\Blocks\BlocksExample; -use function Tests\setupMocks; +use function Tests\buildTestBlocks; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -beforeAll(function () { - Monkey\setUp(); - setupMocks(); -}); - -afterAll(function() { - Monkey\tearDown(); -}); +beforeEach(function () { + setBeforeEach(); -beforeEach(function() { + buildTestBlocks(); (new BlocksExample())->getBlocksDataFullRaw(); }); afterEach(function () { - global $esBlocks; - $esBlocks = null; + setAfterEach(); }); // ------------------------------------------ @@ -104,7 +98,7 @@ }); test('outputCssVariables works when correct attributes are passed to it', function () { - $manifest = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/components/variables'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'variables')); Components::setConfigOutputCssGlobally(false); Components::setConfigOutputCssOptimize(false); @@ -125,7 +119,7 @@ }); test('outputCssVariables works when correct attributes are passed to it and has a unique name', function () { - $manifest = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/components/variables'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'variables')); Components::setConfigOutputCssGlobally(false); Components::setConfigOutputCssOptimize(false); @@ -151,7 +145,7 @@ Components::setConfigOutputCssGlobally(false); Components::setConfigOutputCssOptimize(false); - $manifest = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/components/variables'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'variables')); $attributes = [ 'variableValue' => 'value3', @@ -171,7 +165,7 @@ }); test('outputCssVariables outputs the style tag in inline way if the outputCssGlobally is set to true', function () { - $manifest = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/components/variables'); + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'variables')); $attributes = [ 'variableValue' => 'value3', @@ -246,7 +240,8 @@ test('Asserts that "outputCssVariablesInline" will return style tag with the correct styles.', function () { Components::setConfigOutputCssOptimize(false); - $manifest = Components::getManifest(dirname(__FILE__, 2) . '/data/src/Blocks/components/variables'); + ; + $manifest = Components::getManifest(Components::getProjectPaths('blocksDestinationComponents', 'variables')); $attributes = [ 'variableValue' => 'value3', ]; diff --git a/tests/Helpers/SelectorsTraitTest.php b/tests/Helpers/SelectorsTraitTest.php index d4aa6d0df..61b04d4bc 100644 --- a/tests/Helpers/SelectorsTraitTest.php +++ b/tests/Helpers/SelectorsTraitTest.php @@ -5,27 +5,15 @@ use EightshiftLibs\Exception\ComponentException; use EightshiftLibs\Helpers\Components; -use Brain\Monkey; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -use function Tests\setupMocks; - -beforeAll(function () { - Monkey\setUp(); - setupMocks(); -}); - -afterAll(function() { - Monkey\tearDown(); -}); - -beforeEach(function() { - global $esBlocks; - $esBlocks = null; +beforeEach(function () { + setBeforeEach(); }); -afterEach(function() { - global $esBlocks; - $esBlocks = null; +afterEach(function () { + setAfterEach(); }); // ------------------------------------------ diff --git a/tests/Helpers/StoreTraitTest.php b/tests/Helpers/StoreTraitTest.php index fe050ac96..41913318a 100644 --- a/tests/Helpers/StoreTraitTest.php +++ b/tests/Helpers/StoreTraitTest.php @@ -2,28 +2,22 @@ namespace Tests\Unit\Helpers; -use Brain\Monkey; use EightshiftBoilerplate\Blocks\BlocksExample; use EightshiftLibs\Helpers\Components; -use function Tests\setupMocks; - -beforeAll(function () { - Monkey\setUp(); - setupMocks(); -}); - -afterAll(function() { - Monkey\tearDown(); -}); +use function Tests\buildTestBlocks; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; beforeEach(function () { + setBeforeEach(); + + buildTestBlocks(); (new BlocksExample())->getBlocksDataFullRaw(); }); afterEach(function () { - global $esBlocks; - $esBlocks = null; + setAfterEach(); }); // ------------------------------------------ diff --git a/tests/I18n/I18nCliTest.php b/tests/I18n/I18nCliTest.php index 5a655e1e5..65454741f 100644 --- a/tests/I18n/I18nCliTest.php +++ b/tests/I18n/I18nCliTest.php @@ -2,63 +2,51 @@ namespace Tests\Unit\I18n; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\I18n\I18nCli; use function Tests\deleteCliOutput; use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); -$wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - -$wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - -$this->i18n = new I18nCli('boilerplate'); + $this->mock = new I18nCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); test('I18n CLI command will correctly copy the I18n class with defaults', function () { - $i18n = $this->i18n; - $i18n([], []); - - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/src/I18n/I18n.php'; + $mock = $this->mock; + $mock([], []); - // Check the output dir if the generated method is correctly generated. - $generatedI18n = \file_get_contents($outputPath); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}I18n{$sep}I18n.php")); - $this->assertStringContainsString('class I18n implements ServiceInterface', $generatedI18n); - $this->assertStringContainsString('@package EightshiftLibs\I18n', $generatedI18n); - $this->assertStringContainsString('namespace EightshiftLibs\I18n', $generatedI18n); - $this->assertStringNotContainsString('footer.php', $generatedI18n); - $this->assertFileExists($outputPath); + $this->assertStringContainsString('class I18n implements ServiceInterface', $output); + $this->assertStringContainsString('@package EightshiftLibs\I18n', $output); + $this->assertStringContainsString('namespace EightshiftLibs\I18n', $output); + $this->assertStringNotContainsString('footer.php', $output); }); test('I18n CLI command will correctly copy the I18n class with set arguments', function () { - $i18n = $this->i18n; - $i18n([], [ + $mock = $this->mock; + $mock([], [ 'namespace' => 'CoolTheme', ]); - // Check the output dir if the generated method is correctly generated. - $generatedI18n = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/I18n/I18n.php'); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}I18n{$sep}I18n.php")); - $this->assertStringContainsString('namespace CoolTheme\I18n;', $generatedI18n); + $this->assertStringContainsString('namespace CoolTheme\I18n;', $output); }); test('I18n CLI documentation is correct', function () { - expect($this->i18n->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/Init/InitBlocksCliTest.php b/tests/Init/InitBlocksCliTest.php new file mode 100644 index 000000000..7295cc02d --- /dev/null +++ b/tests/Init/InitBlocksCliTest.php @@ -0,0 +1,47 @@ +mock = new InitBlocksCli('boilerplate'); +}); + +afterEach(function () { + setAfterEach(); + + unset($this->mock); +}); + +test('Blocks CLI command will correctly copy the Blocks class with defaults', function () { + $mock = $this->mock; + $mock([], []); + + // $output = \file_get_contents(Components::getProjectPaths('blocksDestination', "Blocks.php")); + + // $this->assertStringContainsString('class Blocks extends AbstractBlocks', $output); + // $this->assertStringContainsString('@package EightshiftLibs\Blocks', $output); + // $this->assertStringContainsString('namespace EightshiftLibs\Blocks', $output); + // $this->assertStringNotContainsString('footer.php', $output); +}); + +// test('Blocks CLI command will correctly copy the Blocks class with set arguments', function () { +// $mock = $this->mock; +// $mock([], [ +// 'namespace' => 'CoolTheme', +// ]); + +// $output = \file_get_contents(Components::getProjectPaths('blocksDestination', "Blocks.php")); + +// $this->assertStringContainsString('namespace CoolTheme\Blocks;', $output); +// }); + +// test('Blocks CLI documentation is correct', function () { +// expect($this->mock->getDoc())->toBeArray(); +// }); diff --git a/tests/Init/InitProjectCliTest.php b/tests/Init/InitProjectCliTest.php new file mode 100644 index 000000000..ea1c156ce --- /dev/null +++ b/tests/Init/InitProjectCliTest.php @@ -0,0 +1,45 @@ +mock = new InitProjectCli('boilerplate'); +}); + +afterEach(function () { + setAfterEach(); + + unset($this->mock); +}); + +test('Initializing the project command returns correct command name', function () { + $commandName = $this->mock->getCommandName(); + + $this->assertIsString($commandName); + $this->assertSame('project', $commandName); +}); + +test('InitProjectCli CLI documentation is correct', function () { + expect($this->mock->getDoc())->toBeArray(); +}); + +test('InitProject CLI command will correctly copy the project classes', function () { + $mock = $this->mock; + $mock([], \array_merge( + $mock->getDefaultArgs(), + [ + 'path' => Components::getProjectPaths('cliOutput'), + ] + )); + + expect(\getenv('ES_CLI_LOG_HAPPENED')) + ->toContain('Happy developing!'); +}); diff --git a/tests/Init/InitThemeCliTest.php b/tests/Init/InitThemeCliTest.php new file mode 100644 index 000000000..1b4eddfa9 --- /dev/null +++ b/tests/Init/InitThemeCliTest.php @@ -0,0 +1,42 @@ +mock = new InitThemeCli('boilerplate'); +}); + +afterEach(function () { + setAfterEach(); + + unset($this->mock); +}); + +test('Initializing the project command returns correct command name', function () { + $commandName = $this->mock->getCommandName(); + + $this->assertIsString($commandName); + $this->assertSame('theme', $commandName); +}); + + +test('InitThemeCli CLI documentation is correct', function () { + expect($this->mock->getDoc())->toBeArray(); +}); + +test('InitTheme CLI command will correctly copy the project classes', function () { + $mock = $this->mock; + $mock([], $mock->getDefaultArgs()); + + expect(\getenv('ES_CLI_LOG_HAPPENED')) + ->toContain('Happy developing!'); +}); diff --git a/tests/Login/LoginCliTest.php b/tests/Login/LoginCliTest.php index 04d9a4a9b..1d6093219 100644 --- a/tests/Login/LoginCliTest.php +++ b/tests/Login/LoginCliTest.php @@ -2,64 +2,50 @@ namespace Tests\Unit\Login; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\Login\LoginCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); -$wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - -$wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - -$this->login = new LoginCli('boilerplate'); + $this->mock = new LoginCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); test('Login CLI command will correctly copy the Login class with defaults', function () { - $login = $this->login; - $login([], []); - - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/src/Login/Login.php'; + $mock = $this->mock; + $mock([], []); - // Check the output dir if the generated method is correctly generated. - $generatedLogin = \file_get_contents($outputPath); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}Login{$sep}Login.php")); - $this->assertStringContainsString('class Login implements ServiceInterface', $generatedLogin); - $this->assertStringContainsString('@package EightshiftLibs\Login', $generatedLogin); - $this->assertStringContainsString('namespace EightshiftLibs\Login', $generatedLogin); - $this->assertStringNotContainsString('footer.php', $generatedLogin); - $this->assertFileExists($outputPath); + $this->assertStringContainsString('class Login implements ServiceInterface', $output); + $this->assertStringContainsString('@package EightshiftLibs\Login', $output); + $this->assertStringContainsString('namespace EightshiftLibs\Login', $output); + $this->assertStringNotContainsString('footer.php', $output); }); test('Login CLI command will correctly copy the Login class with set arguments', function () { - $login = $this->login; - $login([], [ + $mock = $this->mock; + $mock([], [ 'namespace' => 'CoolTheme', ]); - // Check the output dir if the generated method is correctly generated. - $generatedLogin = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/Login/Login.php'); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}Login{$sep}Login.php")); - $this->assertStringContainsString('namespace CoolTheme\Login;', $generatedLogin); + $this->assertStringContainsString('namespace CoolTheme\Login;', $output); }); test('Login CLI documentation is correct', function () { - expect($this->login->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/Main/AbstractMainTest.php b/tests/Main/AbstractMainTest.php index 4194f3d77..de01747ba 100644 --- a/tests/Main/AbstractMainTest.php +++ b/tests/Main/AbstractMainTest.php @@ -5,31 +5,19 @@ use EightshiftLibs\Main\AbstractMain; use EightshiftLibs\Main\MainCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); -$wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - -$wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - -$this->main = new MainCli('boilerplate'); + $this->mock = new MainCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); test('Abstract main will instantiate services', function () { diff --git a/tests/Main/MainCliTest.php b/tests/Main/MainCliTest.php index 4744b5391..759bb0611 100644 --- a/tests/Main/MainCliTest.php +++ b/tests/Main/MainCliTest.php @@ -2,64 +2,50 @@ namespace Tests\Unit\Main; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\Main\MainCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); -$wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - -$wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - -$this->main = new MainCli('boilerplate'); + $this->mock = new MainCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); test('Main CLI command will correctly copy the Main class with defaults', function () { - $main = $this->main; - $main([], []); - - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/src/Main/Main.php'; + $mock = $this->mock; + $mock([], []); - // Check the output dir if the generated method is correctly generated. - $generatedMain = \file_get_contents($outputPath); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}Main{$sep}Main.php")); - $this->assertStringContainsString('class Main extends AbstractMain', $generatedMain); - $this->assertStringContainsString('@package EightshiftLibs\Main', $generatedMain); - $this->assertStringContainsString('namespace EightshiftLibs\Main', $generatedMain); - $this->assertStringNotContainsString('footer.php', $generatedMain); - $this->assertFileExists($outputPath); + $this->assertStringContainsString('class Main extends AbstractMain', $output); + $this->assertStringContainsString('@package EightshiftLibs\Main', $output); + $this->assertStringContainsString('namespace EightshiftLibs\Main', $output); + $this->assertStringNotContainsString('footer.php', $output); }); test('Main CLI command will correctly copy the Main class with set arguments', function () { - $main = $this->main; - $main([], [ + $mock = $this->mock; + $mock([], [ 'namespace' => 'CoolTheme', ]); - // Check the output dir if the generated method is correctly generated. - $generatedMain = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/Main/Main.php'); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}Main{$sep}Main.php")); - $this->assertStringContainsString('namespace CoolTheme\Main', $generatedMain); - $this->assertStringNotContainsString('namespace EightshiftLibs\Main', $generatedMain); + $this->assertStringContainsString('namespace CoolTheme\Main', $output); + $this->assertStringNotContainsString('namespace EightshiftLibs\Main', $output); }); test('Main CLI documentation is correct', function () { - expect($this->main->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/Main/MainExampleTest.php b/tests/Main/MainExampleTest.php index 9d8da7d86..f58329837 100644 --- a/tests/Main/MainExampleTest.php +++ b/tests/Main/MainExampleTest.php @@ -2,20 +2,19 @@ namespace Tests\Unit\Login; -use Brain\Monkey; use EightshiftBoilerplate\Main\MainExample; -use function Tests\setupMocks; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; beforeEach(function() { - Monkey\setUp(); - setupMocks(); + setBeforeEach(); $this->main = new MainExample([], ''); }); afterEach(function() { - Monkey\tearDown(); + setAfterEach(); }); test('Register method will call init hook', function () { diff --git a/tests/Manifest/ManifestCliTest.php b/tests/Manifest/ManifestCliTest.php index 0e85cc266..ab0d55d61 100644 --- a/tests/Manifest/ManifestCliTest.php +++ b/tests/Manifest/ManifestCliTest.php @@ -2,59 +2,49 @@ namespace Tests\Unit\Manifest; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\Manifest\ManifestCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->manifest = new ManifestCli('boilerplate'); + $this->mock = new ManifestCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); test('Manifest CLI command will correctly copy the Manifest class with defaults', function () { - $manifest = $this->manifest; - $manifest([], []); - - // Check the output dir if the generated method is correctly generated. - $generatedManifest = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/Manifest/Manifest.php'); - $this->assertStringContainsString('class Manifest extends AbstractManifest', $generatedManifest); - $this->assertStringContainsString('setAssetsManifestRaw', $generatedManifest); - $this->assertStringContainsString('manifest-item', $generatedManifest); - $this->assertStringNotContainsString('random string', $generatedManifest); + $mock = $this->mock; + $mock([], []); + + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}Manifest{$sep}Manifest.php")); + + $this->assertStringContainsString('class Manifest extends AbstractManifest', $output); + $this->assertStringContainsString('setAssetsManifestRaw', $output); + $this->assertStringContainsString('manifest-item', $output); + $this->assertStringNotContainsString('random string', $output); }); test('Manifest CLI command will correctly copy the Manifest class with set arguments', function () { - $manifest = $this->manifest; - $manifest([], [ + $mock = $this->mock; + $mock([], [ 'namespace' => 'MyTheme', ]); - // Check the output dir if the generated method is correctly generated. - $generatedManifest = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/Manifest/Manifest.php'); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}Manifest{$sep}Manifest.php")); - $this->assertStringContainsString('namespace MyTheme\Manifest;', $generatedManifest); + $this->assertStringContainsString('namespace MyTheme\Manifest;', $output); }); test('Manifest CLI documentation is correct', function () { - expect($this->manifest->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/Media/MediaCliTest.php b/tests/Media/MediaCliTest.php index 4b16d26eb..2d71d884f 100644 --- a/tests/Media/MediaCliTest.php +++ b/tests/Media/MediaCliTest.php @@ -20,7 +20,7 @@ test('Media CLI command will correctly copy the Media class with defaults', function () { $mock = $this->mediaCli; - $mock([], $mock->getDevelopArgs([])); + $mock([], $mock->getDefaultArgs()); // Check the output dir if the generated method is correctly generated. $generatedMedia = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/Media/Media.php'); diff --git a/tests/Menu/MenuCliTest.php b/tests/Menu/MenuCliTest.php index bd6a2cc20..4a023433b 100644 --- a/tests/Menu/MenuCliTest.php +++ b/tests/Menu/MenuCliTest.php @@ -2,65 +2,52 @@ namespace Tests\Unit\Menu; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\Menu\MenuCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->menu = new MenuCli('boilerplate'); + $this->mock = new MenuCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); -}); + setAfterEach(); + unset($this->mock); +}); test('Menu CLI command will correctly copy the Menu class with defaults', function () { - $menu = $this->menu; - $menu([], []); + $mock = $this->mock; + $mock([], []); - // Check the output dir if the generated method is correctly generated. - $generatedMenu = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/Menu/Menu.php'); - $this->assertStringContainsString('class Menu extends AbstractMenu', $generatedMenu); - $this->assertStringContainsString('header_main_nav', $generatedMenu); - $this->assertStringNotContainsString('rendom string', $generatedMenu); -}); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}Menu{$sep}Menu.php")); + $this->assertStringContainsString('class Menu extends AbstractMenu', $output); + $this->assertStringContainsString('header_main_nav', $output); + $this->assertStringNotContainsString('rendom string', $output); +}); test('Menu CLI command will correctly copy the Menu class with set arguments', function () { - $menu = $this->menu; - $menu([], [ + $mock = $this->mock; + $mock([], [ 'namespace' => 'CoolTheme', ]); - // Check the output dir if the generated method is correctly generated. - $generatedMenu = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/Menu/Menu.php'); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}Menu{$sep}Menu.php")); - $this->assertStringContainsString('class Menu extends AbstractMenu', $generatedMenu); - $this->assertStringContainsString('namespace CoolTheme\Menu;', $generatedMenu); - $this->assertStringContainsString('header_main_nav', $generatedMenu); - $this->assertStringNotContainsString('rendom string', $generatedMenu); + $this->assertStringContainsString('class Menu extends AbstractMenu', $output); + $this->assertStringContainsString('namespace CoolTheme\Menu;', $output); + $this->assertStringContainsString('header_main_nav', $output); + $this->assertStringNotContainsString('rendom string', $output); }); - test('Menu CLI documentation is correct', function () { - expect($this->menu->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/ModifyAdminAppearance/ModifyAdminAppearanceCliTest.php b/tests/ModifyAdminAppearance/ModifyAdminAppearanceCliTest.php index 748ff7b35..e46e1b60c 100644 --- a/tests/ModifyAdminAppearance/ModifyAdminAppearanceCliTest.php +++ b/tests/ModifyAdminAppearance/ModifyAdminAppearanceCliTest.php @@ -2,64 +2,50 @@ namespace Tests\Unit\ModifyAdminAppearance; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\ModifyAdminAppearance\ModifyAdminAppearanceCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); -$wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - -$wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - -$this->modifyAdminAppearance = new ModifyAdminAppearanceCli('boilerplate'); + $this->mock = new ModifyAdminAppearanceCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); test('ModifyAdminAppearance CLI command will correctly copy the ModifyAdminAppearance class with defaults', function () { - $modifyAdminAppearance = $this->modifyAdminAppearance; - $modifyAdminAppearance([], []); - - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/src/ModifyAdminAppearance/ModifyAdminAppearance.php'; + $mock = $this->mock; + $mock([], []); - // Check the output dir if the generated method is correctly generated. - $generatedModifyAdminAppearance = \file_get_contents($outputPath); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}ModifyAdminAppearance{$sep}ModifyAdminAppearance.php")); - $this->assertStringContainsString('class ModifyAdminAppearance implements ServiceInterface', $generatedModifyAdminAppearance); - $this->assertStringContainsString('@package EightshiftLibs\ModifyAdminAppearance', $generatedModifyAdminAppearance); - $this->assertStringContainsString('namespace EightshiftLibs\ModifyAdminAppearance', $generatedModifyAdminAppearance); - $this->assertStringNotContainsString('footer.php', $generatedModifyAdminAppearance); - $this->assertFileExists($outputPath); + $this->assertStringContainsString('class ModifyAdminAppearance implements ServiceInterface', $output); + $this->assertStringContainsString('@package EightshiftLibs\ModifyAdminAppearance', $output); + $this->assertStringContainsString('namespace EightshiftLibs\ModifyAdminAppearance', $output); + $this->assertStringNotContainsString('footer.php', $output); }); test('ModifyAdminAppearance CLI command will correctly copy the ModifyAdminAppearance class with set arguments', function () { - $modifyAdminAppearance = $this->modifyAdminAppearance; - $modifyAdminAppearance([], [ + $mock = $this->mock; + $mock([], [ 'namespace' => 'CoolTheme', ]); - // Check the output dir if the generated method is correctly generated. - $generatedModifyAdminAppearance = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/ModifyAdminAppearance/ModifyAdminAppearance.php'); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}ModifyAdminAppearance{$sep}ModifyAdminAppearance.php")); - $this->assertStringContainsString('namespace CoolTheme\ModifyAdminAppearance;', $generatedModifyAdminAppearance); + $this->assertStringContainsString('namespace CoolTheme\ModifyAdminAppearance;', $output); }); test('ModifyAdminAppearance CLI documentation is correct', function () { - expect($this->modifyAdminAppearance->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/Readme/ReadmeCliTest.php b/tests/Readme/ReadmeCliTest.php index 2f61695de..53ee0a899 100644 --- a/tests/Readme/ReadmeCliTest.php +++ b/tests/Readme/ReadmeCliTest.php @@ -2,67 +2,77 @@ namespace Tests\Unit\Readme; +use EightshiftLibs\Cli\ParentGroups\CliCreate; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\Readme\ReadmeCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); -$wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - -$wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - -$this->readme = new ReadmeCli('boilerplate'); + $this->mock = new ReadmeCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); -test('Readme CLI command will correctly copy the readme file with defaults', function () { - $readme = $this->readme; - $readme([], $readme->getDevelopArgs([])); +//---------------------------------------------------------------------------------// - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/README.md'; +test('getCommandParentName will return correct value', function () { + expect($this->mock->getCommandParentName()) + ->toBeString() + ->toEqual(CliCreate::COMMAND_NAME); +}); - // Check the output dir if the generated method is correctly generated. - $generatedReadme = \file_get_contents($outputPath); +//---------------------------------------------------------------------------------// - $this->assertStringContainsString('This is the official repository of the {Project name}.', $generatedReadme); - $this->assertStringNotContainsString('footer.php', $generatedReadme); - $this->assertFileExists($outputPath); +test('getCommandName will return correct value', function () { + expect($this->mock->getCommandName()) + ->toBeString() + ->toEqual('readme'); }); -test('Readme CLI command will run under custom command name', function () { - $readme = $this->readme; - $result = $readme->getCommandName(); +//---------------------------------------------------------------------------------// - $this->assertStringContainsString('readme', $result); +test('getDefaultArgs will return correct array', function () { + expect($this->mock->getDefaultArgs()) + ->toBeArray() + ->toHaveKeys(['path']); }); -test('Readme CLI command will correctly copy the readme in the custom folder with set arguments', function () { - $readme = $this->readme; - $readme([], [ - 'root' => './test', - ]); +//---------------------------------------------------------------------------------// - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/test/README.md'; +test('getDoc will return correct array', function () { + $docs = $this->mock->getDoc(); - $this->assertFileExists($outputPath); + expect($docs) + ->toBeArray() + ->toHaveKeys(['shortdesc', 'synopsis', 'longdesc']) + ->and(count($docs['synopsis']))->toEqual(1) + ->and($docs['synopsis'][0]['name'])->toEqual('path'); }); -test('Readme CLI documentation is correct', function () { - expect($this->readme->getDoc())->toBeArray(); +//---------------------------------------------------------------------------------// + +test('__invoke will will correctly copy example class with default args', function () { + $mock = $this->mock; + $mock([], [ + 'path' => Components::getProjectPaths('cliOutput'), + ]); + + $output = \file_get_contents(Components::getProjectPaths('cliOutput', 'README.md')); + + expect($output) + ->toContain( + 'This is the official repository of the {Project name}.', + 'Installation', + 'Once you clone this repository, you\'ll need to build it:', + 'Development', + 'Environments', + ); }); diff --git a/tests/Rest/Fields/FieldCliTest.php b/tests/Rest/Fields/FieldCliTest.php index b4f14543a..ca2e20a95 100644 --- a/tests/Rest/Fields/FieldCliTest.php +++ b/tests/Rest/Fields/FieldCliTest.php @@ -2,63 +2,51 @@ namespace Tests\Unit\CustomPostType; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\Rest\Fields\FieldCli; -use Exception; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->field = new FieldCli('boilerplate'); + $this->mock = new FieldCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); -}); + setAfterEach(); + unset($this->mock); +}); test('REST field CLI command will correctly copy the field class with defaults', function () { - $field = $this->field; - $field([], $field->getDevelopArgs([])); - - // Check the output dir if the generated method is correctly generated. - $generatedField = \file_get_contents(\dirname(__FILE__, 4) . '/cliOutput/src/Rest/Fields/TitleField.php'); - - $this->assertStringContainsString('class TitleField extends AbstractField implements CallableFieldInterface', $generatedField); - $this->assertStringContainsString('return \'title\';', $generatedField); - $this->assertStringContainsString('return \'post\';', $generatedField); - $this->assertStringContainsString('get_callback', $generatedField); - $this->assertStringContainsString('rest_ensure_response', $generatedField); - $this->assertStringNotContainsString('ExampleRoute', $generatedField); + $mock = $this->mock; + $mock([], $mock->getDefaultArgs()); + + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}Rest{$sep}Fields{$sep}TitleField.php")); + + $this->assertStringContainsString('class TitleField extends AbstractField implements CallableFieldInterface', $output); + $this->assertStringContainsString('return \'title\';', $output); + $this->assertStringContainsString('return \'post\';', $output); + $this->assertStringContainsString('get_callback', $output); + $this->assertStringContainsString('rest_ensure_response', $output); + $this->assertStringNotContainsString('ExampleRoute', $output); }); -test('REST field CLI command will correctly copy the field class with arguments', function ($fieldNameArguments) { - $field = $this->field; - $field([], $fieldNameArguments); - $fullFieldName = "{$this->field->getFileName($fieldNameArguments['field_name'])}Field"; - $objectType = $fieldNameArguments['object_type']; +test('REST field CLI command will correctly copy the field class with arguments', function ($mockNameArguments) { + $mock = $this->mock; + $mock([], $mockNameArguments); + + $fullFieldName = "{$this->mock->getFileName($mockNameArguments['field_name'])}Field"; + $objectType = $mockNameArguments['object_type']; - // Check the output dir if the generated method is correctly generated. - $generatedField = \file_get_contents(\dirname(__FILE__, 4) . "/cliOutput/src/Rest/Fields/{$fullFieldName}.php"); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}Rest{$sep}Fields{$sep}{$fullFieldName}.php")); - $this->assertStringContainsString("class {$fullFieldName} extends AbstractField implements CallableFieldInterface", $generatedField); - $this->assertStringContainsString("return '{$objectType}';", $generatedField); - $this->assertStringNotContainsString('example-post-type', $generatedField); - $this->assertStringNotContainsString('example-field', $generatedField); + $this->assertStringContainsString("class {$fullFieldName} extends AbstractField implements CallableFieldInterface", $output); + $this->assertStringContainsString("return '{$objectType}';", $output); + $this->assertStringNotContainsString('example-post-type', $output); + $this->assertStringNotContainsString('example-field', $output); })->with('correctFieldNameArguments'); diff --git a/tests/Rest/Routes/RouteCliTest.php b/tests/Rest/Routes/RouteCliTest.php index a7842af11..e8afb9111 100644 --- a/tests/Rest/Routes/RouteCliTest.php +++ b/tests/Rest/Routes/RouteCliTest.php @@ -2,67 +2,51 @@ namespace Tests\Unit\CustomPostType; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\Rest\Routes\RouteCli; -use Exception; -use InvalidArgumentException; - -use function Tests\deleteCliOutput; -use function Tests\mock; -/** - * Mock before tests. - */ -beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); +use function Tests\setAfterEach; +use function Tests\setBeforeEach; - $wpCliMock - ->shouldReceive('error') - ->andReturnUsing( - function ($errorMessage) { - throw new InvalidArgumentException($errorMessage); - } - ); +beforeEach(function () { + setBeforeEach(); - $this->route = new RouteCli('boilerplate'); + $this->mock = new RouteCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(\dirname(__FILE__, 4) . '/cliOutput'); + setAfterEach(); + + unset($this->mock); }); test('REST route CLI command will correctly copy the field class with defaults', function () { - $route = $this->route; - $route([], $route->getDevelopArgs([])); - - // Check the output dir if the generated method is correctly generated. - $generatedField = \file_get_contents(\dirname(__FILE__, 4) . '/cliOutput/src/Rest/Routes/TestRoute.php'); - - $this->assertStringContainsString('class TestRoute extends AbstractRoute implements CallableRouteInterface', $generatedField); - $this->assertStringContainsString('\'methods\' => ', $generatedField); - $this->assertStringContainsString('\'callback\' => ', $generatedField); - $this->assertStringContainsString('\'permission_callback\' => ', $generatedField); - $this->assertStringContainsString('function getCallbackArguments', $generatedField); - $this->assertStringContainsString('function routeCallback', $generatedField); + $mock = $this->mock; + $mock([], $mock->getDefaultArgs()); + + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}Rest{$sep}Routes{$sep}TestRoute.php")); + + $this->assertStringContainsString('class TestRoute extends AbstractRoute implements CallableRouteInterface', $output); + $this->assertStringContainsString('\'methods\' => ', $output); + $this->assertStringContainsString('\'callback\' => ', $output); + $this->assertStringContainsString('\'permission_callback\' => ', $output); + $this->assertStringContainsString('function getCallbackArguments', $output); + $this->assertStringContainsString('function routeCallback', $output); }); -test('REST route CLI command will correctly copy the field class with arguments', function ($routeArguments) { - $route = $this->route; - $route([], $routeArguments); +test('REST route CLI command will correctly copy the field class with arguments', function ($mockArguments) { + $mock = $this->mock; + $mock([], $mockArguments); - $full_route_name = "{$this->route->getFileName($routeArguments['endpoint_slug'])}Route"; - $method_to_const = RouteCli::VERB_ENUM[\strtolower($routeArguments['method'])] ?? ''; + $full_route_name = "{$this->mock->getFileName($mockArguments['endpoint_slug'])}Route"; + $method_to_const = RouteCli::VERB_ENUM[\strtolower($mockArguments['method'])] ?? ''; - // Check the output dir if the generated method is correctly generated. - $generatedField = \file_get_contents(\dirname(__FILE__, 4) . "/cliOutput/src/Rest/Routes/{$full_route_name}.php"); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}Rest{$sep}Routes{$sep}{$full_route_name}.php")); - $this->assertStringContainsString("class {$full_route_name} extends AbstractRoute implements CallableRouteInterface", $generatedField); - $this->assertStringContainsString("'methods' => {$method_to_const}", $generatedField); + $this->assertStringContainsString("class {$full_route_name} extends AbstractRoute implements CallableRouteInterface", $output); + $this->assertStringContainsString("'methods' => {$method_to_const}", $output); })->with('correctRouteArguments'); diff --git a/tests/Services/ServiceExampleCliTest.php b/tests/Services/ServiceExampleCliTest.php index a0af46b8a..d516cea85 100644 --- a/tests/Services/ServiceExampleCliTest.php +++ b/tests/Services/ServiceExampleCliTest.php @@ -2,70 +2,53 @@ namespace Tests\Unit\Services; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\Services\ServiceExampleCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); -$wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - -$wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - -$this->services = new ServiceExampleCli('boilerplate'); + $this->mock = new ServiceExampleCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); test('Services CLI command will correctly copy the Services class with defaults', function () { - $services = $this->services; - $services([], $services->getDevelopArgs([])); + $mock = $this->mock; + $mock([], $mock->getDefaultArgs()); - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/src/TestFolder/TMP/TestTest.php'; + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}TestFolder{$sep}TMP{$sep}TestTest.php")); - // Check the output dir if the generated method is correctly generated. - $generatedService = \file_get_contents($outputPath); - - $this->assertStringContainsString('class TestTest implements ServiceInterface', $generatedService); - $this->assertStringContainsString('namespace EightshiftLibs\TestFolder\TMP', $generatedService); - $this->assertStringContainsString('@package EightshiftLibs\TestFolder\TMP', $generatedService); - $this->assertStringNotContainsString('footer.php', $generatedService); - $this->assertFileExists($outputPath); + $this->assertStringContainsString('class TestTest implements ServiceInterface', $output); + $this->assertStringContainsString('namespace EightshiftLibs\TestFolder\TMP', $output); + $this->assertStringContainsString('@package EightshiftLibs\TestFolder\TMP', $output); + $this->assertStringNotContainsString('footer.php', $output); }); test('Services CLI command will correctly copy the Services class with set arguments', function () { - $services = $this->services; - $services([], [ + $mock = $this->mock; + $mock([], [ 'namespace' => 'CoolTheme', 'folder' => 'FolderName', 'file_name' => 'FileName', ]); - $outputPath = \dirname(__FILE__, 3) . '/cliOutput/src/FolderName/FileName.php'; - - // Check the output dir if the generated method is correctly generated. - $generatedService = \file_get_contents($outputPath); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}FolderName{$sep}FileName.php")); - $this->assertStringContainsString('class FileName implements ServiceInterface', $generatedService); - $this->assertStringContainsString('namespace CoolTheme\FolderName', $generatedService); - $this->assertStringContainsString('@package CoolTheme\FolderName', $generatedService); - $this->assertFileExists($outputPath); + $this->assertStringContainsString('class FileName implements ServiceInterface', $output); + $this->assertStringContainsString('namespace CoolTheme\FolderName', $output); + $this->assertStringContainsString('@package CoolTheme\FolderName', $output); }); test('Services CLI documentation is correct', function () { - expect($this->services->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/Setup/SetupCliTest.php b/tests/Setup/SetupCliTest.php index 6716d596c..9225ff791 100644 --- a/tests/Setup/SetupCliTest.php +++ b/tests/Setup/SetupCliTest.php @@ -2,57 +2,38 @@ namespace Tests\Unit\Setup; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\Setup\SetupCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->setup = new SetupCli('boilerplate'); + $this->mock = new SetupCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); test('Setup CLI command will correctly copy the Setup class with defaults', function () { - $setup = $this->setup; - $setup([], $setup->getDevelopArgs([])); + $sep = \DIRECTORY_SEPARATOR; - // Check the output dir if the generated method is correctly generated. - $generatedFile = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/setup.json'); - $this->assertStringContainsString('twentytwentyone', $generatedFile); - $this->assertStringNotContainsString('random string', $generatedFile); -}); - -test('Setup CLI command will correctly copy the Setup class with set parameters', function () { - $setup = $this->setup; - $setup([], [ - 'root' => 'test', + $mock = $this->mock; + $mock([], [ + 'path' => Components::getProjectPaths('cliOutput', 'setup'), + 'source_path' => Components::getProjectPaths('testsData', 'setup'), ]); - // Check the output dir if the generated method is correctly generated. - $generatedFile = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/test/setup.json'); - $this->assertStringContainsString('twentytwentyone', $generatedFile); - $this->assertStringNotContainsString('random string', $generatedFile); + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "setup{$sep}setup.json")); + + expect($output)->toContain('staging'); }); test('Setup CLI documentation is correct', function () { - expect($this->setup->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/Setup/UpdateCliTest.php b/tests/Setup/UpdateCliTest.php index 97c3114dd..2f8f50cc1 100644 --- a/tests/Setup/UpdateCliTest.php +++ b/tests/Setup/UpdateCliTest.php @@ -8,47 +8,27 @@ use function Brain\Monkey\Functions\when; use function Tests\deleteCliOutput; use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('runcommand') - ->andReturnUsing(function ($cmd) { - putenv("COMMAND={$cmd}"); - }); - - $wpCliMock - ->shouldReceive('log') - ->andReturnArg(0); - - $this->update = new UpdateCli('boilerplate'); + $this->mock = new UpdateCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); test('Update CLI command will correctly throw an exception if setup.json does not exist or has the wrong filename', function () { - $update = $this->update; + $update = $this->mock; $update([], []); })->throws(Exception::class); test('Update CLI documentation is correct', function () { - expect($this->update->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/ThemeOptions/ThemeOptionsCliTest.php b/tests/ThemeOptions/ThemeOptionsCliTest.php index d8747f9bc..7c23b297c 100644 --- a/tests/ThemeOptions/ThemeOptionsCliTest.php +++ b/tests/ThemeOptions/ThemeOptionsCliTest.php @@ -2,66 +2,57 @@ namespace Tests\Unit\ThemeOptions; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\ThemeOptions\ThemeOptionsCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->themeOptions = new ThemeOptionsCli('boilerplate'); + $this->mock = new ThemeOptionsCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); test('Custom theme options CLI command will correctly copy the theme options class with defaults', function () { - $themeOptions = $this->themeOptions; - $themeOptions([], []); + $mock = $this->mock; + $mock([], []); - // Check the output dir if the generated method is correctly generated. - $generatedMeta = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/ThemeOptions/ThemeOptions.php'); + $sep = \DIRECTORY_SEPARATOR; + $output = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}ThemeOptions{$sep}ThemeOptions.php")); - expect($generatedMeta) + expect($output) ->toBeString() - ->toContain('class ThemeOptions implements ServiceInterface') - ->toContain('acf_add_options_page') - ->toContain('acf_add_local_field_group') - ->toContain('createThemeOptionsPage') - ->toContain('registerThemeOptions') + ->toContain( + 'class ThemeOptions implements ServiceInterface', + 'acf_add_options_page', + 'acf_add_local_field_group', + 'createThemeOptionsPage', + 'registerThemeOptions' + ) ->not->toContain('someRandomMethod'); }); test('Custom theme options CLI documentation is correct', function () { - expect($this->themeOptions->getDoc())->toBeArray(); - $themeOptions = $this->themeOptions; + expect($this->mock->getDoc())->toBeArray(); + $mock = $this->mock; - $documentation = $themeOptions->getDoc(); + $mock = $mock->getDoc(); $descKey = 'shortdesc'; - expect($documentation) + expect($mock) ->toBeArray() ->toHaveKey($descKey); - expect($documentation[$descKey]) + expect($mock[$descKey]) ->toBeString() ->toBe('Create project Theme Options service class using ACF plugin.'); }); diff --git a/tests/View/EscapedViewCliTest.php b/tests/View/EscapedViewCliTest.php index 040c55eba..d22d57a06 100644 --- a/tests/View/EscapedViewCliTest.php +++ b/tests/View/EscapedViewCliTest.php @@ -2,48 +2,36 @@ namespace Tests\Unit\View; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\View\EscapedViewCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->escapedView = new EscapedViewCli('boilerplate'); + $this->mock = new EscapedViewCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); }); test('Escaped view command will correctly copy the EscapedView class with defaults', function () { - $escapedView = $this->escapedView; - $escapedView([], $escapedView->getDevelopArgs([])); + $mock = $this->mock; + $mock([], $mock->getDefaultArgs()); // Check the output dir if the generated method is correctly generated. - $generatedEscapedView = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/View/EscapedView.php'); + $sep = \DIRECTORY_SEPARATOR; + $mock = \file_get_contents(Components::getProjectPaths('cliOutput', "src{$sep}View{$sep}EscapedView.php")); - $this->assertNotEmpty($generatedEscapedView); - $this->assertStringContainsString('class EscapedView extends AbstractEscapedView implements ServiceInterface', $generatedEscapedView); - $this->assertStringContainsString('register', $generatedEscapedView); - expect($generatedEscapedView)->not-> toContain('someRandomMethod'); + $this->assertNotEmpty($mock); + $this->assertStringContainsString('class EscapedView extends AbstractEscapedView implements ServiceInterface', $mock); + $this->assertStringContainsString('register', $mock); + expect($mock)->not-> toContain('someRandomMethod'); }); test('Escaped view CLI documentation is correct', function () { - expect($this->escapedView->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/WpCli/WpCliExampleTest.php b/tests/WpCli/WpCliExampleTest.php index 641586fc9..0588e17de 100644 --- a/tests/WpCli/WpCliExampleTest.php +++ b/tests/WpCli/WpCliExampleTest.php @@ -8,52 +8,41 @@ use function Tests\deleteCliOutput; use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->customCommand = new WpCliExample(); + $this->mock = new WpCliExample('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); -}); + setAfterEach(); + unset($this->mock); +}); test('Register method will call init hook', function () { - $this->customCommand->register(); + $this->mock->register(); $this->assertSame(10, has_action('cli_init', 'EightshiftBoilerplate\WpCli\WpCliExample->registerCommand()')); }); test('Prepare command docs returns correct doc', function() { - $customCommand = $this->customCommand->getDocs(); + $customCommand = $this->mock->getDocs(); $this->assertIsArray($customCommand); $this->assertArrayHasKey('shortdesc', $customCommand); }); test('Custom command class is callable', function() { - $customCommand = $this->customCommand; + $customCommand = $this->mock; expect($customCommand)->toBeCallable(); }); test('Custom command example documentation is correct', function () { - expect($this->customCommand->getDocs())->toBeArray(); + expect($this->mock->getDocs())->toBeArray(); }); diff --git a/tests/WpCli/WpCliTest.php b/tests/WpCli/WpCliTest.php index 916ae8324..0cb9a35e8 100644 --- a/tests/WpCli/WpCliTest.php +++ b/tests/WpCli/WpCliTest.php @@ -2,52 +2,41 @@ namespace Tests\Unit\WpCli; -use EightshiftBoilerplate\WpCli\WpCliExample; +use EightshiftLibs\Helpers\Components; use EightshiftLibs\WpCli\WpCli; -use function Tests\deleteCliOutput; -use function Tests\mock; +use function Tests\setAfterEach; +use function Tests\setBeforeEach; -/** - * Mock before tests. - */ beforeEach(function () { - $wpCliMock = mock('alias:WP_CLI'); + setBeforeEach(); - $wpCliMock - ->shouldReceive('success') - ->andReturnArg(0); - - $wpCliMock - ->shouldReceive('error') - ->andReturnArg(0); - - $this->customCommand = new WpCli('boilerplate'); + $this->mock = new WpCli('boilerplate'); }); -/** - * Cleanup after tests. - */ afterEach(function () { - deleteCliOutput(); + setAfterEach(); + + unset($this->mock); }); test('Custom command CLI command will correctly copy the Custom command class with defaults', function () { - $customCommand = $this->customCommand; - $customCommand([], $customCommand->getDevelopArgs([])); + $mock = $this->mock; + $mock([], $mock->getDefaultArgs()); // Check the output dir if the generated method is correctly generated. - $customCommand = \file_get_contents(\dirname(__FILE__, 3) . '/cliOutput/src/WpCli/TestWpCli.php'); - - $this->assertStringContainsString('class TestWpCli implements ServiceCliInterface', $customCommand); - $this->assertStringContainsString('function register', $customCommand); - $this->assertStringContainsString('function registerCommand', $customCommand); - $this->assertStringContainsString('function getDocs', $customCommand); - $this->assertStringContainsString('function __invoke', $customCommand); + $sep = \DIRECTORY_SEPARATOR; + $mock = \file_get_contents(Components::getProjectPaths('srcDestination', "WpCli{$sep}TestWpCli.php")); + + $this->assertStringContainsString('class TestWpCli implements ServiceCliInterface', $mock); + $this->assertStringContainsString('function register', $mock); + $this->assertStringContainsString('function registerCommand', $mock); + $this->assertStringContainsString('function getDocs', $mock); + $this->assertStringContainsString('function __invoke', $mock); }); test('Custom command CLI documentation is correct', function () { - expect($this->customCommand->getDoc())->toBeArray(); + expect($this->mock->getDoc())->toBeArray(); }); diff --git a/tests/data/assets/assets.php b/tests/data/assets/assets.php new file mode 100644 index 000000000..9e1d3e5a3 --- /dev/null +++ b/tests/data/assets/assets.php @@ -0,0 +1,2 @@ + Date: Tue, 5 Jul 2022 12:16:32 +0200 Subject: [PATCH 02/52] updating comments --- src/AdminMenus/AdminMenuCli.php | 2 +- src/AdminMenus/AdminReusableBlocksMenuCli.php | 2 +- src/AdminMenus/AdminSubMenuCli.php | 2 +- src/AnalyticsGdpr/AnalyticsGdprCli.php | 2 +- src/BlockPatterns/BlockPatternCli.php | 2 +- src/Blocks/BlocksCli.php | 13 ++++++++++--- src/Blocks/UseAssetsCli.php | 2 +- src/Blocks/UseBlockCli.php | 2 +- src/Blocks/UseComponentCli.php | 2 +- src/Blocks/UseGlobalAssetsCli.php | 2 +- src/Blocks/UseManifestCli.php | 8 ++++---- src/Blocks/UseStorybookCli.php | 4 ++-- src/Blocks/UseVariationCli.php | 2 +- src/Blocks/UseWrapperCli.php | 6 +++--- src/Build/BuildCli.php | 2 +- src/CiExclude/CiExcludeCli.php | 2 +- src/Columns/Media/WebPMediaColumnCli.php | 2 +- src/Config/ConfigCli.php | 2 +- src/ConfigProject/ConfigProjectCli.php | 2 +- src/CustomMeta/AcfMetaCli.php | 2 +- src/CustomPostType/PostTypeCli.php | 2 +- src/CustomTaxonomy/TaxonomyCli.php | 2 +- src/Db/ExportCli.php | 4 ++-- src/Db/ImportCli.php | 2 +- src/Enqueue/Admin/EnqueueAdminCli.php | 2 +- src/Enqueue/Blocks/EnqueueBlocksCli.php | 2 +- src/Enqueue/Theme/EnqueueThemeCli.php | 2 +- src/Geolocation/GeolocationCli.php | 4 ++-- src/GitIgnore/GitIgnoreCli.php | 2 +- src/I18n/I18nCli.php | 2 +- src/Init/InitBlocksCli.php | 6 +++--- src/Init/InitProjectCli.php | 2 +- src/Init/InitThemeCli.php | 2 +- src/Login/LoginCli.php | 2 +- src/Main/MainCli.php | 2 +- src/Manifest/ManifestCli.php | 2 +- src/Media/MediaCli.php | 2 +- src/Media/RegenerateWebPMediaCli.php | 16 ++++++++-------- src/Media/UseWebPMediaCli.php | 2 +- src/Menu/MenuCli.php | 2 +- .../ModifyAdminAppearanceCli.php | 2 +- src/Readme/ReadmeCli.php | 2 +- src/Rest/Fields/FieldCli.php | 2 +- src/Rest/Routes/LoadMore/LoadMoreRouteCli.php | 2 +- src/Rest/Routes/RouteCli.php | 2 +- src/Services/ServiceExampleCli.php | 2 +- src/Setup/SetupCli.php | 2 +- src/Setup/UpdateCli.php | 4 ++-- src/ThemeOptions/ThemeOptionsCli.php | 2 +- src/View/EscapedViewCli.php | 2 +- src/WpCli/WpCli.php | 2 +- 51 files changed, 78 insertions(+), 71 deletions(-) diff --git a/src/AdminMenus/AdminMenuCli.php b/src/AdminMenus/AdminMenuCli.php index d97204aeb..0a823ed07 100644 --- a/src/AdminMenus/AdminMenuCli.php +++ b/src/AdminMenus/AdminMenuCli.php @@ -113,7 +113,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --title='Content' --menu_title='content' --capability='edit_posts' --menu_slug='es-content' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --title='Content' --menu_title='content' --capability='edit_posts' --menu_slug='es-content' ## RESOURCES diff --git a/src/AdminMenus/AdminReusableBlocksMenuCli.php b/src/AdminMenus/AdminReusableBlocksMenuCli.php index 6829a7f79..a1206832b 100644 --- a/src/AdminMenus/AdminReusableBlocksMenuCli.php +++ b/src/AdminMenus/AdminReusableBlocksMenuCli.php @@ -109,7 +109,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/AdminMenus/AdminSubMenuCli.php b/src/AdminMenus/AdminSubMenuCli.php index 9af22fdb4..bda05eb09 100644 --- a/src/AdminMenus/AdminSubMenuCli.php +++ b/src/AdminMenus/AdminSubMenuCli.php @@ -104,7 +104,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --parent_slug='shop' --title='Content' --menu_title='content' --capability='edit_posts' --menu_slug='es-content' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --parent_slug='shop' --title='Content' --menu_title='content' --capability='edit_posts' --menu_slug='es-content' ## RESOURCES diff --git a/src/AnalyticsGdpr/AnalyticsGdprCli.php b/src/AnalyticsGdpr/AnalyticsGdprCli.php index 6ea855158..0fb2407c6 100644 --- a/src/AnalyticsGdpr/AnalyticsGdprCli.php +++ b/src/AnalyticsGdpr/AnalyticsGdprCli.php @@ -57,7 +57,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/BlockPatterns/BlockPatternCli.php b/src/BlockPatterns/BlockPatternCli.php index 6be1d73c8..d94e48346 100644 --- a/src/BlockPatterns/BlockPatternCli.php +++ b/src/BlockPatterns/BlockPatternCli.php @@ -100,7 +100,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --title='Button' --description='This is description' --capability='edit_posts' --menu_slug='es-content' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --title='Button' --description='This is description' --capability='edit_posts' --menu_slug='es-content' ## RESOURCES diff --git a/src/Blocks/BlocksCli.php b/src/Blocks/BlocksCli.php index 7f0c618ce..8d5e7beba 100644 --- a/src/Blocks/BlocksCli.php +++ b/src/Blocks/BlocksCli.php @@ -48,13 +48,20 @@ public function getDoc(): array { return [ 'shortdesc' => 'Create blocks service class.', - 'longdesc' => " + 'longdesc' => $this->prepareLongDesc(" + ## USAGE + This file is a main entrypoint for all our block editor setup. We use it to register all blocks, limit what blocks user can see, and lots more. ## EXAMPLES - $ wp boilerplate create_blocks - ", + + # Create service class: + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} + + ## RESOURCES + https://github.com/infinum/eightshift-libs/blob/develop/src/Blocks/BlocksExample.php + "), ]; } diff --git a/src/Blocks/UseAssetsCli.php b/src/Blocks/UseAssetsCli.php index e863386b5..8aea9caa3 100644 --- a/src/Blocks/UseAssetsCli.php +++ b/src/Blocks/UseAssetsCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Copy assets. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Blocks/UseBlockCli.php b/src/Blocks/UseBlockCli.php index 6aea2058e..88bcb4669 100644 --- a/src/Blocks/UseBlockCli.php +++ b/src/Blocks/UseBlockCli.php @@ -76,7 +76,7 @@ public function getDoc(): array ## EXAMPLES # Copy block by name. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --name='paragraph' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --name='paragraph' ## RESOURCES diff --git a/src/Blocks/UseComponentCli.php b/src/Blocks/UseComponentCli.php index d3c017d2e..45b602e00 100644 --- a/src/Blocks/UseComponentCli.php +++ b/src/Blocks/UseComponentCli.php @@ -83,7 +83,7 @@ public function getDoc(): array ## EXAMPLES # Copy component by name: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --name='paragraph' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --name='paragraph' ## RESOURCES diff --git a/src/Blocks/UseGlobalAssetsCli.php b/src/Blocks/UseGlobalAssetsCli.php index 3c03f18f3..9a7896938 100644 --- a/src/Blocks/UseGlobalAssetsCli.php +++ b/src/Blocks/UseGlobalAssetsCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Copy global assets. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Blocks/UseManifestCli.php b/src/Blocks/UseManifestCli.php index d826064c0..86da2d61f 100644 --- a/src/Blocks/UseManifestCli.php +++ b/src/Blocks/UseManifestCli.php @@ -47,13 +47,13 @@ public function getCommandName(): string public function getDoc(): array { return [ - 'shortdesc' => 'Create blocks manifest.json file.', - 'longdesc' => " + 'shortdesc' => 'Copy global assets manifest.json file from our library to your project.', + 'longdesc' => $this->prepareLongDesc(" This file is a block editor main setting file where you can find color, option and much more. ## EXAMPLES - $ wp boilerplate create manifest - ", + $ wp {$this->commandParentName} create manifest + "), ]; } diff --git a/src/Blocks/UseStorybookCli.php b/src/Blocks/UseStorybookCli.php index 9933cdea0..afec59d30 100644 --- a/src/Blocks/UseStorybookCli.php +++ b/src/Blocks/UseStorybookCli.php @@ -47,7 +47,7 @@ public function getCommandName(): string public function getDoc(): array { return [ - 'shortdesc' => 'Setup storybook in your project.', + 'shortdesc' => 'Copy storybook config from our library to your project.', 'longdesc' => $this->prepareLongDesc(" ## USAGE @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Create Storybook config: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Blocks/UseVariationCli.php b/src/Blocks/UseVariationCli.php index da42904a9..87c9a36ce 100644 --- a/src/Blocks/UseVariationCli.php +++ b/src/Blocks/UseVariationCli.php @@ -76,7 +76,7 @@ public function getDoc(): array ## EXAMPLES # Copy variation by name. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --name='button-block' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --name='button-block' ## RESOURCES diff --git a/src/Blocks/UseWrapperCli.php b/src/Blocks/UseWrapperCli.php index c62ab10e0..23bc754fe 100644 --- a/src/Blocks/UseWrapperCli.php +++ b/src/Blocks/UseWrapperCli.php @@ -48,17 +48,17 @@ public function getDoc(): array { return [ 'shortdesc' => 'Copy wrapper from our library to your project.', - 'longdesc' => " + 'longdesc' => $this->prepareLongDesc(" ## EXAMPLES # Copy wrapper. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES Our wrapper can be found here: https://github.com/infinum/eightshift-frontend-libs/tree/develop/blocks/init/src/Blocks/wrapper - " + "), ]; } diff --git a/src/Build/BuildCli.php b/src/Build/BuildCli.php index d1ece9c97..9b630b1e3 100644 --- a/src/Build/BuildCli.php +++ b/src/Build/BuildCli.php @@ -93,7 +93,7 @@ public function getDoc(): array ## EXAMPLES # Copy file: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/CiExclude/CiExcludeCli.php b/src/CiExclude/CiExcludeCli.php index 937d32def..f51e4e108 100644 --- a/src/CiExclude/CiExcludeCli.php +++ b/src/CiExclude/CiExcludeCli.php @@ -94,7 +94,7 @@ public function getDoc(): array ## EXAMPLES # Copy file: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Columns/Media/WebPMediaColumnCli.php b/src/Columns/Media/WebPMediaColumnCli.php index d600ab4bf..f5d3821a1 100644 --- a/src/Columns/Media/WebPMediaColumnCli.php +++ b/src/Columns/Media/WebPMediaColumnCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Config/ConfigCli.php b/src/Config/ConfigCli.php index bbe0e75aa..de46e05d8 100644 --- a/src/Config/ConfigCli.php +++ b/src/Config/ConfigCli.php @@ -93,7 +93,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/ConfigProject/ConfigProjectCli.php b/src/ConfigProject/ConfigProjectCli.php index e42e36862..0272ab7d3 100644 --- a/src/ConfigProject/ConfigProjectCli.php +++ b/src/ConfigProject/ConfigProjectCli.php @@ -77,7 +77,7 @@ public function getDoc(): array ## EXAMPLES # Copy file: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/CustomMeta/AcfMetaCli.php b/src/CustomMeta/AcfMetaCli.php index 6542bff50..01621f7b3 100644 --- a/src/CustomMeta/AcfMetaCli.php +++ b/src/CustomMeta/AcfMetaCli.php @@ -77,7 +77,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/CustomPostType/PostTypeCli.php b/src/CustomPostType/PostTypeCli.php index 831b919de..799de2000 100644 --- a/src/CustomPostType/PostTypeCli.php +++ b/src/CustomPostType/PostTypeCli.php @@ -129,7 +129,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --label='Jobs' --slug='jobs' --rewrite_url='jobs' --rest_endpoint_slug='jobs' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --label='Jobs' --slug='jobs' --rewrite_url='jobs' --rest_endpoint_slug='jobs' ## RESOURCES diff --git a/src/CustomTaxonomy/TaxonomyCli.php b/src/CustomTaxonomy/TaxonomyCli.php index 9b7e38baa..bc101551a 100644 --- a/src/CustomTaxonomy/TaxonomyCli.php +++ b/src/CustomTaxonomy/TaxonomyCli.php @@ -104,7 +104,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --label='Job Positions' --slug='job-position' --rest_endpoint_slug='job-positions' --post_type_slug='user' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --label='Job Positions' --slug='job-position' --rest_endpoint_slug='job-positions' --post_type_slug='user' ## RESOURCES diff --git a/src/Db/ExportCli.php b/src/Db/ExportCli.php index efb3e308b..c2025ed2b 100644 --- a/src/Db/ExportCli.php +++ b/src/Db/ExportCli.php @@ -91,10 +91,10 @@ public function getDoc(): array ## EXAMPLES # Run db export command: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} # Run db export command without uploads folder: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --skip_uploads='true' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --skip_uploads='true' ## RESOURCES diff --git a/src/Db/ImportCli.php b/src/Db/ImportCli.php index 472fc8235..3e9ff1959 100644 --- a/src/Db/ImportCli.php +++ b/src/Db/ImportCli.php @@ -87,7 +87,7 @@ public function getDoc(): array ## EXAMPLES # Run db import command: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --from='production' --to='develop' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --from='production' --to='develop' ## RESOURCES diff --git a/src/Enqueue/Admin/EnqueueAdminCli.php b/src/Enqueue/Admin/EnqueueAdminCli.php index 11ba25d35..c740e28ae 100644 --- a/src/Enqueue/Admin/EnqueueAdminCli.php +++ b/src/Enqueue/Admin/EnqueueAdminCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Enqueue/Blocks/EnqueueBlocksCli.php b/src/Enqueue/Blocks/EnqueueBlocksCli.php index 7169de556..85429d4a6 100644 --- a/src/Enqueue/Blocks/EnqueueBlocksCli.php +++ b/src/Enqueue/Blocks/EnqueueBlocksCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Enqueue/Theme/EnqueueThemeCli.php b/src/Enqueue/Theme/EnqueueThemeCli.php index 04ef5241c..75ffe9edd 100644 --- a/src/Enqueue/Theme/EnqueueThemeCli.php +++ b/src/Enqueue/Theme/EnqueueThemeCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Geolocation/GeolocationCli.php b/src/Geolocation/GeolocationCli.php index 172b1ef04..4d25745fc 100644 --- a/src/Geolocation/GeolocationCli.php +++ b/src/Geolocation/GeolocationCli.php @@ -80,10 +80,10 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} # Create service class with custom cookie name: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --cookie_name='test_cookie' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --cookie_name='test_cookie' ## RESOURCES diff --git a/src/GitIgnore/GitIgnoreCli.php b/src/GitIgnore/GitIgnoreCli.php index 83eacf89a..0d17c0977 100644 --- a/src/GitIgnore/GitIgnoreCli.php +++ b/src/GitIgnore/GitIgnoreCli.php @@ -78,7 +78,7 @@ public function getDoc(): array ## EXAMPLES # Copy file: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/I18n/I18nCli.php b/src/I18n/I18nCli.php index a31e551c9..b2053245a 100644 --- a/src/I18n/I18nCli.php +++ b/src/I18n/I18nCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Init/InitBlocksCli.php b/src/Init/InitBlocksCli.php index c2fc8ef32..e1b5374f4 100644 --- a/src/Init/InitBlocksCli.php +++ b/src/Init/InitBlocksCli.php @@ -114,12 +114,12 @@ public function getDoc(): array { return [ 'shortdesc' => 'Create all files for blocks to work.', - 'longdesc' => " + 'longdesc' => $this->prepareLongDesc(" This command will copy all initial block, componens, manifests na service classes to you project in order to start using block editor. ## EXAMPLES - $ wp boilerplate create blocks_init - ", + $ wp {$this->commandParentName} create blocks_init + "), ]; } diff --git a/src/Init/InitProjectCli.php b/src/Init/InitProjectCli.php index 0f41a6cef..270f66662 100644 --- a/src/Init/InitProjectCli.php +++ b/src/Init/InitProjectCli.php @@ -90,7 +90,7 @@ public function getDoc(): array ## EXAMPLES # Setup project: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} "), ]; } diff --git a/src/Init/InitThemeCli.php b/src/Init/InitThemeCli.php index 7c5a6112b..13c9e2161 100644 --- a/src/Init/InitThemeCli.php +++ b/src/Init/InitThemeCli.php @@ -91,7 +91,7 @@ public function getDoc(): array ## EXAMPLES # Setup theme: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} "), ]; } diff --git a/src/Login/LoginCli.php b/src/Login/LoginCli.php index 19d181a6f..28dbcfd08 100644 --- a/src/Login/LoginCli.php +++ b/src/Login/LoginCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Main/MainCli.php b/src/Main/MainCli.php index 3f68adbcb..772aa7141 100644 --- a/src/Main/MainCli.php +++ b/src/Main/MainCli.php @@ -57,7 +57,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Manifest/ManifestCli.php b/src/Manifest/ManifestCli.php index bc3bba400..b7e94a719 100644 --- a/src/Manifest/ManifestCli.php +++ b/src/Manifest/ManifestCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Media/MediaCli.php b/src/Media/MediaCli.php index ca68c8b92..2a008c3c0 100644 --- a/src/Media/MediaCli.php +++ b/src/Media/MediaCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Media/RegenerateWebPMediaCli.php b/src/Media/RegenerateWebPMediaCli.php index b635828b0..4684896b4 100644 --- a/src/Media/RegenerateWebPMediaCli.php +++ b/src/Media/RegenerateWebPMediaCli.php @@ -114,28 +114,28 @@ public function getDoc(): array ## EXAMPLES # Regenerate all supported media to WebP format. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} # Regenerate only one attachment by ID. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --ids='16911' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --ids='16911' # Regenerate multiple attachments by IDs. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --ids='16911, 1692, 1302' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --ids='16911, 1692, 1302' # Force regenerate attachments no matter if they all-ready exist. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --force='true' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --force='true' # Regenerate media with diffferent quality. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --quality='90' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --quality='90' # Delete all WebP media formats. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --action='delete' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --action='delete' # Delete only one WebP attachment by ID. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --ids='16911' --action='delete' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --ids='16911' --action='delete' # Delete multiple WebP attachments by ID. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --ids='16911, 1692, 1302' --action='delete' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --ids='16911, 1692, 1302' --action='delete' "), ]; } diff --git a/src/Media/UseWebPMediaCli.php b/src/Media/UseWebPMediaCli.php index 7eb204ba9..d7670f09d 100644 --- a/src/Media/UseWebPMediaCli.php +++ b/src/Media/UseWebPMediaCli.php @@ -68,7 +68,7 @@ public function getDoc(): array ## EXAMPLES # Toggle frontend media to use WebP format. - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} "), ]; } diff --git a/src/Menu/MenuCli.php b/src/Menu/MenuCli.php index 0863edbcc..cb9304c77 100644 --- a/src/Menu/MenuCli.php +++ b/src/Menu/MenuCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/ModifyAdminAppearance/ModifyAdminAppearanceCli.php b/src/ModifyAdminAppearance/ModifyAdminAppearanceCli.php index 0a9a430d7..f1972b527 100644 --- a/src/ModifyAdminAppearance/ModifyAdminAppearanceCli.php +++ b/src/ModifyAdminAppearance/ModifyAdminAppearanceCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Readme/ReadmeCli.php b/src/Readme/ReadmeCli.php index 5701fd19e..72bd7f53b 100644 --- a/src/Readme/ReadmeCli.php +++ b/src/Readme/ReadmeCli.php @@ -78,7 +78,7 @@ public function getDoc(): array ## EXAMPLES # Copy file: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Rest/Fields/FieldCli.php b/src/Rest/Fields/FieldCli.php index c80194248..9521e9e15 100644 --- a/src/Rest/Fields/FieldCli.php +++ b/src/Rest/Fields/FieldCli.php @@ -84,7 +84,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --field_name='title' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --field_name='title' ## RESOURCES diff --git a/src/Rest/Routes/LoadMore/LoadMoreRouteCli.php b/src/Rest/Routes/LoadMore/LoadMoreRouteCli.php index 12d878eea..7defb03d3 100644 --- a/src/Rest/Routes/LoadMore/LoadMoreRouteCli.php +++ b/src/Rest/Routes/LoadMore/LoadMoreRouteCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Rest/Routes/RouteCli.php b/src/Rest/Routes/RouteCli.php index 8fbce1365..02d54b0a4 100644 --- a/src/Rest/Routes/RouteCli.php +++ b/src/Rest/Routes/RouteCli.php @@ -105,7 +105,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --endpoint_slug='test-route' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --endpoint_slug='test-route' ## RESOURCES diff --git a/src/Services/ServiceExampleCli.php b/src/Services/ServiceExampleCli.php index 5b6af6953..77bd3bb8b 100644 --- a/src/Services/ServiceExampleCli.php +++ b/src/Services/ServiceExampleCli.php @@ -88,7 +88,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --folder='test' --file_name='Test' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --folder='test' --file_name='Test' ## RESOURCES diff --git a/src/Setup/SetupCli.php b/src/Setup/SetupCli.php index ef61cadf2..f00f8b181 100644 --- a/src/Setup/SetupCli.php +++ b/src/Setup/SetupCli.php @@ -87,7 +87,7 @@ public function getDoc(): array ## EXAMPLES # Copy file: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Setup/UpdateCli.php b/src/Setup/UpdateCli.php index 903470944..eb33ee199 100644 --- a/src/Setup/UpdateCli.php +++ b/src/Setup/UpdateCli.php @@ -129,10 +129,10 @@ public function getDoc(): array ## EXAMPLES # Update everything: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} # Update everything but skip plugins: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --skip_plugins='true' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --skip_plugins='true' "), ]; } diff --git a/src/ThemeOptions/ThemeOptionsCli.php b/src/ThemeOptions/ThemeOptionsCli.php index 75bb5a34a..8e2f482ed 100644 --- a/src/ThemeOptions/ThemeOptionsCli.php +++ b/src/ThemeOptions/ThemeOptionsCli.php @@ -57,7 +57,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/View/EscapedViewCli.php b/src/View/EscapedViewCli.php index 468f0387c..cee1dff9d 100644 --- a/src/View/EscapedViewCli.php +++ b/src/View/EscapedViewCli.php @@ -56,7 +56,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/WpCli/WpCli.php b/src/WpCli/WpCli.php index c200b86f0..371e302fc 100644 --- a/src/WpCli/WpCli.php +++ b/src/WpCli/WpCli.php @@ -76,7 +76,7 @@ public function getDoc(): array ## EXAMPLES # Create service class: - $ wp boilerplate {$this->getCommandParentName()} {$this->getCommandName()} --command_name='test' + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --command_name='test' ## RESOURCES From ed53dc605f50c671c922f09d41f8fb12c899a6da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= Date: Tue, 5 Jul 2022 13:23:51 +0200 Subject: [PATCH 03/52] updating command desc --- src/Blocks/UseAssetsCli.php | 2 +- src/Blocks/UseBlockCli.php | 7 +++++-- src/Blocks/UseComponentCli.php | 5 ++++- src/Blocks/UseManifestCli.php | 12 ++++++++++-- src/Blocks/UseVariationCli.php | 2 +- src/Blocks/UseWrapperCli.php | 2 +- src/Cli/ParentGroups/CliBlocks.php | 6 +++--- 7 files changed, 25 insertions(+), 11 deletions(-) diff --git a/src/Blocks/UseAssetsCli.php b/src/Blocks/UseAssetsCli.php index 8aea9caa3..b8b97bd92 100644 --- a/src/Blocks/UseAssetsCli.php +++ b/src/Blocks/UseAssetsCli.php @@ -55,7 +55,7 @@ public function getDoc(): array ## EXAMPLES - # Copy assets. + # Copy assets: $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Blocks/UseBlockCli.php b/src/Blocks/UseBlockCli.php index 88bcb4669..06f2224bd 100644 --- a/src/Blocks/UseBlockCli.php +++ b/src/Blocks/UseBlockCli.php @@ -64,7 +64,7 @@ public function getDoc(): array [ 'type' => 'assoc', 'name' => 'name', - 'description' => 'Specify block name.', + 'description' => 'Specify block name. You can specify multiple blocks by comma separator.', 'optional' => false, ], ], @@ -75,9 +75,12 @@ public function getDoc(): array ## EXAMPLES - # Copy block by name. + # Copy block by name: $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --name='paragraph' + # Copy multiple block by name: + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --name='paragraph, heading' + ## RESOURCES All our blocks can be found here: diff --git a/src/Blocks/UseComponentCli.php b/src/Blocks/UseComponentCli.php index 45b602e00..557fa71c5 100644 --- a/src/Blocks/UseComponentCli.php +++ b/src/Blocks/UseComponentCli.php @@ -71,7 +71,7 @@ public function getDoc(): array [ 'type' => 'assoc', 'name' => 'name', - 'description' => 'Specify component name.', + 'description' => 'Specify component name. You can specify multiple components by comma separator.', 'optional' => false, ], ], @@ -85,6 +85,9 @@ public function getDoc(): array # Copy component by name: $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --name='paragraph' + # Copy multiple component by name: + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --name='paragraph, heading' + ## RESOURCES All our components can be found here: diff --git a/src/Blocks/UseManifestCli.php b/src/Blocks/UseManifestCli.php index 86da2d61f..368e53b41 100644 --- a/src/Blocks/UseManifestCli.php +++ b/src/Blocks/UseManifestCli.php @@ -47,12 +47,20 @@ public function getCommandName(): string public function getDoc(): array { return [ - 'shortdesc' => 'Copy global assets manifest.json file from our library to your project.', + 'shortdesc' => 'Copy global settings manifest.json file from our library to your project.', 'longdesc' => $this->prepareLongDesc(" This file is a block editor main setting file where you can find color, option and much more. ## EXAMPLES - $ wp {$this->commandParentName} create manifest + + # Copy manifest.json: + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} + + + ## RESOURCES + + Manifest.json file will be created from this file: + https://github.com/infinum/eightshift-frontend-libs/tree/develop/blocks/init/src/Blocks/manifest.json "), ]; } diff --git a/src/Blocks/UseVariationCli.php b/src/Blocks/UseVariationCli.php index 87c9a36ce..97a078087 100644 --- a/src/Blocks/UseVariationCli.php +++ b/src/Blocks/UseVariationCli.php @@ -75,7 +75,7 @@ public function getDoc(): array ## EXAMPLES - # Copy variation by name. + # Copy variation by name: $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --name='button-block' ## RESOURCES diff --git a/src/Blocks/UseWrapperCli.php b/src/Blocks/UseWrapperCli.php index 23bc754fe..03defc302 100644 --- a/src/Blocks/UseWrapperCli.php +++ b/src/Blocks/UseWrapperCli.php @@ -51,7 +51,7 @@ public function getDoc(): array 'longdesc' => $this->prepareLongDesc(" ## EXAMPLES - # Copy wrapper. + # Copy wrapper: $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} ## RESOURCES diff --git a/src/Cli/ParentGroups/CliBlocks.php b/src/Cli/ParentGroups/CliBlocks.php index 7c19824c7..57c9231fb 100644 --- a/src/Cli/ParentGroups/CliBlocks.php +++ b/src/Cli/ParentGroups/CliBlocks.php @@ -18,13 +18,13 @@ * ## EXAMPLES * * # Copy block by name. - * $ wp boilerplate blocks block --name='paragraph' + * $ wp boilerplate blocks use_block --name='paragraph' * * # Copy component by name. - * $ wp boilerplate blocks component --name='heading' + * $ wp boilerplate blocks use_component --name='heading' * * # Copy wrapper. - * $ wp boilerplate blocks wrapper + * $ wp boilerplate blocks use_wrapper */ class CliBlocks extends WP_CLI_Command { From 94b660fcc009dc4f42a770073c84a9763906c967 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= Date: Tue, 5 Jul 2022 13:42:56 +0200 Subject: [PATCH 04/52] adding variation to init setup --- phpunit.xml | 2 +- src/Init/InitBlocksCli.php | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/phpunit.xml b/phpunit.xml index d2f863e38..ea76d64c9 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -10,7 +10,7 @@ - + diff --git a/src/Init/InitBlocksCli.php b/src/Init/InitBlocksCli.php index e1b5374f4..07dde312c 100644 --- a/src/Init/InitBlocksCli.php +++ b/src/Init/InitBlocksCli.php @@ -17,6 +17,7 @@ use EightshiftLibs\Blocks\UseGlobalAssetsCli; use EightshiftLibs\Blocks\UseManifestCli; use EightshiftLibs\Blocks\UseStorybookCli; +use EightshiftLibs\Blocks\UseVariationCli; use EightshiftLibs\Blocks\UseWrapperCli; use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliInit; @@ -83,6 +84,14 @@ class InitBlocksCli extends AbstractCli 'variables', ], ], + UseVariationCli::class => [ + 'default' => [ + 'button-block' + ], + 'test' => [ + 'button-block' + ] + ] ]; /** From 07c96b3041acbe64a744eaa190f9ada13a5fdd70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= Date: Tue, 5 Jul 2022 14:19:27 +0200 Subject: [PATCH 05/52] adding init blocks all command --- src/Cli/CliHelpers.php | 15 +++++++++ src/Init/InitBlocksCli.php | 62 +++++++++++++++++++++++++++++++++----- 2 files changed, 70 insertions(+), 7 deletions(-) diff --git a/src/Cli/CliHelpers.php b/src/Cli/CliHelpers.php index 6ef1a29e8..16ef49ad4 100644 --- a/src/Cli/CliHelpers.php +++ b/src/Cli/CliHelpers.php @@ -90,4 +90,19 @@ protected function getShortenCliPathOutput(string $path, string $ref = 'projectR { return \str_replace(Components::getProjectPaths($ref), '', $path); } + + /** + * Scan folder for items. + * + * @param string $path Path to search. + * + * @return array + */ + protected function getFolderItems(string $path): array + { + $output = \array_diff(\scandir($path), ['..', '.']); + $output = \array_values($output); + + return $output; + } } diff --git a/src/Init/InitBlocksCli.php b/src/Init/InitBlocksCli.php index 07dde312c..265ad6dda 100644 --- a/src/Init/InitBlocksCli.php +++ b/src/Init/InitBlocksCli.php @@ -21,6 +21,7 @@ use EightshiftLibs\Blocks\UseWrapperCli; use EightshiftLibs\Cli\AbstractCli; use EightshiftLibs\Cli\ParentGroups\CliInit; +use EightshiftLibs\Helpers\Components; use ReflectionClass; /** @@ -123,6 +124,15 @@ public function getDoc(): array { return [ 'shortdesc' => 'Create all files for blocks to work.', + 'synopsis' => [ + [ + 'type' => 'assoc', + 'name' => 'use_all', + 'description' => 'Output all items to your project.', + 'optional' => true, + 'default' => false, + ], + ], 'longdesc' => $this->prepareLongDesc(" This command will copy all initial block, componens, manifests na service classes to you project in order to start using block editor. @@ -136,6 +146,7 @@ public function getDoc(): array public function __invoke(array $args, array $assocArgs) { $groupOutput = $assocArgs['groupOutput'] ?? false; + $all = $assocArgs['use_all'] ?? false; if (!$groupOutput) { $this->getIntroText(); @@ -143,7 +154,50 @@ public function __invoke(array $args, array $assocArgs) $this->cliLog(\esc_html__('Setting block editor files:', 'eightshift-libs'), 'C'); - foreach (static::COMMANDS as $className => $items) { + $commands = static::COMMANDS; + + if ($all) { + $commands = []; + $type = \getenv('ES_TEST') ? 'test' : 'default'; + + foreach (\array_keys(static::COMMANDS) as $command) { + switch ($command) { + case UseBlockCli::class: + $commands[$command][$type] = $this->getFolderItems(Components::getProjectPaths('blocksSourceCustom')); + break; + case UseComponentCli::class: + $commands[$command][$type] = $this->getFolderItems(Components::getProjectPaths('blocksSourceComponents')); + break; + case UseVariationCli::class: + $commands[$command][$type] = $this->getFolderItems(Components::getProjectPaths('blocksSourceVariations')); + break; + default: + $commands[$command] = []; + break; + } + } + } + + $this->getInitBlocks($assocArgs, $commands); + + if (!$groupOutput) { + $this->cliLog('--------------------------------------------------'); + $this->cliLog('We have moved everything you need to start creating WordPress blocks. Please type `npm start` in your terminal to kickstart your assets bundle process.', "M"); + $this->cliLog('Happy developing!', "M"); + } + } + + /** + * Init block by providing list of commands + * + * @param array $assocArgs List of argument for options. + * @param array $commands Commands to use. + * + * @return void + */ + private function getInitBlocks(array $assocArgs, array $commands): void + { + foreach ($commands as $className => $items) { $reflectionClass = new ReflectionClass($className); $class = $reflectionClass->newInstanceArgs([$this->commandParentName]); @@ -174,11 +228,5 @@ public function __invoke(array $args, array $assocArgs) )); } } - - if (!$groupOutput) { - $this->cliLog('--------------------------------------------------'); - $this->cliLog('We have moved everything you need to start creating WordPress blocks. Please type `npm start` in your terminal to kickstart your assets bundle process.', "M"); - $this->cliLog('Happy developing!', "M"); - } } } From 7cae8e2f183464616aa419128e76c45757a0f4b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= Date: Tue, 5 Jul 2022 15:10:02 +0200 Subject: [PATCH 06/52] adding init all command --- src/Cli/Cli.php | 2 + src/Geolocation/GeolocationExample.php | 4 +- src/Init/InitAllCli.php | 130 ++++++++++++++++++ src/Init/InitBlocksCli.php | 2 +- tests/Cli/CliTest.php | 2 +- tests/Geolocation/AbstractGeolocationTest.php | 3 +- tests/Geolocation/GeolocationExampleTest.php | 2 +- 7 files changed, 138 insertions(+), 7 deletions(-) create mode 100644 src/Init/InitAllCli.php diff --git a/src/Cli/Cli.php b/src/Cli/Cli.php index e3c504050..a6eb47a46 100644 --- a/src/Cli/Cli.php +++ b/src/Cli/Cli.php @@ -56,6 +56,7 @@ use EightshiftLibs\Db\ImportCli; use EightshiftLibs\Geolocation\GeolocationCli; use EightshiftLibs\GitIgnore\GitIgnoreCli; +use EightshiftLibs\Init\InitAllCli; use EightshiftLibs\Init\InitBlocksCli; use EightshiftLibs\Init\InitProjectCli; use EightshiftLibs\Init\InitThemeCli; @@ -169,6 +170,7 @@ class Cli InitThemeCli::class, InitProjectCli::class, InitBlocksCli::class, + InitAllCli::class, ]; /** diff --git a/src/Geolocation/GeolocationExample.php b/src/Geolocation/GeolocationExample.php index 1da3224c4..c24f59830 100644 --- a/src/Geolocation/GeolocationExample.php +++ b/src/Geolocation/GeolocationExample.php @@ -3,12 +3,12 @@ /** * Class that adds Geolocation detection. * - * @package EightshiftLibs\Geolocation + * @package EightshiftBoilerplate\Geolocation */ declare(strict_types=1); -namespace EightshiftLibs\Geolocation; +namespace EightshiftBoilerplate\Geolocation; use EightshiftLibs\Geolocation\AbstractGeolocation; use Exception; diff --git a/src/Init/InitAllCli.php b/src/Init/InitAllCli.php new file mode 100644 index 000000000..1d67aef29 --- /dev/null +++ b/src/Init/InitAllCli.php @@ -0,0 +1,130 @@ + + */ + public const COMMANDS = [ + [ + 'type' => 'classes', + 'label' => 'Setting classes:', + 'items' => Cli::CREATE_COMMANDS, + ], + [ + 'type' => 'blocks', + 'label' => '', + 'items' => [ + InitBlocksCli::class, + ], + ], + ]; + + /** + * Get WPCLI command parent name + * + * @return string + */ + public function getCommandParentName(): string + { + return CliInit::COMMAND_NAME; + } + + /** + * Get WPCLI command name + * + * @return string + */ + public function getCommandName(): string + { + return 'all'; + } + + /** + * Get WPCLI command doc + * + * @return array>|string> + */ + public function getDoc(): array + { + return [ + 'shortdesc' => 'Move everything to your project.', + 'longdesc' => $this->prepareLongDesc(" + ## USAGE + + This command is used to move everything that we have to your project, all service classes, block editor items, etc. + + ## EXAMPLES + + # Setup project: + $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} + "), + ]; + } + + /* @phpstan-ignore-next-line */ + public function __invoke(array $args, array $assocArgs) + { + $groupOutput = $assocArgs['groupOutput'] ?? false; + + if (!$groupOutput) { + $this->getIntroText(); + } + + foreach (static::COMMANDS as $item) { + $label = $item['label'] ?? ''; + $items = $item['items'] ?? []; + $type = $item['type'] ?? ''; + + if ($label) { + $this->cliLog($label, 'C'); + } + + if ($type === 'blocks') { + $assocArgs['use_all'] = true; + } + + if ($items) { + foreach ($items as $className) { + $reflectionClass = new ReflectionClass($className); + $class = $reflectionClass->newInstanceArgs([$this->commandParentName]); + + $class->__invoke([], \array_merge( + $assocArgs, + [ + 'groupOutput' => $type === 'blocks', + 'introOutput' => false, + ] + )); + } + } + + $this->cliLog('--------------------------------------------------'); + } + + if (!$groupOutput) { + $this->cliLog('We have moved everything we have to your project. Please type `npm start` in your terminal to kickstart your assets bundle process.', "M"); + $this->cliLog('Happy developing!', "M"); + } + } +} diff --git a/src/Init/InitBlocksCli.php b/src/Init/InitBlocksCli.php index 265ad6dda..33b322693 100644 --- a/src/Init/InitBlocksCli.php +++ b/src/Init/InitBlocksCli.php @@ -126,7 +126,7 @@ public function getDoc(): array 'shortdesc' => 'Create all files for blocks to work.', 'synopsis' => [ [ - 'type' => 'assoc', + 'type' => 'flag', 'name' => 'use_all', 'description' => 'Output all items to your project.', 'optional' => true, diff --git a/tests/Cli/CliTest.php b/tests/Cli/CliTest.php index a2623887a..0966d371e 100644 --- a/tests/Cli/CliTest.php +++ b/tests/Cli/CliTest.php @@ -37,7 +37,7 @@ expect(\count($publicClasses)) ->toBeInt() - ->toBe(51); // Public classes count. + ->toBe(52); // Public classes count. }); test('Running load command works', function() { diff --git a/tests/Geolocation/AbstractGeolocationTest.php b/tests/Geolocation/AbstractGeolocationTest.php index 3eca21c5b..290331656 100644 --- a/tests/Geolocation/AbstractGeolocationTest.php +++ b/tests/Geolocation/AbstractGeolocationTest.php @@ -2,12 +2,11 @@ namespace Tests\Unit\Geolocation; -use EightshiftLibs\Geolocation\GeolocationExample; - use function Tests\setAfterEach; use function Tests\setBeforeEach; use function Tests\getDataPath; use Brain\Monkey\Functions; +use EightshiftBoilerplate\Geolocation\GeolocationExample; use Exception; use function Tests\mock; diff --git a/tests/Geolocation/GeolocationExampleTest.php b/tests/Geolocation/GeolocationExampleTest.php index 1ab1e0aed..0fdaaf9a0 100644 --- a/tests/Geolocation/GeolocationExampleTest.php +++ b/tests/Geolocation/GeolocationExampleTest.php @@ -2,7 +2,7 @@ namespace Tests\Unit\Geolocation; -use EightshiftLibs\Geolocation\GeolocationExample; +use EightshiftBoilerplate\Geolocation\GeolocationExample; use Exception; use function Tests\setAfterEach; From 113c9ffc3a00a0a1ad95319c05c8f72d44621d43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 09:02:43 +0200 Subject: [PATCH 07/52] Update src/Blocks/AbstractBlocksCli.php MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Denis Žoljom --- src/Blocks/AbstractBlocksCli.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Blocks/AbstractBlocksCli.php b/src/Blocks/AbstractBlocksCli.php index 8696c96fa..a11262762 100644 --- a/src/Blocks/AbstractBlocksCli.php +++ b/src/Blocks/AbstractBlocksCli.php @@ -187,7 +187,7 @@ static function ($item) use ($sep) { } /** - * Determin if item has dependencies and output helper commands. + * Determine if the item has dependencies and output helper commands. * * @param string $source Source or the item. * @param string $type Type for log. From 155d39b70e075d064285b3da9368390b664b103d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 09:07:31 +0200 Subject: [PATCH 08/52] Apply suggestions from code review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Denis Žoljom Co-authored-by: Davorin Prislin <81157133+dadadavorin@users.noreply.github.com> --- src/Blocks/UseManifestCli.php | 4 ++-- src/Cli/Cli.php | 4 ++-- src/Init/InitAllCli.php | 8 ++++---- src/Init/InitBlocksCli.php | 12 ++++++------ src/Init/InitProjectCli.php | 12 ++++++------ 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/Blocks/UseManifestCli.php b/src/Blocks/UseManifestCli.php index 368e53b41..3c6863ab4 100644 --- a/src/Blocks/UseManifestCli.php +++ b/src/Blocks/UseManifestCli.php @@ -49,7 +49,7 @@ public function getDoc(): array return [ 'shortdesc' => 'Copy global settings manifest.json file from our library to your project.', 'longdesc' => $this->prepareLongDesc(" - This file is a block editor main setting file where you can find color, option and much more. + This file is a block editor's main setting file where you can find the color, options, and much more. ## EXAMPLES @@ -87,7 +87,7 @@ public function __invoke(array $args, array $assocArgs) // phpcs:ignore if (!$groupOutput) { WP_CLI::log('--------------------------------------------------'); - $this->cliLog('Please run `npm start` again to make sure everything works correctly.', "M"); + $this->cliLog('Please run `npm start` again to make sure everything works correctly.', 'M'); } } } diff --git a/src/Cli/Cli.php b/src/Cli/Cli.php index a6eb47a46..c4ddacca1 100644 --- a/src/Cli/Cli.php +++ b/src/Cli/Cli.php @@ -131,7 +131,7 @@ class Cli ]; /** - * All commands that can be used on WP project directly from the libs. Command prefix - run. + * All commands that can be used on a WP project directly from the libs. Command prefix - run. * * @var class-string[] */ @@ -144,7 +144,7 @@ class Cli ]; /** - * All commands used for block editor. Command prefix - blocks. + * All commands used for block editor. Command prefix - blocks. * * @var class-string[] */ diff --git a/src/Init/InitAllCli.php b/src/Init/InitAllCli.php index 1d67aef29..05f8b9e91 100644 --- a/src/Init/InitAllCli.php +++ b/src/Init/InitAllCli.php @@ -21,7 +21,7 @@ class InitAllCli extends AbstractCli { /** - * All classes for initial theme setup for project + * All classes for initial theme setup for project. * * @var array */ @@ -41,7 +41,7 @@ class InitAllCli extends AbstractCli ]; /** - * Get WPCLI command parent name + * Get WPCLI command parent name. * * @return string */ @@ -51,7 +51,7 @@ public function getCommandParentName(): string } /** - * Get WPCLI command name + * Get WPCLI command name. * * @return string */ @@ -61,7 +61,7 @@ public function getCommandName(): string } /** - * Get WPCLI command doc + * Get WPCLI command doc. * * @return array>|string> */ diff --git a/src/Init/InitBlocksCli.php b/src/Init/InitBlocksCli.php index 33b322693..5d4313557 100644 --- a/src/Init/InitBlocksCli.php +++ b/src/Init/InitBlocksCli.php @@ -1,7 +1,7 @@ >|string> */ @@ -134,7 +134,7 @@ public function getDoc(): array ], ], 'longdesc' => $this->prepareLongDesc(" - This command will copy all initial block, componens, manifests na service classes to you project in order to start using block editor. + This command will copy all initial block, components, manifests and service classes to you project in order to start using block editor. ## EXAMPLES $ wp {$this->commandParentName} create blocks_init @@ -188,7 +188,7 @@ public function __invoke(array $args, array $assocArgs) } /** - * Init block by providing list of commands + * Init block by providing list of commands. * * @param array $assocArgs List of argument for options. * @param array $commands Commands to use. diff --git a/src/Init/InitProjectCli.php b/src/Init/InitProjectCli.php index 270f66662..ee18e1876 100644 --- a/src/Init/InitProjectCli.php +++ b/src/Init/InitProjectCli.php @@ -1,7 +1,7 @@ */ @@ -53,7 +53,7 @@ class InitProjectCli extends AbstractCli ]; /** - * Get WPCLI command parent name + * Get WP-CLI command parent name. * * @return string */ @@ -63,7 +63,7 @@ public function getCommandParentName(): string } /** - * Get WPCLI command name + * Get WP-CLI command name. * * @return string */ @@ -73,7 +73,7 @@ public function getCommandName(): string } /** - * Get WPCLI command doc + * Get WP-CLI command doc. * * @return array>|string> */ @@ -131,7 +131,7 @@ public function __invoke(array $args, array $assocArgs) if (!$groupOutput) { $this->cliLog('--------------------------------------------------'); - $this->cliLog('We have moved everything you need, to start creating your awesome WordPress project. Please type `npm start` in your terminal to kickstart your assets bundle process.', "M"); + $this->cliLog('We have moved everything you need to start creating your awesome WordPress project. Please type `npm start` in your terminal to kickstart your assets bundle process.', "M"); $this->cliLog('Happy developing!', "M"); } } From a2f5261f1287d01298967973332f35490124edc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 09:08:10 +0200 Subject: [PATCH 09/52] Update src/Blocks/UseComponentCli.php MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Denis Žoljom --- src/Blocks/UseComponentCli.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Blocks/UseComponentCli.php b/src/Blocks/UseComponentCli.php index 557fa71c5..6e4ce2d8b 100644 --- a/src/Blocks/UseComponentCli.php +++ b/src/Blocks/UseComponentCli.php @@ -71,7 +71,7 @@ public function getDoc(): array [ 'type' => 'assoc', 'name' => 'name', - 'description' => 'Specify component name. You can specify multiple components by comma separator.', + 'description' => 'Specify component name. You can specify multiple components (separate them with comma).', 'optional' => false, ], ], From 7516fd950cdcf56706b9e8785c944ddeedb33314 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 09:08:24 +0200 Subject: [PATCH 10/52] Update src/Blocks/UseGlobalAssetsCli.php MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Denis Žoljom --- src/Blocks/UseGlobalAssetsCli.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Blocks/UseGlobalAssetsCli.php b/src/Blocks/UseGlobalAssetsCli.php index 9a7896938..fc8590b4c 100644 --- a/src/Blocks/UseGlobalAssetsCli.php +++ b/src/Blocks/UseGlobalAssetsCli.php @@ -51,7 +51,7 @@ public function getDoc(): array 'longdesc' => $this->prepareLongDesc(" ## USAGE - Used to copy pre-created global assets from our library to your project. After copying you can modify it in any way you see fit. + Used to copy pre-created global assets from our library to your project. After copying you can modify them in any way you see fit. ## EXAMPLES From e44823352bb6d840af2f430b69bde72356632572 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 09:09:25 +0200 Subject: [PATCH 11/52] Update tests/WpCli/WpCliTest.php MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Denis Žoljom --- tests/WpCli/WpCliTest.php | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/WpCli/WpCliTest.php b/tests/WpCli/WpCliTest.php index 0cb9a35e8..4b21bdb82 100644 --- a/tests/WpCli/WpCliTest.php +++ b/tests/WpCli/WpCliTest.php @@ -29,11 +29,12 @@ $sep = \DIRECTORY_SEPARATOR; $mock = \file_get_contents(Components::getProjectPaths('srcDestination', "WpCli{$sep}TestWpCli.php")); - $this->assertStringContainsString('class TestWpCli implements ServiceCliInterface', $mock); - $this->assertStringContainsString('function register', $mock); - $this->assertStringContainsString('function registerCommand', $mock); - $this->assertStringContainsString('function getDocs', $mock); - $this->assertStringContainsString('function __invoke', $mock); + expect($mock) + ->assertContains('class TestWpCli implements ServiceCliInterface', $mock) + ->assertContains('function register', $mock) + ->assertContains('function registerCommand', $mock) + ->assertContains('function getDocs', $mock) + ->assertContains('function __invoke', $mock); }); From 1ce0c6acde21158336548a75b0f6d05171cb4103 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 09:09:48 +0200 Subject: [PATCH 12/52] Update src/Cli/ParentGroups/CliBoilerplate.php Co-authored-by: Davorin Prislin <81157133+dadadavorin@users.noreply.github.com> --- src/Cli/ParentGroups/CliBoilerplate.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Cli/ParentGroups/CliBoilerplate.php b/src/Cli/ParentGroups/CliBoilerplate.php index 1d0b96426..5ad5c84e0 100644 --- a/src/Cli/ParentGroups/CliBoilerplate.php +++ b/src/Cli/ParentGroups/CliBoilerplate.php @@ -1,7 +1,7 @@ Date: Wed, 6 Jul 2022 09:10:04 +0200 Subject: [PATCH 13/52] Update src/GitIgnore/GitIgnoreCli.php Co-authored-by: Davorin Prislin <81157133+dadadavorin@users.noreply.github.com> --- src/GitIgnore/GitIgnoreCli.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/GitIgnore/GitIgnoreCli.php b/src/GitIgnore/GitIgnoreCli.php index 0d17c0977..62986a9dd 100644 --- a/src/GitIgnore/GitIgnoreCli.php +++ b/src/GitIgnore/GitIgnoreCli.php @@ -64,7 +64,7 @@ public function getDoc(): array [ 'type' => 'assoc', 'name' => 'path', - 'description' => 'Define absolute folder path where gitignore file file will be created.', + 'description' => "Define absolute folder path where `.gitignore` file will be created.", 'optional' => true, 'default' => $this->getDefaultArg('path'), ], From f61ad225cea0b2f3300ade2ee6919262501aade4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 09:10:25 +0200 Subject: [PATCH 14/52] Update src/Helpers/StoreTrait.php Co-authored-by: Davorin Prislin <81157133+dadadavorin@users.noreply.github.com> --- src/Helpers/StoreTrait.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Helpers/StoreTrait.php b/src/Helpers/StoreTrait.php index 2eb42b285..7ca13a8b8 100644 --- a/src/Helpers/StoreTrait.php +++ b/src/Helpers/StoreTrait.php @@ -592,7 +592,7 @@ public static function setPaths(): void } /** - * Get path details. + * Get paths details. * * @return array */ From dae9649c536d1bcb8dd8ae93012b54fbd2c82fea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 09:10:36 +0200 Subject: [PATCH 15/52] Update tests/Helpers.php Co-authored-by: Davorin Prislin <81157133+dadadavorin@users.noreply.github.com> --- tests/Helpers.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Helpers.php b/tests/Helpers.php index 3800e8cd2..395e642c0 100644 --- a/tests/Helpers.php +++ b/tests/Helpers.php @@ -265,7 +265,7 @@ function getCliOutputPath(string $path = ''): string } /** - * Get projects root path for mocks. + * Get project root path for mocks. * * @return string */ From 481f2ae35e6b16ef6414ba278bb470739ba0ffc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 09:11:06 +0200 Subject: [PATCH 16/52] Update src/Init/InitThemeCli.php Co-authored-by: Davorin Prislin <81157133+dadadavorin@users.noreply.github.com> --- src/Init/InitThemeCli.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Init/InitThemeCli.php b/src/Init/InitThemeCli.php index 13c9e2161..796a9ca25 100644 --- a/src/Init/InitThemeCli.php +++ b/src/Init/InitThemeCli.php @@ -133,7 +133,7 @@ public function __invoke(array $args, array $assocArgs) } if (!$groupOutput) { - $this->cliLog('We have moved everything you need, to start creating your awesome WordPress theme. Please type `npm start` in your terminal to kickstart your assets bundle process.', "M"); + $this->cliLog('We have moved everything you need to start creating your awesome WordPress theme. Please type `npm start` in your terminal to kickstart your assets bundle process.', "M"); $this->cliLog('Happy developing!', "M"); } } From 7fa0cb3e05757380636cb8426195de96aee25f64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 09:11:17 +0200 Subject: [PATCH 17/52] Update src/Init/InitThemeCli.php Co-authored-by: Davorin Prislin <81157133+dadadavorin@users.noreply.github.com> --- src/Init/InitThemeCli.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Init/InitThemeCli.php b/src/Init/InitThemeCli.php index 796a9ca25..3cc22daa7 100644 --- a/src/Init/InitThemeCli.php +++ b/src/Init/InitThemeCli.php @@ -75,7 +75,7 @@ public function getCommandName(): string } /** - * Get WPCLI command doc + * Get WP-CLI command doc. * * @return array>|string> */ From 9a5d56280c95ffb953a8353a08a283972e10795b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 09:11:27 +0200 Subject: [PATCH 18/52] Update src/Init/InitThemeCli.php Co-authored-by: Davorin Prislin <81157133+dadadavorin@users.noreply.github.com> --- src/Init/InitThemeCli.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Init/InitThemeCli.php b/src/Init/InitThemeCli.php index 3cc22daa7..f4f13c7d4 100644 --- a/src/Init/InitThemeCli.php +++ b/src/Init/InitThemeCli.php @@ -65,7 +65,7 @@ public function getCommandParentName(): string } /** - * Get WPCLI command name + * Get WP-CLI command name. * * @return string */ From 573e180bcc903a82ab0faf9a90517db1686281c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 09:11:37 +0200 Subject: [PATCH 19/52] Update src/Init/InitThemeCli.php Co-authored-by: Davorin Prislin <81157133+dadadavorin@users.noreply.github.com> --- src/Init/InitThemeCli.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Init/InitThemeCli.php b/src/Init/InitThemeCli.php index f4f13c7d4..09685bab7 100644 --- a/src/Init/InitThemeCli.php +++ b/src/Init/InitThemeCli.php @@ -55,7 +55,7 @@ class InitThemeCli extends AbstractCli ]; /** - * Get WPCLI command parent name + * Get WP-CLI command parent name. * * @return string */ From e5f1cf7546166a9a5d00b832b3957aff6b7cfbf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 09:11:51 +0200 Subject: [PATCH 20/52] Update src/Init/InitThemeCli.php Co-authored-by: Davorin Prislin <81157133+dadadavorin@users.noreply.github.com> --- src/Init/InitThemeCli.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Init/InitThemeCli.php b/src/Init/InitThemeCli.php index 09685bab7..b8d35c0a3 100644 --- a/src/Init/InitThemeCli.php +++ b/src/Init/InitThemeCli.php @@ -1,7 +1,7 @@ Date: Wed, 6 Jul 2022 09:12:03 +0200 Subject: [PATCH 21/52] Update src/Init/InitThemeCli.php Co-authored-by: Davorin Prislin <81157133+dadadavorin@users.noreply.github.com> --- src/Init/InitThemeCli.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Init/InitThemeCli.php b/src/Init/InitThemeCli.php index b8d35c0a3..bb9dfee5e 100644 --- a/src/Init/InitThemeCli.php +++ b/src/Init/InitThemeCli.php @@ -27,7 +27,7 @@ class InitThemeCli extends AbstractCli { /** - * All classes for initial theme setup for project + * All classes for initial theme setup for project. * * @var array */ From 2a3713230be13b1ff5556d7c38748a63ad4953db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= Date: Wed, 6 Jul 2022 09:15:56 +0200 Subject: [PATCH 22/52] removing build and ci-exclude functionality --- phpcs.xml.dist | 1 - src/Build/BuildCli.php | 120 ------------------------- src/Build/BuildExample.php | 12 --- src/CiExclude/CiExcludeCli.php | 125 --------------------------- src/CiExclude/CiExcludeExample.php | 28 ------ src/Cli/Cli.php | 4 - src/Init/InitProjectCli.php | 4 - tests/Build/BuildCliTest.php | 38 -------- tests/CiExclude/CiExcludeCliTest.php | 109 ----------------------- 9 files changed, 441 deletions(-) delete mode 100644 src/Build/BuildCli.php delete mode 100644 src/Build/BuildExample.php delete mode 100644 src/CiExclude/CiExcludeCli.php delete mode 100644 src/CiExclude/CiExcludeExample.php delete mode 100644 tests/Build/BuildCliTest.php delete mode 100644 tests/CiExclude/CiExcludeCliTest.php diff --git a/phpcs.xml.dist b/phpcs.xml.dist index d33bdd79d..0563871e8 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -10,7 +10,6 @@ */src/commands/templates/* */src/Build/BuildExample.php */bin/cli.php - */src/CiExclude/CiExcludeExample.php diff --git a/src/Build/BuildCli.php b/src/Build/BuildCli.php deleted file mode 100644 index 9b630b1e3..000000000 --- a/src/Build/BuildCli.php +++ /dev/null @@ -1,120 +0,0 @@ - - */ - public function getDefaultArgs(): array - { - return [ - 'path' => Components::getProjectPaths('projectRoot', 'bin'), - 'project_name' => 'eightshift-boilerplate', - 'project_type' => 'themes', - ]; - } - - /** - * Get WPCLI command doc - * - * @return array>|string> - */ - public function getDoc(): array - { - return [ - 'shortdesc' => 'Copy bash script for building your project with one command, generally used on CI deployments.', - 'synopsis' => [ - [ - 'type' => 'assoc', - 'name' => 'path', - 'description' => 'Define absolute folder path where build script file will be created.', - 'optional' => true, - 'default' => $this->getDefaultArg('path'), - ], - [ - 'type' => 'assoc', - 'name' => 'project_name', - 'description' => 'Set project file name, if theme use theme folder name, if plugin use plugin folder name.', - 'optional' => true, - 'default' => $this->getDefaultArg('project_name'), - ], - [ - 'type' => 'assoc', - 'name' => 'project_type', - 'description' => 'Set project file name, if theme use theme folder name, if plugin use plugin folder name. Default is themes.', - 'optional' => true, - 'default' => $this->getDefaultArg('project_type'), - ], - ], - 'longdesc' => $this->prepareLongDesc(" - ## USAGE - - Used for building your project to production ready version in one command. Generally used in GitHub Actions or any other tool for continuous integration. This file will be copied to your project root under the bin folder. - - ## EXAMPLES - - # Copy file: - $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} - - ## RESOURCES - - File will be created from this example: - https://github.com/infinum/eightshift-libs/blob/develop/src/Build/BuildExample.php - "), - ]; - } - - /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) - { - $this->getIntroText($assocArgs); - - // Get Props. - $path = $this->getArg($assocArgs, 'path'); - - // Read the template contents, and replace the placeholders with provided variables. - $this->getExampleTemplate(__DIR__, $this->getClassShortName()) - ->renameProjectName($assocArgs) - ->renameProjectType($assocArgs) - ->outputWrite($path, 'build.sh', $assocArgs); - } -} diff --git a/src/Build/BuildExample.php b/src/Build/BuildExample.php deleted file mode 100644 index 0cb6953a2..000000000 --- a/src/Build/BuildExample.php +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env sh - -set -e - -function build() { - cd 'wp-content/%project_type%/%project_name%'; - npm install - composer install --no-dev - npm run build -} - -build diff --git a/src/CiExclude/CiExcludeCli.php b/src/CiExclude/CiExcludeCli.php deleted file mode 100644 index f51e4e108..000000000 --- a/src/CiExclude/CiExcludeCli.php +++ /dev/null @@ -1,125 +0,0 @@ - - */ - public function getDefaultArgs(): array - { - return [ - 'path' => Components::getProjectPaths('projectRoot'), - 'project_name' => 'eightshift-boilerplate', - 'project_type' => 'themes', - ]; - } - - /** - * Get WPCLI command doc - * - * @return array>|string> - */ - public function getDoc(): array - { - return [ - 'shortdesc' => 'Copy text file for building your projects continuous integration exclude file.', - 'synopsis' => [ - [ - 'type' => 'assoc', - 'name' => 'path', - 'description' => 'Define absolute folder path where exclude file file will be created.', - 'optional' => true, - 'default' => $this->getDefaultArg('path'), - ], - [ - 'type' => 'assoc', - 'name' => 'project_name', - 'description' => 'Set project file name, if theme use theme folder name, if plugin use plugin folder name.', - 'optional' => true, - 'default' => $this->getDefaultArg('project_name'), - ], - [ - 'type' => 'assoc', - 'name' => 'project_type', - 'description' => 'Set project file name, if theme use theme folder name, if plugin use plugin folder name. Default is themes.', - 'optional' => true, - 'default' => $this->getDefaultArg('project_type'), - ], - ], - 'longdesc' => $this->prepareLongDesc(" - ## USAGE - - Used to list all files you want to exclude in your continuous integration process. Generally used in GitHub Actions or any other tool for continuous integration. - This file will be copied to your project root folder. - - ## EXAMPLES - - # Copy file: - $ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} - - ## RESOURCES - - File will be created from this example: - https://github.com/infinum/eightshift-libs/blob/develop/src/Build/BuildExample.php - "), - ]; - } - - /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) - { - $this->getIntroText($assocArgs); - - // Get Props. - $path = $this->getArg($assocArgs, 'path'); - $projectName = $this->getArg($assocArgs, 'project_name'); - $projectType = $this->getArg($assocArgs, 'project_type'); - - // Read the template contents, and replace the placeholders with provided variables. - $this->getExampleTemplate(__DIR__, $this->getClassShortName()) - ->searchReplaceString('searchReplaceString('\';', '') - ->searchReplaceString($this->getArgTemplate('project_name'), $projectName) - ->searchReplaceString($this->getArgTemplate('project_type'), $projectType) - ->outputWrite($path, 'ci-exclude.txt', $assocArgs); - } -} diff --git a/src/CiExclude/CiExcludeExample.php b/src/CiExclude/CiExcludeExample.php deleted file mode 100644 index 0e8f69bbc..000000000 --- a/src/CiExclude/CiExcludeExample.php +++ /dev/null @@ -1,28 +0,0 @@ - - [ GitIgnoreCli::class, SetupCli::class, - CiExcludeCli::class, - BuildCli::class, ReadmeCli::class, ConfigProjectCli::class, ], diff --git a/tests/Build/BuildCliTest.php b/tests/Build/BuildCliTest.php deleted file mode 100644 index 3ce94fa9c..000000000 --- a/tests/Build/BuildCliTest.php +++ /dev/null @@ -1,38 +0,0 @@ -mock = new BuildCli('boilerplate'); -}); - -afterEach(function () { - setAfterEach(); - - unset($this->mock); -}); - -test('Build CLI will correctly copy the build script with defaults', function () { - $sep = \DIRECTORY_SEPARATOR; - - $mock = $this->mock; - $mock([], [ - 'path' => Components::getProjectPaths('cliOutput', 'bin'), - ]); - - $output = \file_get_contents(Components::getProjectPaths('cliOutput', "bin{$sep}build.sh")); - - $this->assertStringNotContainsString('random string', $output); -}); - -test('Build CLI documentation is correct', function () { - expect($this->mock->getDoc())->toBeArray(); -}); diff --git a/tests/CiExclude/CiExcludeCliTest.php b/tests/CiExclude/CiExcludeCliTest.php deleted file mode 100644 index a1c949fb0..000000000 --- a/tests/CiExclude/CiExcludeCliTest.php +++ /dev/null @@ -1,109 +0,0 @@ -mock = new CiExcludeCli('boilerplate'); -}); - -afterEach(function () { - setAfterEach(); - - unset($this->mock); -}); - -//---------------------------------------------------------------------------------// - -test('getCommandParentName will return correct value', function () { - expect($this->mock->getCommandParentName()) - ->toBeString() - ->toEqual(CliCreate::COMMAND_NAME); -}); - -//---------------------------------------------------------------------------------// - -test('getCommandName will return correct value', function () { - expect($this->mock->getCommandName()) - ->toBeString() - ->toEqual('ci_exclude'); -}); - -//---------------------------------------------------------------------------------// - -test('getDefaultArgs will return correct array', function () { - $args = $this->mock->getDefaultArgs(); - - expect($args) - ->toBeArray() - ->toHaveKeys(['path', 'project_name', 'project_type']) - ->and($args['project_name'])->toEqual('eightshift-boilerplate') - ->and($args['project_type'])->toEqual('themes'); -}); - -//---------------------------------------------------------------------------------// - -test('getDoc will return correct array', function () { - $docs = $this->mock->getDoc(); - - expect($docs) - ->toBeArray() - ->toHaveKeys(['shortdesc', 'synopsis', 'longdesc']) - ->and(count($docs['synopsis']))->toEqual(3) - ->and($docs['synopsis'][0]['name'])->toEqual('path') - ->and($docs['synopsis'][1]['name'])->toEqual('project_name') - ->and($docs['synopsis'][2]['name'])->toEqual('project_type'); -}); - -//---------------------------------------------------------------------------------// - -test('__invoke will will correctly copy example class with default args', function () { - $mock = $this->mock; - $mock([], array_merge( - $this->mock->getDefaultArgs(), - [ - 'path' => Components::getProjectPaths('cliOutput'), - ] - )); - - $output = \file_get_contents(Components::getProjectPaths('cliOutput', 'ci-exclude.txt')); - - expect($output) - ->toContain( - 'eightshift-boilerplate', - 'themes', - ) - ->not->toContain( - '%project_type%', - '%project_type%', - ); -}); - -test('__invoke will will correctly copy example class with custom args', function () { - $mock = $this->mock; - $mock([], [ - 'path' => Components::getProjectPaths('cliOutput'), - 'project_name' => 'test', - 'project_type' => 'plugins', - ]); - - $output = \file_get_contents(Components::getProjectPaths('cliOutput', 'ci-exclude.txt')); - - expect($output) - ->toContain( - 'test', - 'plugins', - ) - ->not->toContain( - '%project_type%', - '%project_type%', - ); -}); From 6ae212a2823c213c1bb2225d51136b7f9c965436 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= Date: Wed, 6 Jul 2022 09:21:06 +0200 Subject: [PATCH 23/52] renaming blocks command prefix --- src/BlockPatterns/BlockPatternCli.php | 2 +- src/Blocks/BlocksCli.php | 2 +- src/Blocks/UseAssetsCli.php | 2 +- src/Blocks/UseBlockCli.php | 2 +- src/Blocks/UseComponentCli.php | 2 +- src/Blocks/UseGlobalAssetsCli.php | 2 +- src/Blocks/UseManifestCli.php | 2 +- src/Blocks/UseStorybookCli.php | 2 +- src/Blocks/UseVariationCli.php | 2 +- src/Blocks/UseWrapperCli.php | 2 +- tests/WpCli/WpCliExampleTest.php | 13 +++++-------- 11 files changed, 15 insertions(+), 18 deletions(-) diff --git a/src/BlockPatterns/BlockPatternCli.php b/src/BlockPatterns/BlockPatternCli.php index d94e48346..2c5acc48a 100644 --- a/src/BlockPatterns/BlockPatternCli.php +++ b/src/BlockPatterns/BlockPatternCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'create_block_pattern'; + return 'create block_pattern'; } /** diff --git a/src/Blocks/BlocksCli.php b/src/Blocks/BlocksCli.php index 8d5e7beba..63573a4fc 100644 --- a/src/Blocks/BlocksCli.php +++ b/src/Blocks/BlocksCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'create_blocks_class'; + return 'create blocks_class'; } /** diff --git a/src/Blocks/UseAssetsCli.php b/src/Blocks/UseAssetsCli.php index b8b97bd92..214febeca 100644 --- a/src/Blocks/UseAssetsCli.php +++ b/src/Blocks/UseAssetsCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'use_assets'; + return 'use assets'; } /** diff --git a/src/Blocks/UseBlockCli.php b/src/Blocks/UseBlockCli.php index 06f2224bd..7d5d0defd 100644 --- a/src/Blocks/UseBlockCli.php +++ b/src/Blocks/UseBlockCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'use_block'; + return 'use block'; } /** diff --git a/src/Blocks/UseComponentCli.php b/src/Blocks/UseComponentCli.php index 6e4ce2d8b..8257c8931 100644 --- a/src/Blocks/UseComponentCli.php +++ b/src/Blocks/UseComponentCli.php @@ -24,7 +24,7 @@ class UseComponentCli extends AbstractBlocksCli * * @var string */ - public const COMMAND_NAME = 'use_component'; + public const COMMAND_NAME = 'use component'; /** * Get WPCLI command parent name diff --git a/src/Blocks/UseGlobalAssetsCli.php b/src/Blocks/UseGlobalAssetsCli.php index fc8590b4c..ac0bf3ba2 100644 --- a/src/Blocks/UseGlobalAssetsCli.php +++ b/src/Blocks/UseGlobalAssetsCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'use_global_assets'; + return 'use global_assets'; } /** diff --git a/src/Blocks/UseManifestCli.php b/src/Blocks/UseManifestCli.php index 3c6863ab4..58f94288d 100644 --- a/src/Blocks/UseManifestCli.php +++ b/src/Blocks/UseManifestCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'use_manifest'; + return 'use manifest'; } /** diff --git a/src/Blocks/UseStorybookCli.php b/src/Blocks/UseStorybookCli.php index afec59d30..f10fe5882 100644 --- a/src/Blocks/UseStorybookCli.php +++ b/src/Blocks/UseStorybookCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'use_storybook'; + return 'use storybook'; } /** diff --git a/src/Blocks/UseVariationCli.php b/src/Blocks/UseVariationCli.php index 97a078087..8e4a2aefe 100644 --- a/src/Blocks/UseVariationCli.php +++ b/src/Blocks/UseVariationCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'use_variation'; + return 'use variation'; } /** diff --git a/src/Blocks/UseWrapperCli.php b/src/Blocks/UseWrapperCli.php index 03defc302..6690ed3cf 100644 --- a/src/Blocks/UseWrapperCli.php +++ b/src/Blocks/UseWrapperCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'use_wrapper'; + return 'use wrapper'; } /** diff --git a/tests/WpCli/WpCliExampleTest.php b/tests/WpCli/WpCliExampleTest.php index 0588e17de..40594d021 100644 --- a/tests/WpCli/WpCliExampleTest.php +++ b/tests/WpCli/WpCliExampleTest.php @@ -3,11 +3,7 @@ namespace Tests\Unit\WpCli; use EightshiftBoilerplate\WpCli\WpCliExample; -use EightshiftLibs\Services\ServiceCliInterface; -use RuntimeException; -use function Tests\deleteCliOutput; -use function Tests\mock; use function Tests\setAfterEach; use function Tests\setBeforeEach; @@ -26,14 +22,15 @@ test('Register method will call init hook', function () { $this->mock->register(); - $this->assertSame(10, has_action('cli_init', 'EightshiftBoilerplate\WpCli\WpCliExample->registerCommand()')); + expect(has_action('cli_init', 'EightshiftBoilerplate\WpCli\WpCliExample->registerCommand()')) + ->toEqual(10); }); test('Prepare command docs returns correct doc', function() { - $customCommand = $this->mock->getDocs(); + $mock = $this->mock->getDocs(); - $this->assertIsArray($customCommand); - $this->assertArrayHasKey('shortdesc', $customCommand); + expect($mock) + ->toHaveKeys(['shortdesc']); }); test('Custom command class is callable', function() { From cccee935ee40d57c3ee51b548cc3394b4587011f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= Date: Wed, 6 Jul 2022 09:55:24 +0200 Subject: [PATCH 24/52] updating tests --- composer.json | 2 +- phpcs.xml.dist | 10 ++++++++++ src/AnalyticsGdpr/AnalyticsGdprCli.php | 2 +- src/Blocks/UseAssetsCli.php | 2 +- src/Blocks/UseBlockCli.php | 2 +- src/Blocks/UseComponentCli.php | 2 +- src/Blocks/UseGlobalAssetsCli.php | 2 +- src/Blocks/UseManifestCli.php | 2 +- src/Blocks/UseStorybookCli.php | 2 +- src/Blocks/UseVariationCli.php | 2 +- src/Blocks/UseWrapperCli.php | 2 +- tests/Blocks/BlockVariationCliTest.php | 2 +- tests/Cli/CliTest.php | 2 +- tests/WpCli/WpCliTest.php | 12 +++++++----- 14 files changed, 29 insertions(+), 17 deletions(-) diff --git a/composer.json b/composer.json index 5bfa392e2..c2413c939 100644 --- a/composer.json +++ b/composer.json @@ -35,7 +35,7 @@ "brain/monkey": "^2.6", "captainhook/captainhook": "^5.10", "dealerdirect/phpcodesniffer-composer-installer": "^0.7", - "infinum/eightshift-coding-standards": "^1.5", + "infinum/eightshift-coding-standards": "^1.6", "pestphp/pest": "^1.2", "php-stubs/wordpress-stubs": "^5.9", "phpunit/phpunit": "^9.5", diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 0563871e8..9461e5cc1 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -78,4 +78,14 @@ + + + + + + + + + + diff --git a/src/AnalyticsGdpr/AnalyticsGdprCli.php b/src/AnalyticsGdpr/AnalyticsGdprCli.php index 0fb2407c6..2ad7ae201 100644 --- a/src/AnalyticsGdpr/AnalyticsGdprCli.php +++ b/src/AnalyticsGdpr/AnalyticsGdprCli.php @@ -71,7 +71,7 @@ public function getDoc(): array } /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) // phpcs:ignore + public function __invoke(array $args, array $assocArgs) { $this->getIntroText($assocArgs); diff --git a/src/Blocks/UseAssetsCli.php b/src/Blocks/UseAssetsCli.php index 214febeca..d45098fc8 100644 --- a/src/Blocks/UseAssetsCli.php +++ b/src/Blocks/UseAssetsCli.php @@ -67,7 +67,7 @@ public function getDoc(): array } /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) // phpcs:ignore + public function __invoke(array $args, array $assocArgs) { $this->getIntroText($assocArgs); diff --git a/src/Blocks/UseBlockCli.php b/src/Blocks/UseBlockCli.php index 7d5d0defd..c02745bcd 100644 --- a/src/Blocks/UseBlockCli.php +++ b/src/Blocks/UseBlockCli.php @@ -90,7 +90,7 @@ public function getDoc(): array } /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) // phpcs:ignore Eightshift.Commenting.FunctionComment.WrongStyle + public function __invoke(array $args, array $assocArgs) { $this->getIntroText($assocArgs); diff --git a/src/Blocks/UseComponentCli.php b/src/Blocks/UseComponentCli.php index 8257c8931..7ea10db7c 100644 --- a/src/Blocks/UseComponentCli.php +++ b/src/Blocks/UseComponentCli.php @@ -97,7 +97,7 @@ public function getDoc(): array } /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) // phpcs:ignore Eightshift.Commenting.FunctionComment.WrongStyle + public function __invoke(array $args, array $assocArgs) { $this->getIntroText($assocArgs); diff --git a/src/Blocks/UseGlobalAssetsCli.php b/src/Blocks/UseGlobalAssetsCli.php index ac0bf3ba2..a97e5890c 100644 --- a/src/Blocks/UseGlobalAssetsCli.php +++ b/src/Blocks/UseGlobalAssetsCli.php @@ -67,7 +67,7 @@ public function getDoc(): array } /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) // phpcs:ignore + public function __invoke(array $args, array $assocArgs) { $this->getIntroText($assocArgs); diff --git a/src/Blocks/UseManifestCli.php b/src/Blocks/UseManifestCli.php index 58f94288d..e08ae3c80 100644 --- a/src/Blocks/UseManifestCli.php +++ b/src/Blocks/UseManifestCli.php @@ -66,7 +66,7 @@ public function getDoc(): array } /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) // phpcs:ignore + public function __invoke(array $args, array $assocArgs) { $this->getIntroText($assocArgs); diff --git a/src/Blocks/UseStorybookCli.php b/src/Blocks/UseStorybookCli.php index f10fe5882..5fca653ec 100644 --- a/src/Blocks/UseStorybookCli.php +++ b/src/Blocks/UseStorybookCli.php @@ -67,7 +67,7 @@ public function getDoc(): array } /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) // phpcs:ignore + public function __invoke(array $args, array $assocArgs) { $this->getIntroText($assocArgs); diff --git a/src/Blocks/UseVariationCli.php b/src/Blocks/UseVariationCli.php index 8e4a2aefe..0bdc340db 100644 --- a/src/Blocks/UseVariationCli.php +++ b/src/Blocks/UseVariationCli.php @@ -87,7 +87,7 @@ public function getDoc(): array } /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) // phpcs:ignore + public function __invoke(array $args, array $assocArgs) { $this->getIntroText($assocArgs); diff --git a/src/Blocks/UseWrapperCli.php b/src/Blocks/UseWrapperCli.php index 6690ed3cf..3d9dc90d1 100644 --- a/src/Blocks/UseWrapperCli.php +++ b/src/Blocks/UseWrapperCli.php @@ -63,7 +63,7 @@ public function getDoc(): array } /* @phpstan-ignore-next-line */ - public function __invoke(array $args, array $assocArgs) // phpcs:ignore + public function __invoke(array $args, array $assocArgs) { $this->getIntroText($assocArgs); diff --git a/tests/Blocks/BlockVariationCliTest.php b/tests/Blocks/BlockVariationCliTest.php index 14a49616c..5750aafe2 100644 --- a/tests/Blocks/BlockVariationCliTest.php +++ b/tests/Blocks/BlockVariationCliTest.php @@ -34,7 +34,7 @@ test('getCommandName will return correct value', function () { expect($this->mock->getCommandName()) ->toBeString() - ->toEqual('use_variation'); + ->toEqual('use variation'); }); //---------------------------------------------------------------------------------// diff --git a/tests/Cli/CliTest.php b/tests/Cli/CliTest.php index 0966d371e..d86e1dd87 100644 --- a/tests/Cli/CliTest.php +++ b/tests/Cli/CliTest.php @@ -37,7 +37,7 @@ expect(\count($publicClasses)) ->toBeInt() - ->toBe(52); // Public classes count. + ->toBe(50); // Public classes count. }); test('Running load command works', function() { diff --git a/tests/WpCli/WpCliTest.php b/tests/WpCli/WpCliTest.php index 4b21bdb82..979b893c9 100644 --- a/tests/WpCli/WpCliTest.php +++ b/tests/WpCli/WpCliTest.php @@ -30,11 +30,13 @@ $mock = \file_get_contents(Components::getProjectPaths('srcDestination', "WpCli{$sep}TestWpCli.php")); expect($mock) - ->assertContains('class TestWpCli implements ServiceCliInterface', $mock) - ->assertContains('function register', $mock) - ->assertContains('function registerCommand', $mock) - ->assertContains('function getDocs', $mock) - ->assertContains('function __invoke', $mock); + ->toContain( + 'class TestWpCli implements ServiceCliInterface', + 'function register', + 'function registerCommand', + 'function getDocs', + 'function __invoke', + ); }); From 3a3d569eb2cb6212e09ba1382fa6b7df66eda026 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= Date: Wed, 6 Jul 2022 10:00:58 +0200 Subject: [PATCH 25/52] updating tests --- src/Cli/ParentGroups/CliBlocks.php | 6 ++-- src/Cli/ParentGroups/CliBlocksCreate.php | 32 ++++++++++++++++++++++ src/Cli/ParentGroups/CliBlocksUse.php | 35 ++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 3 deletions(-) create mode 100644 src/Cli/ParentGroups/CliBlocksCreate.php create mode 100644 src/Cli/ParentGroups/CliBlocksUse.php diff --git a/src/Cli/ParentGroups/CliBlocks.php b/src/Cli/ParentGroups/CliBlocks.php index 57c9231fb..303da655f 100644 --- a/src/Cli/ParentGroups/CliBlocks.php +++ b/src/Cli/ParentGroups/CliBlocks.php @@ -18,13 +18,13 @@ * ## EXAMPLES * * # Copy block by name. - * $ wp boilerplate blocks use_block --name='paragraph' + * $ wp boilerplate blocks use block --name='paragraph' * * # Copy component by name. - * $ wp boilerplate blocks use_component --name='heading' + * $ wp boilerplate blocks use component --name='heading' * * # Copy wrapper. - * $ wp boilerplate blocks use_wrapper + * $ wp boilerplate blocks use wrapper */ class CliBlocks extends WP_CLI_Command { diff --git a/src/Cli/ParentGroups/CliBlocksCreate.php b/src/Cli/ParentGroups/CliBlocksCreate.php new file mode 100644 index 000000000..97702ada4 --- /dev/null +++ b/src/Cli/ParentGroups/CliBlocksCreate.php @@ -0,0 +1,32 @@ + Date: Wed, 6 Jul 2022 10:47:20 +0200 Subject: [PATCH 26/52] updating docs for new subcommands --- src/Cli/Cli.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Cli/Cli.php b/src/Cli/Cli.php index a23a6b58a..7c5e6a095 100644 --- a/src/Cli/Cli.php +++ b/src/Cli/Cli.php @@ -28,6 +28,8 @@ use EightshiftLibs\Cli\ParentGroups\CliCreate; use EightshiftLibs\Cli\ParentGroups\CliRun; use EightshiftLibs\Cli\ParentGroups\CliBlocks; +use EightshiftLibs\Cli\ParentGroups\CliBlocksCreate; +use EightshiftLibs\Cli\ParentGroups\CliBlocksUse; use EightshiftLibs\Cli\ParentGroups\CliInit; use EightshiftLibs\Columns\Media\WebPMediaColumnCli; use EightshiftLibs\Config\ConfigCli; @@ -84,6 +86,8 @@ class Cli CliCreate::class, CliRun::class, CliBlocks::class, + CliBlocksUse::class, + CliBlocksCreate::class, CliInit::class, ]; From 54050924865f5a96c2c0c4e03d236a5c3dded63c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= Date: Wed, 6 Jul 2022 11:13:13 +0200 Subject: [PATCH 27/52] fixing failing i18n command --- src/I18n/I18nCli.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/I18n/I18nCli.php b/src/I18n/I18nCli.php index b2053245a..9e65617ee 100644 --- a/src/I18n/I18nCli.php +++ b/src/I18n/I18nCli.php @@ -73,6 +73,14 @@ public function __invoke(array $args, array $assocArgs) $className = $this->getClassShortName(); + $sep = \DIRECTORY_SEPARATOR; + + $sourceLanguages = Components::getProjectPaths('srcDestination', "I18n{$sep}languages"); + + if (!\is_dir($sourceLanguages)) { + \mkdir($sourceLanguages, 0755, true); + } + // Read the template contents, and replace the placeholders with provided variables. $this->getExampleTemplate(__DIR__, $className) ->renameClassName($className) From 4133ae06f5eb3ac60eed74790ae63a458a6a7ee8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= Date: Wed, 6 Jul 2022 14:26:50 +0200 Subject: [PATCH 28/52] fixing wrong indentation --- src/Helpers/Components.php | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Helpers/Components.php b/src/Helpers/Components.php index f7874a722..1a7578569 100644 --- a/src/Helpers/Components.php +++ b/src/Helpers/Components.php @@ -387,7 +387,7 @@ public static function getProjectPaths(string $type = '', string $sufix = '', st } break; case 'libs': - $path = self::joinPaths($libsPath); + $path = self::joinPaths($libsPath); if (\getenv('ES_TEST')) { $path = ''; @@ -397,28 +397,28 @@ public static function getProjectPaths(string $type = '', string $sufix = '', st $path = self::joinPaths([...$flibsPath, $assetsPath]); if (\getenv('ES_TEST')) { - $path = self::joinPaths([...$testsDataPath, $assetsPath]); + $path = self::joinPaths([...$testsDataPath, $assetsPath]); } break; case 'blocksAssetsSource': $path = self::joinPaths([...$flibsPath, ...$blocksPath, $assetsPath]); if (\getenv('ES_TEST')) { - $path = self::joinPaths([...$testsDataPath, ...$blocksPath, $assetsPath]); + $path = self::joinPaths([...$testsDataPath, ...$blocksPath, $assetsPath]); } break; case 'blocksStorybookSource': $path = self::joinPaths([...$flibsPath, $storybookPath]); if (\getenv('ES_TEST')) { - $path = self::joinPaths([...$testsDataPath, $storybookPath]); + $path = self::joinPaths([...$testsDataPath, $storybookPath]); } break; case 'blocksSource': $path = self::joinPaths([...$flibsPath, ...$blocksPath]); if (\getenv('ES_TEST')) { - $path = self::joinPaths([...$testsDataPath, ...$blocksPath]); + $path = self::joinPaths([...$testsDataPath, ...$blocksPath]); } break; case 'blocksSourceCustom': @@ -438,28 +438,28 @@ public static function getProjectPaths(string $type = '', string $sufix = '', st $path = self::joinPaths([$assetsPath]); if (\getenv('ES_TEST')) { - $path = self::joinPaths([$cliOutputPath, $assetsPath]); + $path = self::joinPaths([$cliOutputPath, $assetsPath]); } break; case 'blocksAssetsDestination': $path = self::joinPaths([...$blocksPath, $assetsPath]); if (\getenv('ES_TEST')) { - $path = self::joinPaths([$cliOutputPath, ...$blocksPath, $assetsPath]); + $path = self::joinPaths([$cliOutputPath, ...$blocksPath, $assetsPath]); } break; case 'blocksStorybookDestination': $path = self::joinPaths([".{$storybookPath}"]); if (\getenv('ES_TEST')) { - $path = self::joinPaths([$cliOutputPath, ".{$storybookPath}"]); + $path = self::joinPaths([$cliOutputPath, ".{$storybookPath}"]); } break; case 'blocksDestination': $path = self::joinPaths($blocksPath); if (\getenv('ES_TEST')) { - $path = self::joinPaths([$cliOutputPath, ...$blocksPath]); + $path = self::joinPaths([$cliOutputPath, ...$blocksPath]); } break; case 'blocksDestinationCustom': @@ -484,7 +484,7 @@ public static function getProjectPaths(string $type = '', string $sufix = '', st $path = self::joinPaths([...$flibsPath, ...$blocksPath, $name]); if (\getenv('ES_TEST')) { - $path = self::joinPaths([...$testsDataPath, ...$blocksPath, $name]); + $path = self::joinPaths([...$testsDataPath, ...$blocksPath, $name]); } break; @@ -495,7 +495,7 @@ public static function getProjectPaths(string $type = '', string $sufix = '', st $path = self::joinPaths([...$blocksPath, $name]); if (\getenv('ES_TEST')) { - $path = self::joinPaths([$cliOutputPath, ...$blocksPath, $name]); + $path = self::joinPaths([$cliOutputPath, ...$blocksPath, $name]); } break; } From 0956525b81c40151f310dd1fa1e5932f6d22f8bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= Date: Wed, 6 Jul 2022 23:32:23 +0200 Subject: [PATCH 29/52] renaming command names from _ to - --- src/AdminMenus/AdminMenuCli.php | 2 +- src/AdminMenus/AdminReusableBlocksMenuCli.php | 2 +- src/AdminMenus/AdminSubMenuCli.php | 2 +- src/AnalyticsGdpr/AnalyticsGdprCli.php | 2 +- src/BlockPatterns/BlockPatternCli.php | 2 +- src/Blocks/BlocksCli.php | 2 +- src/Blocks/UseGlobalAssetsCli.php | 2 +- src/Columns/Media/WebPMediaColumnCli.php | 2 +- src/ConfigProject/ConfigProjectCli.php | 2 +- src/CustomMeta/AcfMetaCli.php | 2 +- src/CustomPostType/PostTypeCli.php | 2 +- src/Enqueue/Admin/EnqueueAdminCli.php | 2 +- src/Enqueue/Blocks/EnqueueBlocksCli.php | 2 +- src/Enqueue/Theme/EnqueueThemeCli.php | 2 +- src/Media/RegenerateWebPMediaCli.php | 2 +- src/Media/UseWebPMediaCli.php | 2 +- src/ModifyAdminAppearance/ModifyAdminAppearanceCli.php | 2 +- src/Rest/Fields/FieldCli.php | 2 +- src/Rest/Routes/LoadMore/LoadMoreRouteCli.php | 2 +- src/Rest/Routes/RouteCli.php | 2 +- src/Services/ServiceExampleCli.php | 2 +- src/ThemeOptions/ThemeOptionsCli.php | 2 +- src/View/EscapedViewCli.php | 2 +- src/WpCli/WpCli.php | 2 +- 24 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/AdminMenus/AdminMenuCli.php b/src/AdminMenus/AdminMenuCli.php index 0a823ed07..839a9e702 100644 --- a/src/AdminMenus/AdminMenuCli.php +++ b/src/AdminMenus/AdminMenuCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'admin_menu'; + return 'admin-menu'; } /** diff --git a/src/AdminMenus/AdminReusableBlocksMenuCli.php b/src/AdminMenus/AdminReusableBlocksMenuCli.php index a1206832b..3d09e93fe 100644 --- a/src/AdminMenus/AdminReusableBlocksMenuCli.php +++ b/src/AdminMenus/AdminReusableBlocksMenuCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'admin_reusable_blocks_menu'; + return 'admin-reusable-blocks-menu'; } /** diff --git a/src/AdminMenus/AdminSubMenuCli.php b/src/AdminMenus/AdminSubMenuCli.php index bda05eb09..b5563b2a6 100644 --- a/src/AdminMenus/AdminSubMenuCli.php +++ b/src/AdminMenus/AdminSubMenuCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'admin_sub_menu'; + return 'admin-sub-menu'; } /** diff --git a/src/AnalyticsGdpr/AnalyticsGdprCli.php b/src/AnalyticsGdpr/AnalyticsGdprCli.php index 2ad7ae201..c3f09c81e 100644 --- a/src/AnalyticsGdpr/AnalyticsGdprCli.php +++ b/src/AnalyticsGdpr/AnalyticsGdprCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'analytics_gdpr_settings'; + return 'analytics-gdpr-settings'; } /** diff --git a/src/BlockPatterns/BlockPatternCli.php b/src/BlockPatterns/BlockPatternCli.php index 2c5acc48a..f2db5c0de 100644 --- a/src/BlockPatterns/BlockPatternCli.php +++ b/src/BlockPatterns/BlockPatternCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'create block_pattern'; + return 'create block-pattern'; } /** diff --git a/src/Blocks/BlocksCli.php b/src/Blocks/BlocksCli.php index 63573a4fc..e17cba5b8 100644 --- a/src/Blocks/BlocksCli.php +++ b/src/Blocks/BlocksCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'create blocks_class'; + return 'create blocks-class'; } /** diff --git a/src/Blocks/UseGlobalAssetsCli.php b/src/Blocks/UseGlobalAssetsCli.php index a97e5890c..776681e22 100644 --- a/src/Blocks/UseGlobalAssetsCli.php +++ b/src/Blocks/UseGlobalAssetsCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'use global_assets'; + return 'use global-assets'; } /** diff --git a/src/Columns/Media/WebPMediaColumnCli.php b/src/Columns/Media/WebPMediaColumnCli.php index f5d3821a1..28e63715d 100644 --- a/src/Columns/Media/WebPMediaColumnCli.php +++ b/src/Columns/Media/WebPMediaColumnCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'webp_media_column'; + return 'webp-media-column'; } /** diff --git a/src/ConfigProject/ConfigProjectCli.php b/src/ConfigProject/ConfigProjectCli.php index 0272ab7d3..75684244a 100644 --- a/src/ConfigProject/ConfigProjectCli.php +++ b/src/ConfigProject/ConfigProjectCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'config_project'; + return 'config-project'; } /** diff --git a/src/CustomMeta/AcfMetaCli.php b/src/CustomMeta/AcfMetaCli.php index 01621f7b3..9c5d658da 100644 --- a/src/CustomMeta/AcfMetaCli.php +++ b/src/CustomMeta/AcfMetaCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'acf_meta'; + return 'acf-meta'; } /** diff --git a/src/CustomPostType/PostTypeCli.php b/src/CustomPostType/PostTypeCli.php index 799de2000..036647732 100644 --- a/src/CustomPostType/PostTypeCli.php +++ b/src/CustomPostType/PostTypeCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'post_type'; + return 'post-type'; } /** diff --git a/src/Enqueue/Admin/EnqueueAdminCli.php b/src/Enqueue/Admin/EnqueueAdminCli.php index c740e28ae..8028ab5d9 100644 --- a/src/Enqueue/Admin/EnqueueAdminCli.php +++ b/src/Enqueue/Admin/EnqueueAdminCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'enqueue_admin'; + return 'enqueue-admin'; } /** diff --git a/src/Enqueue/Blocks/EnqueueBlocksCli.php b/src/Enqueue/Blocks/EnqueueBlocksCli.php index 85429d4a6..66aee8f8d 100644 --- a/src/Enqueue/Blocks/EnqueueBlocksCli.php +++ b/src/Enqueue/Blocks/EnqueueBlocksCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'enqueue_blocks'; + return 'enqueue-blocks'; } /** diff --git a/src/Enqueue/Theme/EnqueueThemeCli.php b/src/Enqueue/Theme/EnqueueThemeCli.php index 75ffe9edd..393ee06b4 100644 --- a/src/Enqueue/Theme/EnqueueThemeCli.php +++ b/src/Enqueue/Theme/EnqueueThemeCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'enqueue_theme'; + return 'enqueue-theme'; } /** diff --git a/src/Media/RegenerateWebPMediaCli.php b/src/Media/RegenerateWebPMediaCli.php index 4684896b4..7fd8ab5cf 100644 --- a/src/Media/RegenerateWebPMediaCli.php +++ b/src/Media/RegenerateWebPMediaCli.php @@ -42,7 +42,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'regenerate_media'; + return 'regenerate-media'; } /** diff --git a/src/Media/UseWebPMediaCli.php b/src/Media/UseWebPMediaCli.php index d7670f09d..5ffee6ee3 100644 --- a/src/Media/UseWebPMediaCli.php +++ b/src/Media/UseWebPMediaCli.php @@ -48,7 +48,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'use_webp_media'; + return 'use-webp-media'; } /** diff --git a/src/ModifyAdminAppearance/ModifyAdminAppearanceCli.php b/src/ModifyAdminAppearance/ModifyAdminAppearanceCli.php index f1972b527..903b3f57f 100644 --- a/src/ModifyAdminAppearance/ModifyAdminAppearanceCli.php +++ b/src/ModifyAdminAppearance/ModifyAdminAppearanceCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'modify_admin_appearance'; + return 'modify-admin-appearance'; } /** diff --git a/src/Rest/Fields/FieldCli.php b/src/Rest/Fields/FieldCli.php index 9521e9e15..f6e46a89c 100644 --- a/src/Rest/Fields/FieldCli.php +++ b/src/Rest/Fields/FieldCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'rest_field'; + return 'rest-field'; } /** diff --git a/src/Rest/Routes/LoadMore/LoadMoreRouteCli.php b/src/Rest/Routes/LoadMore/LoadMoreRouteCli.php index 7defb03d3..7567a7c54 100644 --- a/src/Rest/Routes/LoadMore/LoadMoreRouteCli.php +++ b/src/Rest/Routes/LoadMore/LoadMoreRouteCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'rest_route_load_more'; + return 'rest-route-load-more'; } /** diff --git a/src/Rest/Routes/RouteCli.php b/src/Rest/Routes/RouteCli.php index 02d54b0a4..19c9beac4 100644 --- a/src/Rest/Routes/RouteCli.php +++ b/src/Rest/Routes/RouteCli.php @@ -50,7 +50,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'rest_route'; + return 'rest-route'; } /** diff --git a/src/Services/ServiceExampleCli.php b/src/Services/ServiceExampleCli.php index 77bd3bb8b..f3c8f4153 100644 --- a/src/Services/ServiceExampleCli.php +++ b/src/Services/ServiceExampleCli.php @@ -41,7 +41,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'service_example'; + return 'service-example'; } /** diff --git a/src/ThemeOptions/ThemeOptionsCli.php b/src/ThemeOptions/ThemeOptionsCli.php index 8e2f482ed..a7f1e36bd 100644 --- a/src/ThemeOptions/ThemeOptionsCli.php +++ b/src/ThemeOptions/ThemeOptionsCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'theme_options'; + return 'theme-options'; } /** diff --git a/src/View/EscapedViewCli.php b/src/View/EscapedViewCli.php index cee1dff9d..8c582f72d 100644 --- a/src/View/EscapedViewCli.php +++ b/src/View/EscapedViewCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'escaped_view'; + return 'escaped-view'; } /** diff --git a/src/WpCli/WpCli.php b/src/WpCli/WpCli.php index 371e302fc..8fbaa4784 100644 --- a/src/WpCli/WpCli.php +++ b/src/WpCli/WpCli.php @@ -36,7 +36,7 @@ public function getCommandParentName(): string */ public function getCommandName(): string { - return 'wp_cli'; + return 'wp-cli'; } /** From f49a95449ac5a65023de4b499a2e60e531859145 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= Date: Wed, 6 Jul 2022 23:33:13 +0200 Subject: [PATCH 30/52] Update src/ConfigProject/ConfigProjectCli.php MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Denis Žoljom --- src/ConfigProject/ConfigProjectCli.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ConfigProject/ConfigProjectCli.php b/src/ConfigProject/ConfigProjectCli.php index 75684244a..2f141d45f 100644 --- a/src/ConfigProject/ConfigProjectCli.php +++ b/src/ConfigProject/ConfigProjectCli.php @@ -64,7 +64,7 @@ public function getDoc(): array [ 'type' => 'assoc', 'name' => 'path', - 'description' => 'Define absolute path to project root folder.', + 'description' => 'Define absolute path to project root folder.', 'optional' => true, 'default' => $this->getDefaultArg('path'), ], From a1d46ed230677b4ba73097f3196a865eb5ae4d84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= Date: Wed, 6 Jul 2022 23:47:42 +0200 Subject: [PATCH 31/52] fixing tests --- tests/AdminMenus/AdminMenuCliTest.php | 2 +- tests/AdminMenus/AdminMenuExampleTest.php | 31 ------------------- .../AdminReusableBlocksMenuCliTest.php | 2 +- tests/AdminMenus/AdminSubMenuCliTest.php | 2 +- tests/Blocks/BlocksExampleTest.php | 9 ------ .../Columns/Media/WebPMediaColumnCliTest.php | 2 +- tests/ConfigProject/ConfigProjectCliTest.php | 2 +- .../CustomPostType/CustomPostTypeCliTest.php | 2 +- tests/Helpers.php | 3 ++ tests/Helpers/AttributesTraitTest.php | 1 - tests/Helpers/ComponentHelpersTest.php | 1 - tests/Helpers/CssVariablesTraitTest.php | 2 -- tests/Helpers/StoreTraitTest.php | 1 - 13 files changed, 9 insertions(+), 51 deletions(-) diff --git a/tests/AdminMenus/AdminMenuCliTest.php b/tests/AdminMenus/AdminMenuCliTest.php index 9ed6ec739..9020d260b 100644 --- a/tests/AdminMenus/AdminMenuCliTest.php +++ b/tests/AdminMenus/AdminMenuCliTest.php @@ -34,7 +34,7 @@ test('getCommandName will return correct value', function () { expect($this->mock->getCommandName()) ->toBeString() - ->toEqual('admin_menu'); + ->toEqual('admin-menu'); }); //---------------------------------------------------------------------------------// diff --git a/tests/AdminMenus/AdminMenuExampleTest.php b/tests/AdminMenus/AdminMenuExampleTest.php index 45c9d6fc0..4b819772d 100644 --- a/tests/AdminMenus/AdminMenuExampleTest.php +++ b/tests/AdminMenus/AdminMenuExampleTest.php @@ -76,34 +76,3 @@ protected function getViewComponent(): string ->not->toBeEmpty() ->toContain('
Unable to locate component by path:');
 });
-
-// test('processAdminMenu will render the error if the component is missing', function() {
-// 	Functions\when('wp_nonce_field')->justReturn('nonce');
-
-// 	$faultyExample = new class extends AdminMenuExample {
-// 		protected function getViewComponent(): string
-// 		{
-// 			return 'test';
-// 		}
-// 	};
-
-// 	ob_start();
-// 	$faultyExample->processAdminMenu([]);
-// 	$contents = ob_get_clean();
-
-// 	expect($contents)
-// 		->not->toBeEmpty()
-// 		->toContain('
Unable to locate component by path:');
-// });
-
-
-// test('getIcon will return the default icon', function() {
-
-// 	// We shouldn't do this, but the add_menu_page is called in a closure.
-// 	$method = new \ReflectionMethod('EightshiftBoilerplate\\AdminMenus\\AdminMenuExample', 'getIcon');
-// 	$method->setAccessible(true);
-
-// 	expect($method->invoke(new AdminMenuExample()))
-// 		->not->toBeEmpty()
-// 		->toBe('%menu_icon%');
-// });
diff --git a/tests/AdminMenus/AdminReusableBlocksMenuCliTest.php b/tests/AdminMenus/AdminReusableBlocksMenuCliTest.php
index 19724f003..720dfce5e 100644
--- a/tests/AdminMenus/AdminReusableBlocksMenuCliTest.php
+++ b/tests/AdminMenus/AdminReusableBlocksMenuCliTest.php
@@ -34,7 +34,7 @@
 test('getCommandName will return correct value', function () {
 	expect($this->mock->getCommandName())
 		->toBeString()
-		->toEqual('admin_reusable_blocks_menu');
+		->toEqual('admin-reusable-blocks-menu');
 });
 
 //---------------------------------------------------------------------------------//
diff --git a/tests/AdminMenus/AdminSubMenuCliTest.php b/tests/AdminMenus/AdminSubMenuCliTest.php
index 29967c52d..8f12a7390 100644
--- a/tests/AdminMenus/AdminSubMenuCliTest.php
+++ b/tests/AdminMenus/AdminSubMenuCliTest.php
@@ -34,7 +34,7 @@
 test('getCommandName will return correct value', function () {
 	expect($this->mock->getCommandName())
 		->toBeString()
-		->toEqual('admin_sub_menu');
+		->toEqual('admin-sub-menu');
 });
 
 //---------------------------------------------------------------------------------//
diff --git a/tests/Blocks/BlocksExampleTest.php b/tests/Blocks/BlocksExampleTest.php
index 5ca292d4c..e58426034 100644
--- a/tests/Blocks/BlocksExampleTest.php
+++ b/tests/Blocks/BlocksExampleTest.php
@@ -96,8 +96,6 @@
 
 	buildTestBlocks();
 
-	$this->mock->getBlocksDataFullRaw();
-
 	$list = $this->mock->getAllBlocksListOld([], $post);
 
 	expect($list)
@@ -115,8 +113,6 @@
 
 	buildTestBlocks();
 
-	(new BlocksExample())->getBlocksDataFullRaw();
-
 	Components::setConfigFlags();
 
 	$blocks = $this->mock->getAllBlocksList(false, $blockContext);
@@ -213,8 +209,6 @@
 
 	buildTestBlocks();
 
-	$this->mock->getBlocksDataFullRaw();
-
 	$this->mock->changeEditorColorPalette();
 
 	expect(\getenv('EDITOR_COLOR_PALETTE'))->toBe('true');
@@ -230,8 +224,6 @@
 
 	buildTestBlocks();
 
-	$this->mock->getBlocksDataFullRaw();
-
 	$this->mock->registerBlocks();
 
 	expect(\getenv('BLOCK_TYPE'))->toBe('true');
@@ -372,7 +364,6 @@
 
 	// Set namespace data.
 	buildTestBlocks();
-	$this->mock->getBlocksDataFullRaw();
 
 	$filteredBlockContent = $this->mock->filterBlocksContent($parsedBlock, []);
 
diff --git a/tests/Columns/Media/WebPMediaColumnCliTest.php b/tests/Columns/Media/WebPMediaColumnCliTest.php
index 23de82e26..ab4674b40 100644
--- a/tests/Columns/Media/WebPMediaColumnCliTest.php
+++ b/tests/Columns/Media/WebPMediaColumnCliTest.php
@@ -24,7 +24,7 @@
 
 	expect($mock)
 		->toBeString()
-		->toEqual('webp_media_column');
+		->toEqual('webp-media-column');
 });
 
 test('Check if CLI command documentation is correct.', function () {
diff --git a/tests/ConfigProject/ConfigProjectCliTest.php b/tests/ConfigProject/ConfigProjectCliTest.php
index ad73c1406..63a316703 100644
--- a/tests/ConfigProject/ConfigProjectCliTest.php
+++ b/tests/ConfigProject/ConfigProjectCliTest.php
@@ -34,7 +34,7 @@
 test('getCommandName will return correct value', function () {
 	expect($this->mock->getCommandName())
 		->toBeString()
-		->toEqual('config_project');
+		->toEqual('config-project');
 });
 
 //---------------------------------------------------------------------------------//
diff --git a/tests/CustomPostType/CustomPostTypeCliTest.php b/tests/CustomPostType/CustomPostTypeCliTest.php
index a3d815b89..f753570c7 100644
--- a/tests/CustomPostType/CustomPostTypeCliTest.php
+++ b/tests/CustomPostType/CustomPostTypeCliTest.php
@@ -35,7 +35,7 @@
 test('getCommandName will return correct value', function () {
 	expect($this->mock->getCommandName())
 		->toBeString()
-		->toEqual('post_type');
+		->toEqual('post-type');
 });
 
 //---------------------------------------------------------------------------------//
diff --git a/tests/Helpers.php b/tests/Helpers.php
index 395e642c0..4ad7f6628 100644
--- a/tests/Helpers.php
+++ b/tests/Helpers.php
@@ -5,6 +5,7 @@
 use Brain\Monkey\Functions;
 use Mockery;
 use Brain\Monkey;
+use EightshiftBoilerplate\Blocks\BlocksExample;
 use EightshiftLibs\Init\InitBlocksCli;
 use Exception;
 use Mockery\MockInterface;
@@ -301,6 +302,8 @@ function getCliOutputFile(string $path = ''): string
  */
 function buildTestBlocks() {
 	(new InitBlocksCli('boilerplate'))->__invoke([], []);
+
+	(new BlocksExample())->getBlocksDataFullRaw();
 }
 
 /**
diff --git a/tests/Helpers/AttributesTraitTest.php b/tests/Helpers/AttributesTraitTest.php
index 67395648d..4a620ae99 100644
--- a/tests/Helpers/AttributesTraitTest.php
+++ b/tests/Helpers/AttributesTraitTest.php
@@ -16,7 +16,6 @@
 	setBeforeEach();
 
 	buildTestBlocks();
-	(new BlocksExample())->getBlocksDataFullRaw();
 });
 
 afterEach(function () {
diff --git a/tests/Helpers/ComponentHelpersTest.php b/tests/Helpers/ComponentHelpersTest.php
index ed91ad4fd..6f964554e 100644
--- a/tests/Helpers/ComponentHelpersTest.php
+++ b/tests/Helpers/ComponentHelpersTest.php
@@ -15,7 +15,6 @@
 	setBeforeEach();
 
 	buildTestBlocks();
-	(new BlocksExample())->getBlocksDataFullRaw();
 });
 
 afterEach(function () {
diff --git a/tests/Helpers/CssVariablesTraitTest.php b/tests/Helpers/CssVariablesTraitTest.php
index aae5d3975..4f5eeeaad 100644
--- a/tests/Helpers/CssVariablesTraitTest.php
+++ b/tests/Helpers/CssVariablesTraitTest.php
@@ -5,7 +5,6 @@
 use EightshiftLibs\Helpers\Components;
 
 use Brain\Monkey\Functions;
-use EightshiftBoilerplate\Blocks\BlocksExample;
 
 use function Tests\buildTestBlocks;
 use function Tests\setAfterEach;
@@ -15,7 +14,6 @@
 	setBeforeEach();
 
 	buildTestBlocks();
-	(new BlocksExample())->getBlocksDataFullRaw();
 });
 
 afterEach(function () {
diff --git a/tests/Helpers/StoreTraitTest.php b/tests/Helpers/StoreTraitTest.php
index 41913318a..aaf6ca3a9 100644
--- a/tests/Helpers/StoreTraitTest.php
+++ b/tests/Helpers/StoreTraitTest.php
@@ -13,7 +13,6 @@
 	setBeforeEach();
 
 	buildTestBlocks();
-	(new BlocksExample())->getBlocksDataFullRaw();
 });
 
 afterEach(function () {

From 93639ba513c37ee9817d086bfd98c81080cc253d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= 
Date: Thu, 7 Jul 2022 00:03:53 +0200
Subject: [PATCH 32/52] fixing tests

---
 tests/BlockPatterns/BlockPatternCliTest.php   |  6 +-
 .../CustomPostType/CustomPostTypeCliTest.php  | 14 ++--
 tests/CustomTaxonomy/TaxonomyCliTest.php      | 12 +++-
 tests/Geolocation/AbstractGeolocationTest.php | 22 ++++--
 tests/Helpers.php                             | 69 -------------------
 tests/I18n/I18nCliTest.php                    |  2 -
 tests/Setup/UpdateCliTest.php                 |  3 -
 7 files changed, 39 insertions(+), 89 deletions(-)

diff --git a/tests/BlockPatterns/BlockPatternCliTest.php b/tests/BlockPatterns/BlockPatternCliTest.php
index 7d9d3c938..723514a27 100644
--- a/tests/BlockPatterns/BlockPatternCliTest.php
+++ b/tests/BlockPatterns/BlockPatternCliTest.php
@@ -3,10 +3,10 @@
 namespace Tests\Unit\BlockPatterns;
 
 use EightshiftLibs\BlockPatterns\BlockPatternCli;
+use EightshiftLibs\Helpers\Components;
 
 use function Tests\setAfterEach;
 use function Tests\setBeforeEach;
-use function Tests\getCliOutputPath;
 
 beforeEach(function () {
 	setBeforeEach();
@@ -27,7 +27,9 @@
 	$mock([], $this->mock->getDefaultArgs());
 
 	// Check the output dir if the generated method is correctly generated.
-	$output = \file_get_contents(getCliOutputPath('src/BlockPatterns/ExampleTitleBlockPattern.php'));
+	$sep = \DIRECTORY_SEPARATOR;
+
+	$output = \file_get_contents(Components::getProjectPaths('srcDestination', "BlockPatterns{$sep}ExampleTitleBlockPattern.php"));
 
 	expect($output)
 		->toContain(
diff --git a/tests/CustomPostType/CustomPostTypeCliTest.php b/tests/CustomPostType/CustomPostTypeCliTest.php
index f753570c7..68d4be187 100644
--- a/tests/CustomPostType/CustomPostTypeCliTest.php
+++ b/tests/CustomPostType/CustomPostTypeCliTest.php
@@ -4,11 +4,10 @@
 
 use EightshiftLibs\Cli\ParentGroups\CliCreate;
 use EightshiftLibs\CustomPostType\PostTypeCli;
-
+use EightshiftLibs\Helpers\Components;
 
 use function Tests\setAfterEach;
 use function Tests\setBeforeEach;
-use function Tests\getCliOutputFile;
 
 beforeEach(function () {
 	setBeforeEach();
@@ -80,7 +79,11 @@
 	$mock = $this->mock;
 	$mock([], $this->mock->getDefaultArgs());
 
-	expect(getCliOutputFile('src/CustomPostType/ProductPostType.php'))
+	$sep = \DIRECTORY_SEPARATOR;
+
+	$output = file_get_contents(Components::getProjectPaths('srcDestination', "CustomPostType{$sep}ProductPostType.php"));
+
+	expect($output)
 		->toContain(
 			'class ProductPostType',
 			'Product',
@@ -118,7 +121,10 @@
 		'menu_icon' => 'admin-panel',
 	]);
 
-	expect(getCliOutputFile('src/CustomPostType/TestPostType.php'))
+	$sep = \DIRECTORY_SEPARATOR;
+	$output = file_get_contents(Components::getProjectPaths('srcDestination', "CustomPostType{$sep}TestPostType.php"));
+
+	expect($output)
 		->toContain(
 			'class TestPostType',
 			'Test',
diff --git a/tests/CustomTaxonomy/TaxonomyCliTest.php b/tests/CustomTaxonomy/TaxonomyCliTest.php
index aca6844e7..695af2fa0 100644
--- a/tests/CustomTaxonomy/TaxonomyCliTest.php
+++ b/tests/CustomTaxonomy/TaxonomyCliTest.php
@@ -4,10 +4,10 @@
 
 use EightshiftLibs\Cli\ParentGroups\CliCreate;
 use EightshiftLibs\CustomTaxonomy\TaxonomyCli;
+use EightshiftLibs\Helpers\Components;
 
 use function Tests\setAfterEach;
 use function Tests\setBeforeEach;
-use function Tests\getCliOutputFile;
 
 beforeEach(function () {
 	setBeforeEach();
@@ -73,7 +73,10 @@
 	$mock = $this->mock;
 	$mock([], $this->mock->getDefaultArgs());
 
-	expect(getCliOutputFile('src/CustomTaxonomy/LocationTaxonomy.php'))
+	$sep = \DIRECTORY_SEPARATOR;
+	$output = file_get_contents(Components::getProjectPaths('srcDestination', "CustomTaxonomy{$sep}LocationTaxonomy.php"));
+
+	expect($output)
 		->toContain(
 			'class LocationTaxonomy',
 			'Location',
@@ -102,7 +105,10 @@
 		'post_type_slug' => 'product',
 	]);
 
-	expect(getCliOutputFile('src/CustomTaxonomy/TestTaxonomy.php'))
+	$sep = \DIRECTORY_SEPARATOR;
+	$output = file_get_contents(Components::getProjectPaths('srcDestination', "CustomTaxonomy{$sep}TestTaxonomy.php"));
+
+	expect($output)
 		->toContain(
 			'class TestTaxonomy',
 			'Test',
diff --git a/tests/Geolocation/AbstractGeolocationTest.php b/tests/Geolocation/AbstractGeolocationTest.php
index 290331656..53f5b2386 100644
--- a/tests/Geolocation/AbstractGeolocationTest.php
+++ b/tests/Geolocation/AbstractGeolocationTest.php
@@ -4,9 +4,9 @@
 
 use function Tests\setAfterEach;
 use function Tests\setBeforeEach;
-use function Tests\getDataPath;
 use Brain\Monkey\Functions;
 use EightshiftBoilerplate\Geolocation\GeolocationExample;
+use EightshiftLibs\Helpers\Components;
 use Exception;
 
 use function Tests\mock;
@@ -104,8 +104,11 @@
 
 test('setLocationCookie will set cookie based on the server location.', function () {
 	$mock = mock(GeolocationExample::class)->makePartial();
-	$mock->shouldReceive('getGeolocationPharLocation')->andReturn(getDataPath('geolocation/geoip.phar'));
-	$mock->shouldReceive('getGeolocationDbLocation')->andReturn(getDataPath('geolocation/geoip.mmdb'));
+
+	$sep = \DIRECTORY_SEPARATOR;
+
+	$mock->shouldReceive('getGeolocationPharLocation')->andReturn(Components::getProjectPaths('testsData', "geolocation{$sep}geoip.phar"));
+	$mock->shouldReceive('getGeolocationDbLocation')->andReturn(Components::getProjectPaths('testsData', "geolocation{$sep}geoip.mmdb"));
 	$mock->shouldReceive('setCookie')->withArgs(function (string $name, string $value) {
 		putenv("ES_SIDEAFFECT_1={$name}");
 		putenv("ES_SIDEAFFECT_2={$value}");
@@ -122,8 +125,11 @@
 
 test('setLocationCookie will set cookie based on the provided manual ip.', function () {
 	$mock = mock(GeolocationExample::class)->makePartial();
-	$mock->shouldReceive('getGeolocationPharLocation')->andReturn(getDataPath('geolocation/geoip.phar'));
-	$mock->shouldReceive('getGeolocationDbLocation')->andReturn(getDataPath('geolocation/geoip.mmdb'));
+
+	$sep = \DIRECTORY_SEPARATOR;
+
+	$mock->shouldReceive('getGeolocationPharLocation')->andReturn(Components::getProjectPaths('testsData', "geolocation{$sep}geoip.phar"));
+	$mock->shouldReceive('getGeolocationDbLocation')->andReturn(Components::getProjectPaths('testsData', "geolocation{$sep}geoip.mmdb"));
 	$mock->shouldReceive('getIpAddress')->andReturn($this->germanIp);
 	$mock->shouldReceive('setCookie')->withArgs(function (string $name, string $value) {
 		putenv("ES_SIDEAFFECT_1={$name}");
@@ -137,7 +143,11 @@
 
 test('setLocationCookie will throw and error if something is wrong.', function () {
 	$mock = mock(GeolocationExample::class)->makePartial();
-	$mock->shouldReceive('getGeolocationPharLocation')->andReturn(getDataPath('geolocation/geoip.phar'));
+
+	$sep = \DIRECTORY_SEPARATOR;
+
+	$mock->shouldReceive('getGeolocationPharLocation')->andReturn(Components::getProjectPaths('testsData', "geolocation{$sep}geoip.phar"));
+
 	$mock->shouldReceive('getGeolocationDbLocation')->andThrow(new Exception('test'));
 	$mock->shouldReceive('getIpAddress')->andReturn($this->germanIp);
 	$mock->shouldReceive('setCookie')->withArgs(function (string $name, string $value) {
diff --git a/tests/Helpers.php b/tests/Helpers.php
index 4ad7f6628..a23b554e8 100644
--- a/tests/Helpers.php
+++ b/tests/Helpers.php
@@ -183,7 +183,6 @@ function setAfterEach($delete = true) {
 
 	for ($i = 1; $i <= 10; $i++ ) {
 		putenv("ES_SIDEAFFECT_{$i}");
-		putenv("ES_SIDEAFFECT_1");
 	}
 
 	putenv('ES_CLI_SUCCESS_HAPPENED');
@@ -227,74 +226,6 @@ function deleteCliOutput(string $dir = '') : void
 	rmdir($dir);
 }
 
-/**
- * Get path to data mocks.
- *
- * @param string $path Path to attach.
- *
- * @return string
- */
-function getDataPath(string $path = ''): string
-{
-	$sep = \DIRECTORY_SEPARATOR;
-	$internalPath = __DIR__ . "{$sep}data";
-
-	if ($path) {
-		return "{$internalPath}{$sep}{$path}";
-	}
-
-	return $internalPath;
-}
-
-/**
- * Get path to cliOutput mocks.
- *
- * @param string $path Path to attach.
- *
- * @return string
- */
-function getCliOutputPath(string $path = ''): string
-{
-	$sep = \DIRECTORY_SEPARATOR;
-	$internalPath = getProjectRootPath() . "{$sep}cliOutput";
-
-	if ($path) {
-		return "{$internalPath}{$sep}{$path}";
-	}
-
-	return $internalPath;
-}
-
-/**
- * Get project root path for mocks.
- *
- * @return string
- */
-function getProjectRootPath(): string
-{
-	return \dirname(__FILE__, 2);
-}
-
-/**
- * Get file in cliOutput folder.
- *
- * @param string $path Path to get.
- *
- * @throws Exception If file is missing.
- *
- * @return string
- */
-function getCliOutputFile(string $path = ''): string
-{
-	$pathFile = getCliOutputPath($path);
-
-	if (!file_exists($pathFile)) {
-		throw new Exception("File missing on this path: {$pathFile}");
-	}
-
-	return \file_get_contents($pathFile);
-}
-
 /**
  * Build all blocks setup output.
  *
diff --git a/tests/I18n/I18nCliTest.php b/tests/I18n/I18nCliTest.php
index 65454741f..9337ba39a 100644
--- a/tests/I18n/I18nCliTest.php
+++ b/tests/I18n/I18nCliTest.php
@@ -5,8 +5,6 @@
 use EightshiftLibs\Helpers\Components;
 use EightshiftLibs\I18n\I18nCli;
 
-use function Tests\deleteCliOutput;
-use function Tests\mock;
 use function Tests\setAfterEach;
 use function Tests\setBeforeEach;
 
diff --git a/tests/Setup/UpdateCliTest.php b/tests/Setup/UpdateCliTest.php
index 2f8f50cc1..c0241bf49 100644
--- a/tests/Setup/UpdateCliTest.php
+++ b/tests/Setup/UpdateCliTest.php
@@ -5,9 +5,6 @@
 use EightshiftLibs\Setup\UpdateCli;
 use Exception;
 
-use function Brain\Monkey\Functions\when;
-use function Tests\deleteCliOutput;
-use function Tests\mock;
 use function Tests\setAfterEach;
 use function Tests\setBeforeEach;
 

From 7b95c17dcbfc1022b7a5b0f9a81ca94c6aac6e3b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= 
Date: Thu, 7 Jul 2022 15:11:41 +0200
Subject: [PATCH 33/52] updating cli command names

---
 src/Blocks/BlocksCli.php                 |  2 +-
 src/Blocks/UseAssetsCli.php              |  2 +-
 src/Blocks/UseBlockCli.php               |  2 +-
 src/Blocks/UseComponentCli.php           |  2 +-
 src/Blocks/UseGlobalAssetsCli.php        |  2 +-
 src/Blocks/UseManifestCli.php            |  2 +-
 src/Blocks/UseStorybookCli.php           |  2 +-
 src/Blocks/UseVariationCli.php           |  2 +-
 src/Blocks/UseWrapperCli.php             |  2 +-
 src/Cli/Cli.php                          |  4 ---
 src/Cli/ParentGroups/CliBlocks.php       |  6 ++--
 src/Cli/ParentGroups/CliBlocksCreate.php | 32 ----------------------
 src/Cli/ParentGroups/CliBlocksUse.php    | 35 ------------------------
 tests/Blocks/BlockVariationCliTest.php   |  2 +-
 14 files changed, 13 insertions(+), 84 deletions(-)
 delete mode 100644 src/Cli/ParentGroups/CliBlocksCreate.php
 delete mode 100644 src/Cli/ParentGroups/CliBlocksUse.php

diff --git a/src/Blocks/BlocksCli.php b/src/Blocks/BlocksCli.php
index e17cba5b8..4c482bad7 100644
--- a/src/Blocks/BlocksCli.php
+++ b/src/Blocks/BlocksCli.php
@@ -36,7 +36,7 @@ public function getCommandParentName(): string
 	 */
 	public function getCommandName(): string
 	{
-		return 'create blocks-class';
+		return 'create-blocks-class';
 	}
 
 	/**
diff --git a/src/Blocks/UseAssetsCli.php b/src/Blocks/UseAssetsCli.php
index d45098fc8..a0853dd59 100644
--- a/src/Blocks/UseAssetsCli.php
+++ b/src/Blocks/UseAssetsCli.php
@@ -36,7 +36,7 @@ public function getCommandParentName(): string
 	 */
 	public function getCommandName(): string
 	{
-		return 'use assets';
+		return 'use-assets';
 	}
 
 	/**
diff --git a/src/Blocks/UseBlockCli.php b/src/Blocks/UseBlockCli.php
index c02745bcd..14b4bc409 100644
--- a/src/Blocks/UseBlockCli.php
+++ b/src/Blocks/UseBlockCli.php
@@ -36,7 +36,7 @@ public function getCommandParentName(): string
 	 */
 	public function getCommandName(): string
 	{
-		return 'use block';
+		return 'use-block';
 	}
 
 	/**
diff --git a/src/Blocks/UseComponentCli.php b/src/Blocks/UseComponentCli.php
index 7ea10db7c..ef062a476 100644
--- a/src/Blocks/UseComponentCli.php
+++ b/src/Blocks/UseComponentCli.php
@@ -24,7 +24,7 @@ class UseComponentCli extends AbstractBlocksCli
 	 *
 	 * @var string
 	 */
-	public const COMMAND_NAME = 'use component';
+	public const COMMAND_NAME = 'use-component';
 
 	/**
 	 * Get WPCLI command parent name
diff --git a/src/Blocks/UseGlobalAssetsCli.php b/src/Blocks/UseGlobalAssetsCli.php
index 776681e22..588d11735 100644
--- a/src/Blocks/UseGlobalAssetsCli.php
+++ b/src/Blocks/UseGlobalAssetsCli.php
@@ -36,7 +36,7 @@ public function getCommandParentName(): string
 	 */
 	public function getCommandName(): string
 	{
-		return 'use global-assets';
+		return 'use-global-assets';
 	}
 
 	/**
diff --git a/src/Blocks/UseManifestCli.php b/src/Blocks/UseManifestCli.php
index e08ae3c80..090e3217e 100644
--- a/src/Blocks/UseManifestCli.php
+++ b/src/Blocks/UseManifestCli.php
@@ -36,7 +36,7 @@ public function getCommandParentName(): string
 	 */
 	public function getCommandName(): string
 	{
-		return 'use manifest';
+		return 'use-manifest';
 	}
 
 	/**
diff --git a/src/Blocks/UseStorybookCli.php b/src/Blocks/UseStorybookCli.php
index 5fca653ec..461fb9123 100644
--- a/src/Blocks/UseStorybookCli.php
+++ b/src/Blocks/UseStorybookCli.php
@@ -36,7 +36,7 @@ public function getCommandParentName(): string
 	 */
 	public function getCommandName(): string
 	{
-		return 'use storybook';
+		return 'use-storybook';
 	}
 
 	/**
diff --git a/src/Blocks/UseVariationCli.php b/src/Blocks/UseVariationCli.php
index 0bdc340db..75db4c5db 100644
--- a/src/Blocks/UseVariationCli.php
+++ b/src/Blocks/UseVariationCli.php
@@ -36,7 +36,7 @@ public function getCommandParentName(): string
 	 */
 	public function getCommandName(): string
 	{
-		return 'use variation';
+		return 'use-variation';
 	}
 
 	/**
diff --git a/src/Blocks/UseWrapperCli.php b/src/Blocks/UseWrapperCli.php
index 3d9dc90d1..8af0593d4 100644
--- a/src/Blocks/UseWrapperCli.php
+++ b/src/Blocks/UseWrapperCli.php
@@ -36,7 +36,7 @@ public function getCommandParentName(): string
 	 */
 	public function getCommandName(): string
 	{
-		return 'use wrapper';
+		return 'use-wrapper';
 	}
 
 	/**
diff --git a/src/Cli/Cli.php b/src/Cli/Cli.php
index 7c5e6a095..a23a6b58a 100644
--- a/src/Cli/Cli.php
+++ b/src/Cli/Cli.php
@@ -28,8 +28,6 @@
 use EightshiftLibs\Cli\ParentGroups\CliCreate;
 use EightshiftLibs\Cli\ParentGroups\CliRun;
 use EightshiftLibs\Cli\ParentGroups\CliBlocks;
-use EightshiftLibs\Cli\ParentGroups\CliBlocksCreate;
-use EightshiftLibs\Cli\ParentGroups\CliBlocksUse;
 use EightshiftLibs\Cli\ParentGroups\CliInit;
 use EightshiftLibs\Columns\Media\WebPMediaColumnCli;
 use EightshiftLibs\Config\ConfigCli;
@@ -86,8 +84,6 @@ class Cli
 		CliCreate::class,
 		CliRun::class,
 		CliBlocks::class,
-		CliBlocksUse::class,
-		CliBlocksCreate::class,
 		CliInit::class,
 	];
 
diff --git a/src/Cli/ParentGroups/CliBlocks.php b/src/Cli/ParentGroups/CliBlocks.php
index 303da655f..849222c9f 100644
--- a/src/Cli/ParentGroups/CliBlocks.php
+++ b/src/Cli/ParentGroups/CliBlocks.php
@@ -18,13 +18,13 @@
  * ## EXAMPLES
  *
  *    # Copy block by name.
- *    $ wp boilerplate blocks use block --name='paragraph'
+ *    $ wp boilerplate blocks use-block --name='paragraph'
  *
  *    # Copy component by name.
- *    $ wp boilerplate blocks use component --name='heading'
+ *    $ wp boilerplate blocks use-component --name='heading'
  *
  *    # Copy wrapper.
- *    $ wp boilerplate blocks use wrapper
+ *    $ wp boilerplate blocks use-wrapper
  */
 class CliBlocks extends WP_CLI_Command
 {
diff --git a/src/Cli/ParentGroups/CliBlocksCreate.php b/src/Cli/ParentGroups/CliBlocksCreate.php
deleted file mode 100644
index 97702ada4..000000000
--- a/src/Cli/ParentGroups/CliBlocksCreate.php
+++ /dev/null
@@ -1,32 +0,0 @@
-mock->getCommandName())
 		->toBeString()
-		->toEqual('use variation');
+		->toEqual('use-variation');
 });
 
 //---------------------------------------------------------------------------------//

From 081d31bc8e77206acb90eafa16c30ec18bddbe61 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ruz=CC=8Cevic=CC=81?= 
Date: Thu, 7 Jul 2022 15:14:57 +0200
Subject: [PATCH 34/52] fixing tests

---
 tests/Init/InitBlocksCliTest.php | 24 ++++--------------------
 1 file changed, 4 insertions(+), 20 deletions(-)

diff --git a/tests/Init/InitBlocksCliTest.php b/tests/Init/InitBlocksCliTest.php
index 7295cc02d..a14b2aa72 100644
--- a/tests/Init/InitBlocksCliTest.php
+++ b/tests/Init/InitBlocksCliTest.php
@@ -2,6 +2,7 @@
 
 namespace Tests\Unit\Init;
 
+use EightshiftLibs\Helpers\Components;
 use EightshiftLibs\Init\InitBlocksCli;
 
 use function Tests\setAfterEach;
@@ -23,25 +24,8 @@
 	$mock = $this->mock;
 	$mock([], []);
 
-	// $output = \file_get_contents(Components::getProjectPaths('blocksDestination', "Blocks.php"));
+	$output = \file_get_contents(Components::getProjectPaths('blocksDestination', "Blocks.php"));
 
-	// $this->assertStringContainsString('class Blocks extends AbstractBlocks', $output);
-	// $this->assertStringContainsString('@package EightshiftLibs\Blocks', $output);
-	// $this->assertStringContainsString('namespace EightshiftLibs\Blocks', $output);
-	// $this->assertStringNotContainsString('footer.php', $output);
+	expect($output)
+		->toBeString();
 });
-
-// test('Blocks CLI command will correctly copy the Blocks class with set arguments', function () {
-// 	$mock = $this->mock;
-// 	$mock([], [
-// 		'namespace' => 'CoolTheme',
-// 	]);
-
-// 	$output = \file_get_contents(Components::getProjectPaths('blocksDestination', "Blocks.php"));
-
-// 	$this->assertStringContainsString('namespace CoolTheme\Blocks;', $output);
-// });
-
-// test('Blocks CLI documentation is correct', function () {
-// 	expect($this->mock->getDoc())->toBeArray();
-// });

From 3c11fa6d1d81d0c0bb72632320f2bd93d220d4e7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Thu, 7 Jul 2022 15:16:06 +0200
Subject: [PATCH 35/52] Update src/Blocks/AbstractBlocksCli.php
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Igor Obradović 
---
 src/Blocks/AbstractBlocksCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Blocks/AbstractBlocksCli.php b/src/Blocks/AbstractBlocksCli.php
index a11262762..264eb7252 100644
--- a/src/Blocks/AbstractBlocksCli.php
+++ b/src/Blocks/AbstractBlocksCli.php
@@ -206,7 +206,7 @@ private function outputDependencyItems(string $source, string $type): void
 			$this->cliLog(
 				\sprintf(
 					// translators: %s will be replaced with type of item.
-					\esc_html__("We have found that this %s has dependencies, please run this commands also if you don't have it in your project:", 'eightshift-libs'),
+					\esc_html__("We have found that this %s has dependencies, please run these commands also if you don't have it in your project:", 'eightshift-libs'),
 					$type
 				)
 			);

From 80ca3c2ec03542b51f9aedd5e2b174619e7af7da Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Thu, 7 Jul 2022 15:16:17 +0200
Subject: [PATCH 36/52] Update src/Blocks/AbstractBlocksCli.php
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Igor Obradović 
---
 src/Blocks/AbstractBlocksCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Blocks/AbstractBlocksCli.php b/src/Blocks/AbstractBlocksCli.php
index 264eb7252..4d1d9033c 100644
--- a/src/Blocks/AbstractBlocksCli.php
+++ b/src/Blocks/AbstractBlocksCli.php
@@ -54,7 +54,7 @@ protected function moveItems(array $args, string $source, string $destination, s
 			self::cliError(
 				\sprintf(
 					// translators: %s will be replaced with type of item, and shorten cli path.
-					"%s files doesn't exist on this path: `%s`. Please check if you have eightshift-frontend-libs instaled.",
+					"%s files doesn't exist on this path: `%s`. Please check if you have eightshift-frontend-libs installed.",
 					$type,
 					$this->getShortenCliPathOutput($source)
 				)

From e614b0ecb5061c95c00ce84341eb1c0d565a66d4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Thu, 7 Jul 2022 15:16:27 +0200
Subject: [PATCH 37/52] Update src/Blocks/AbstractBlocksCli.php
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Igor Obradović 
---
 src/Blocks/AbstractBlocksCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Blocks/AbstractBlocksCli.php b/src/Blocks/AbstractBlocksCli.php
index 4d1d9033c..6c0870fe1 100644
--- a/src/Blocks/AbstractBlocksCli.php
+++ b/src/Blocks/AbstractBlocksCli.php
@@ -106,7 +106,7 @@ protected function moveItems(array $args, string $source, string $destination, s
 				self::cliError(
 					\sprintf(
 						// translators: %s will be replaced with type of item, and shorten cli path.
-						"%s files exist on this path: `%s`. If you want to override the destination folder plase use --skip_existing='true' argument.",
+						"%s files exist on this path: `%s`. If you want to override the destination folder please use --skip_existing='true' argument.",
 						$type,
 						$this->getShortenCliPathOutput($fullDestination)
 					)

From f9aa9edbad9502240d559cb943a54acd4a588585 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Thu, 7 Jul 2022 15:16:36 +0200
Subject: [PATCH 38/52] Update src/Blocks/AbstractBlocksCli.php
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Igor Obradović 
---
 src/Blocks/AbstractBlocksCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Blocks/AbstractBlocksCli.php b/src/Blocks/AbstractBlocksCli.php
index 6c0870fe1..7f5d3fe5b 100644
--- a/src/Blocks/AbstractBlocksCli.php
+++ b/src/Blocks/AbstractBlocksCli.php
@@ -86,7 +86,7 @@ protected function moveItems(array $args, string $source, string $destination, s
 				self::cliError(
 					\sprintf(
 						// translators: %s will be replaced with type of item, item name and shorten cli path.
-						"Requested %s with the name `%s` doesn't exist in our library please review you search.\nYou can find all available items on this list: \n\n%s\n\nOr find them on this link: https://infinum.github.io/eightshift-docs/storybook/",
+						"Requested %s with the name `%s` doesn't exist in our library. Please review you search.\nYou can find all available items on this list: \n\n%s\n\nOr find them on this link: https://infinum.github.io/eightshift-docs/storybook/",
 						$type,
 						$item,
 						\implode(\PHP_EOL, $sourceItems)

From 16e97ebf26529192c07bdb645f204e11f477569e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Thu, 7 Jul 2022 15:16:47 +0200
Subject: [PATCH 39/52] Update src/Blocks/AbstractBlocksCli.php
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Igor Obradović 
---
 src/Blocks/AbstractBlocksCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Blocks/AbstractBlocksCli.php b/src/Blocks/AbstractBlocksCli.php
index 7f5d3fe5b..abf575660 100644
--- a/src/Blocks/AbstractBlocksCli.php
+++ b/src/Blocks/AbstractBlocksCli.php
@@ -74,7 +74,7 @@ protected function moveItems(array $args, string $source, string $destination, s
 			self::cliError(
 				\sprintf(
 					// translators: %s will be replaced with type of item, and shorten cli path.
-					"%s files doesn't exist on this path: `%s`. Please check if you have eightshift-frontend-libs instaled.",
+					"%s files doesn't exist on this path: `%s`. Please check if you have eightshift-frontend-libs installed.",
 					$type,
 					$this->getShortenCliPathOutput($source)
 				)

From 3cfc457a8c8b7c05a74a88831ad8d7c415b172a6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Thu, 7 Jul 2022 15:17:34 +0200
Subject: [PATCH 40/52] Update src/Cli/AbstractCli.php
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Igor Obradović 
---
 src/Cli/AbstractCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Cli/AbstractCli.php b/src/Cli/AbstractCli.php
index af4faadd3..6fe7860d5 100644
--- a/src/Cli/AbstractCli.php
+++ b/src/Cli/AbstractCli.php
@@ -338,7 +338,7 @@ public function outputWrite(string $destination, string $fileName, array $args =
 		if (\file_exists($destinationFile) && $skipExisting === false) {
 			self::cliError(
 				\sprintf(
-					"%s file `%s` exist on this path: `%s`. If you want to override the destination folder plase use --skip_existing='true' argument.",
+					"%s file `%s` exist on this path: `%s`. If you want to override the destination folder please use --skip_existing='true' argument.",
 					$typeOutput,
 					$fileName,
 					$this->getShortenCliPathOutput($destinationFile)

From 731c03022f771c722d94d7171b454ce3622e1c81 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Thu, 7 Jul 2022 15:17:54 +0200
Subject: [PATCH 41/52] Update src/Cli/README.md
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Igor Obradović 
---
 src/Cli/README.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Cli/README.md b/src/Cli/README.md
index adacf83e9..93cca8b20 100644
--- a/src/Cli/README.md
+++ b/src/Cli/README.md
@@ -3,7 +3,7 @@
 We created an WP-CLI commands for all the features of the Eightshift-Libs.
 
 ## Develop
-You can run this commands by mocking them in the tests.
+You can run these commands by mocking them in the tests.
 
 ## Boilerplate
 You can run this command to show all available commands in WordPress env:

From 2e3ec0c6945fc7c91a91acd8d7193e6430970e43 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Thu, 7 Jul 2022 15:18:04 +0200
Subject: [PATCH 42/52] Update src/Init/InitBlocksCli.php
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Igor Obradović 
---
 src/Init/InitBlocksCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Init/InitBlocksCli.php b/src/Init/InitBlocksCli.php
index 5d4313557..c65facb62 100644
--- a/src/Init/InitBlocksCli.php
+++ b/src/Init/InitBlocksCli.php
@@ -134,7 +134,7 @@ public function getDoc(): array
 				],
 			],
 			'longdesc' => $this->prepareLongDesc("
-				This command will copy all initial block, components, manifests and service classes to you project in order to start using block editor.
+				This command will copy all initial blocks, components, manifests and service classes to you project in order to start using block editor.
 
 				## EXAMPLES
 				$ wp {$this->commandParentName} create blocks_init

From 30150ffa8b32c48c1fcca0c2ad94b240dbabd4fd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Thu, 7 Jul 2022 15:18:17 +0200
Subject: [PATCH 43/52] Update src/Init/InitBlocksCli.php
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Igor Obradović 
---
 src/Init/InitBlocksCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Init/InitBlocksCli.php b/src/Init/InitBlocksCli.php
index c65facb62..c096537e7 100644
--- a/src/Init/InitBlocksCli.php
+++ b/src/Init/InitBlocksCli.php
@@ -190,7 +190,7 @@ public function __invoke(array $args, array $assocArgs)
 	/**
 	 * Init block by providing list of commands.
 	 *
-	 * @param array $assocArgs List of argument for options.
+	 * @param array $assocArgs List of arguments for options.
 	 * @param array $commands Commands to use.
 	 *
 	 * @return void

From a7608cfd2b6936882ebd857e4a5474893c141ab7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Thu, 7 Jul 2022 15:18:29 +0200
Subject: [PATCH 44/52] Update src/Blocks/UseBlockCli.php
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Igor Obradović 
---
 src/Blocks/UseBlockCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Blocks/UseBlockCli.php b/src/Blocks/UseBlockCli.php
index 14b4bc409..c9b9da7cd 100644
--- a/src/Blocks/UseBlockCli.php
+++ b/src/Blocks/UseBlockCli.php
@@ -78,7 +78,7 @@ public function getDoc(): array
 				# Copy block by name:
 				$ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --name='paragraph'
 
-				# Copy multiple block by name:
+				# Copy multiple blocks by name:
 				$ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --name='paragraph, heading'
 
 				## RESOURCES

From 4a4618cf1afc3c59968479f781c51c691fb68f2e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Thu, 7 Jul 2022 15:18:42 +0200
Subject: [PATCH 45/52] Update src/Blocks/UseComponentCli.php
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Igor Obradović 
---
 src/Blocks/UseComponentCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Blocks/UseComponentCli.php b/src/Blocks/UseComponentCli.php
index ef062a476..85fca63dc 100644
--- a/src/Blocks/UseComponentCli.php
+++ b/src/Blocks/UseComponentCli.php
@@ -85,7 +85,7 @@ public function getDoc(): array
 				# Copy component by name:
 				$ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --name='paragraph'
 
-				# Copy multiple component by name:
+				# Copy multiple components by name:
 				$ wp {$this->commandParentName} {$this->getCommandParentName()} {$this->getCommandName()} --name='paragraph, heading'
 
 				## RESOURCES

From 3efe570fe8fca87b967f8664c62fa2911b22de48 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Fri, 8 Jul 2022 08:50:07 +0200
Subject: [PATCH 46/52] Update src/Blocks/AbstractBlocksCli.php

Co-authored-by: Davorin Prislin <81157133+dadadavorin@users.noreply.github.com>
---
 src/Blocks/AbstractBlocksCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Blocks/AbstractBlocksCli.php b/src/Blocks/AbstractBlocksCli.php
index abf575660..788f3a9ba 100644
--- a/src/Blocks/AbstractBlocksCli.php
+++ b/src/Blocks/AbstractBlocksCli.php
@@ -123,7 +123,7 @@ protected function moveItems(array $args, string $source, string $destination, s
 			$partialsOutput = [];
 			$partialsPath = Components::joinPaths([$fullDestination, 'partials']);
 
-			// Check if we have partials folder. If so output and that folder with items in it.
+			// Check if we have partials folder. If so output that folder with items in it.
 			if (\is_dir($partialsPath)) {
 				$partials = \array_diff(\scandir($partialsPath), ['..', '.']);
 				$partials = \array_values($partials);

From 38f8b3c2478446dec1d048fb67c8a429fd5a3dbf Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Fri, 8 Jul 2022 08:50:55 +0200
Subject: [PATCH 47/52] Update src/Blocks/UseAssetsCli.php

Co-authored-by: Davorin Prislin <81157133+dadadavorin@users.noreply.github.com>
---
 src/Blocks/UseAssetsCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Blocks/UseAssetsCli.php b/src/Blocks/UseAssetsCli.php
index a0853dd59..0130193e4 100644
--- a/src/Blocks/UseAssetsCli.php
+++ b/src/Blocks/UseAssetsCli.php
@@ -1,7 +1,7 @@
 
Date: Fri, 8 Jul 2022 08:51:23 +0200
Subject: [PATCH 48/52] Update src/Init/InitBlocksCli.php

Co-authored-by: Mario Borna Mjertan 
---
 src/Init/InitBlocksCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Init/InitBlocksCli.php b/src/Init/InitBlocksCli.php
index c096537e7..3477048fa 100644
--- a/src/Init/InitBlocksCli.php
+++ b/src/Init/InitBlocksCli.php
@@ -152,7 +152,7 @@ public function __invoke(array $args, array $assocArgs)
 			$this->getIntroText();
 		}
 
-		$this->cliLog(\esc_html__('Setting block editor files:', 'eightshift-libs'), 'C');
+		$this->cliLog(\esc_html__('Creating block editor files:', 'eightshift-libs'), 'C');
 
 		$commands = static::COMMANDS;
 

From 896e1bcb656a0e8239cc5447254a4ffd82ce8e4c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Fri, 8 Jul 2022 08:52:11 +0200
Subject: [PATCH 49/52] Update src/Blocks/BlocksCli.php

Co-authored-by: Mario Borna Mjertan 
---
 src/Blocks/BlocksCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Blocks/BlocksCli.php b/src/Blocks/BlocksCli.php
index 4c482bad7..860d0bd67 100644
--- a/src/Blocks/BlocksCli.php
+++ b/src/Blocks/BlocksCli.php
@@ -52,7 +52,7 @@ public function getDoc(): array
 				## USAGE
 
 				This file is a main entrypoint for all our block editor setup.
-				We use it to register all blocks, limit what blocks user can see, and lots more.
+				It's used to register blocks, define which blocks are allowed, and more.
 
 				## EXAMPLES
 

From fd7a2ae636a6034fed6f931dad933d4c7e785fb1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Fri, 8 Jul 2022 08:52:36 +0200
Subject: [PATCH 50/52] Update src/Blocks/UseComponentCli.php

Co-authored-by: Mario Borna Mjertan 
---
 src/Blocks/UseComponentCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/Blocks/UseComponentCli.php b/src/Blocks/UseComponentCli.php
index 85fca63dc..5630fa783 100644
--- a/src/Blocks/UseComponentCli.php
+++ b/src/Blocks/UseComponentCli.php
@@ -71,7 +71,7 @@ public function getDoc(): array
 				[
 					'type' => 'assoc',
 					'name' => 'name',
-					'description' => 'Specify component name. You can specify multiple components (separate them with comma).',
+					'description' => 'Specify component name. You can specify multiple components by separating them with a comma.',
 					'optional' => false,
 				],
 			],

From 0e8efffec941ac5cb251773adf24536b2efda45d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Fri, 8 Jul 2022 08:53:32 +0200
Subject: [PATCH 51/52] Update src/CustomPostType/PostTypeCli.php

Co-authored-by: Mario Borna Mjertan 
---
 src/CustomPostType/PostTypeCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/CustomPostType/PostTypeCli.php b/src/CustomPostType/PostTypeCli.php
index 036647732..f6d22c3c8 100644
--- a/src/CustomPostType/PostTypeCli.php
+++ b/src/CustomPostType/PostTypeCli.php
@@ -77,7 +77,7 @@ public function getDoc(): array
 				[
 					'type' => 'assoc',
 					'name' => 'plural_label',
-					'description' => 'The plural label of the custom post type. Used for label generation. If not specified the plural will have appended s at the end of the label.', // phpcs:ignore Generic.Files.LineLength.TooLong
+					'description' => 'The plural label for the custom post type. Used for label generation. If not specified, the plural will be an "s" appended to the singular label.', // phpcs:ignore Generic.Files.LineLength.TooLong
 					'optional' => false,
 					'default' => $this->getDefaultArg('plural_label'),
 				],

From 134bff5af352652a6eff2e7f38efdbd25472ecec Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ivan=20Ru=C5=BEevi=C4=87?= 
Date: Fri, 8 Jul 2022 08:53:53 +0200
Subject: [PATCH 52/52] Update src/CustomTaxonomy/TaxonomyCli.php

Co-authored-by: Mario Borna Mjertan 
---
 src/CustomTaxonomy/TaxonomyCli.php | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/CustomTaxonomy/TaxonomyCli.php b/src/CustomTaxonomy/TaxonomyCli.php
index bc101551a..0fa378698 100644
--- a/src/CustomTaxonomy/TaxonomyCli.php
+++ b/src/CustomTaxonomy/TaxonomyCli.php
@@ -74,7 +74,7 @@ public function getDoc(): array
 				[
 					'type' => 'assoc',
 					'name' => 'plural_label',
-					'description' => 'The label of the custom taxonomy to show in WP admin but as a plural version.',
+					'description' => 'The plural form of the custom taxonomy label.',
 					'optional' => false,
 				],
 				[