diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index 0688d67..5cd87b3 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -18,10 +18,11 @@ jobs: - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v5 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 @@ -35,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v3 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -48,6 +49,6 @@ jobs: run: vendor/bin/phpunit --colors=always --coverage-clover clover.xml - name: Send code coverage report to Codecov.io - uses: codecov/codecov-action@v5 + uses: codecov/codecov-action@v7 with: token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 63e06de..b428224 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -4,7 +4,7 @@ on: name: Run PHPStan checks jobs: - mutation: + static-analysis: name: PHPStan ${{ matrix.php }}-${{ matrix.os }} runs-on: ${{ matrix.os }} @@ -18,16 +18,17 @@ jobs: - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 with: php-version: "${{ matrix.php }}" - coverage: pcov + coverage: none ini-values: assert.exception=1, zend.assertions=1, error_reporting=-1, log_errors_max_len=0, display_errors=On tools: composer:v2, cs2pr @@ -35,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} diff --git a/.gitignore b/.gitignore index 9074559..7d2d6e4 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ composer.lock .phpunit.result.cache .phpcs-cache +.phpunit.cache diff --git a/.laminas-ci.json b/.laminas-ci.json index 29216fa..e827682 100644 --- a/.laminas-ci.json +++ b/.laminas-ci.json @@ -1,3 +1,6 @@ { + "ignore_php_platform_requirements": { + "8.6": true + }, "backwardCompatibilityCheck": true } diff --git a/CHANGELOG.md b/CHANGELOG.md index e69de29..b346f86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -0,0 +1,290 @@ +# Changelog + +All notable changes to this project are documented in this file, newest first. + +## 3.0.0 - TBD + +### Added + +- PHP 8.6 support. +- "Next steps" are printed after `make command`, `make middleware` and `make entity`, not only after `make module`, and every message is kept when several components are created in one run. +- `Input::isExhausted()` to detect the end of input. +- `.gitattributes`, so the Composer package no longer ships tests, docs and tooling files. +- Upgrade guide in the documentation. + +### Changed + +- PHPUnit 12 and PHPStan level 8. +- Names must start with a letter and must not be PHP reserved words, with or without the component suffix. +- A name that is only the component suffix (for example `Entity`) is kept as the class name. +- `bin/dot-maker` exits with code 1 when the command fails. +- `make form` in an API project fails before asking for a module. +- Generated arrays are aligned to the Laminas Coding Standard. +- Generated `GetEdit...FormHandler` and `GetDelete...FormHandler` pass the entity to the template under its camelCase name, like the POST handlers. +- `Context::getRootNamespace()` and `Context::getProjectType()` return `string`, and `Context` requires a non-Core namespace under `autoload.psr-4`. +- `FileInterface::create()` returns `File` instead of `?File`. +- `Module::getMessages()` returns the messages grouped by priority. + +### Deprecated + +- Nothing. + +### Removed + +- `Entity::getNumericIdentifierTraitFqcn()` and `FileSystem::coreModule()`, which nothing called. + +### Fixed + +- Infinite loop when the input ends at the "Existing module name" prompt. +- Wrong console name for Commands whose name contains "Command" before the end. +- Generated files that failed `php -l` for names starting with a digit or matching a PHP reserved word. +- Empty class name (`.php` file) when the name was only the component suffix. +- `TypeError` for an invalid `composer.json` or `config/autoload/maker.local.php`. +- `File::create('')` reported a failure after writing the file. +- `TypeError` when writing to a closed output stream. + +### Security + +- Nothing. + +## 2.1.0 - 2026-10-13 + +### Added + +- `operationId` in generated OpenAPI operations (#46). + +### Changed + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- PHP 8.2 support (#47). + +### Fixed + +- Nothing. + +### Security + +- Nothing. + +## 2.0.0 - 2025-12-15 + +### Added + +- Nothing. + +### Changed + +- Generated code adapted for Headless Platform 7 (#44, #45). + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Nothing. + +### Security + +- Nothing. + +## 1.1.0 - 2025-10-29 + +### Added + +- PHP 8.4 and 8.5 support (#42). + +### Changed + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- PHP 8.1 support (#42). + +### Fixed + +- Invalid array type assignations reported by PHPStan (#40). + +### Security + +- Nothing. + +## 1.0.5 - 2025-09-25 + +### Added + +- Link to the tutorial video in the documentation (#38). + +### Changed + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Nothing. + +### Security + +- Nothing. + +## 1.0.4 - 2025-09-10 + +### Added + +- Nothing. + +### Changed + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Installation instructions in the documentation (#36). + +### Security + +- Nothing. + +## 1.0.3 - 2025-09-09 + +### Added + +- Nothing. + +### Changed + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Package installation command (#34). + +### Security + +- Nothing. + +## 1.0.2 - 2025-09-02 + +### Added + +- Nothing. + +### Changed + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Resources in routes must be singular (#19). +- InputFilters initialised via `init` in Admin and via the constructor in API (#21). +- Form factory used in ConfigProvider (#23). +- Handler naming pattern for non-API projects (#25). +- Invalid `CsrfInput` name in non-API InputFilters (#27). +- Template naming pattern (#28). +- Route name used in Form action attributes (#29). + +### Security + +- Nothing. + +## 1.0.1 - 2025-08-22 + +### Added + +- Nothing. + +### Changed + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Collection path generated in RoutesDelegator (#8). +- Invalid property initialisations (#10). +- `(Core)ConfigProvider` and Middleware related messages after `make module` (#12). + +### Security + +- Nothing. + +## 1.0.0 - 2025-08-21 + +### Added + +- Initial release. + +### Changed + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Nothing. + +### Security + +- Nothing. diff --git a/README.md b/README.md index c51faba..d41c531 100644 --- a/README.md +++ b/README.md @@ -9,16 +9,16 @@ Documentation is available at: https://docs.dotkernel.org/dot-maker/. ## Badges ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-maker) -![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-maker/2.1.0) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-maker/3.0.0) [![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-maker)](https://github.com/dotkernel/dot-maker/issues) [![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-maker)](https://github.com/dotkernel/dot-maker/network) [![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-maker)](https://github.com/dotkernel/dot-maker/stargazers) -[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-maker)](https://github.com/dotkernel/dot-maker/blob/2.0/LICENSE) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-maker)](https://github.com/dotkernel/dot-maker/blob/3.0/LICENSE) -[![Build Static](https://github.com/dotkernel/dot-maker/actions/workflows/continuous-integration.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-maker/actions/workflows/continuous-integration.yml) +[![Build Static](https://github.com/dotkernel/dot-maker/actions/workflows/continuous-integration.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-maker/actions/workflows/continuous-integration.yml) [![codecov](https://codecov.io/gh/dotkernel/dot-maker/graph/badge.svg?token=KT9UA402B4)](https://codecov.io/gh/dotkernel/dot-maker) -[![PHPStan](https://github.com/dotkernel/dot-maker/actions/workflows/static-analysis.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-maker/actions/workflows/static-analysis.yml) +[![PHPStan](https://github.com/dotkernel/dot-maker/actions/workflows/static-analysis.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-maker/actions/workflows/static-analysis.yml) ## Installation diff --git a/SECURITY.md b/SECURITY.md index 3188de0..cd1401b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,7 +4,8 @@ | Version | Supported | PHP Version | |---------|--------------------|-----------------------------------------------------------------------------------------------------------| -| 2.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-maker/2.0.0) | +| 3.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-maker/3.0.0) | +| 2.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-maker/2.1.0) | | 1.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-maker/1.1.0) | ## Reporting Potential Security Issues diff --git a/bin/dot-maker b/bin/dot-maker index f8bc8ec..9de10d5 100755 --- a/bin/dot-maker +++ b/bin/dot-maker @@ -13,4 +13,10 @@ if (file_exists($autoload)) { exit(1); } -(new Maker(getcwd()))($argv); +$cwd = getcwd(); +if ($cwd === false) { + fwrite(STDERR, 'Cannot determine the current working directory' . PHP_EOL); + exit(1); +} + +exit((new Maker($cwd))($argv)); diff --git a/composer.json b/composer.json index 7250728..d4d0022 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,7 @@ } }, "require": { - "php": "~8.3.0 || ~8.4.0 || ~8.5.0" + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0" }, "require-dev": { "boundwize/structarmed": "^0.19", @@ -36,7 +36,7 @@ "mikey179/vfsstream": "^1.6.12", "phpstan/phpstan": "^2.1.33", "phpstan/phpstan-phpunit": "^2.0.10", - "phpunit/phpunit": "^10.5.60" + "phpunit/phpunit": "^12.5" }, "scripts": { "check": [ diff --git a/docs/book/v3/component/collection.md b/docs/book/v3/component/collection.md new file mode 100644 index 0000000..0b40fbc --- /dev/null +++ b/docs/book/v3/component/collection.md @@ -0,0 +1,67 @@ +# Create Collection + +> This page assumes that you have created a Composer "make" script as described on the [Setup page](../setup.md#add-dot-maker-to-composerjson). + +> Collections can be created only in APIs. + +## Run the command + +To create a Collection, use either of the following commands: + +```shell +composer make collection +``` + +OR + +```shell +./vendor/bin/dot-maker collection +``` + +## Identify the target module + +`dot-maker` needs to know in which module you want to create the new Collection. +To determine this, it will prompt you to enter the name of an existing module: + +> Existing module name: + +If you input a module name which does not exist (like, "NonExistentModule"), an error will be thrown: + +> Module "NonExistentModule" not found + +and will keep prompting for a valid module name until you provide one. + +Once an existing module name (like, "ExistingModule") is provided, `dot-maker` will output a success message: + +> Found Module "ExistingModule" + +## Name the Collection + +Once the target module has been identified, you will be prompted to input a name for the Collection: + +> Collection name: + +**The name must start with a letter, contain only letters and numbers, and must not be a PHP reserved word (for example `List`, `Class` or `Int`), with or without the component suffix.** + +> You don't have to append "Collection" to the name. +> It is automatically appended when necessary. +> See our [Naming Standards](../naming-standards.md) page for more information. + +If you leave the name blank, the process will exit. + +If you input an invalid name (like, "."), an error will be thrown: + +> Invalid Collection name: "." + +If you input the name of an existing Collection (like, "ExistingCollection"), an error will be thrown: + +> Class "ExistingCollection" already exists at /path/to/project/src/ExistingModule/src/Collection/ExistingCollection.php + +If you input a valid name (like, "NewCollection"), `dot-maker` will create the Collection and output a success message: + +> Created Collection: /path/to/project/src/ExistingModule/src/Collection/NewCollection.php + +## Create multiple Collections + +To allow the creation of multiple Collections, the process will loop until you leave the name blank. +Each iteration creates a new Collection under the same module. diff --git a/docs/book/v3/component/command.md b/docs/book/v3/component/command.md new file mode 100644 index 0000000..2be3785 --- /dev/null +++ b/docs/book/v3/component/command.md @@ -0,0 +1,91 @@ +# Create Command + +> This page assumes that you have created a Composer "make" script as described on the [Setup page](../setup.md#add-dot-maker-to-composerjson). + +> `dot-maker` will look for a matching ServiceInterface in the module (e.g.: BookServiceInterface — BookCommand). +> If it finds one, it will automatically inject it into the Command. + +To create a Command, use either of the following commands: + +## Run the command + +```shell +composer make command +``` + +OR + +```shell +./vendor/bin/dot-maker command +``` + +## Identify the target module + +`dot-maker` needs to know in which module you want to create the new Command. +To determine this, it will prompt you to enter the name of an existing module: + +> Existing module name: + +If you input a module name which does not exist (like, "NonExistentModule"), an error will be thrown: + +> Module "NonExistentModule" not found + +and will keep prompting for a valid module name until you provide one. + +Once an existing module name (like, "ExistingModule") is provided, `dot-maker` will output a success message: + +> Found Module "ExistingModule" + +## Name the Command + +Once the target module has been identified, you will be prompted to input a name for the Command: + +> Command name: + +**The name must start with a letter, contain only letters and numbers, and must not be a PHP reserved word (for example `List`, `Class` or `Int`), with or without the component suffix.** + +> You don't have to append "Command" to the name. +> It is automatically appended when necessary. +> See our [Naming Standards](../naming-standards.md) page for more information. + +If you leave the name blank, the process will exit. + +If you input an invalid name (like, "."), an error will be thrown: + +> Invalid Command name: "." + +If you input the name of an existing Command (like, "ExistingCommand"), an error will be thrown: + +> Class "ExistingCommand" already exists at /path/to/project/src/ExistingModule/src/Command/ExistingCommand.php + +If you input a valid name (like, "NewCommand"), `dot-maker` will create the Command and output a success message: + +> Created Command: /path/to/project/src/ExistingModule/src/Command/NewCommand.php + +## Create multiple Commands + +To allow the creation of multiple Commands, the process will loop until you leave the name blank. +Each iteration creates a new Command under the same module. + +## Command name + +The console name of the Command is built from its class name: the class name is converted to kebab-case, a trailing `-command` is removed and `:command` is appended. + +| You input | Class | Console name | +| --- | --- | --- | +| `BookStore` | `BookStoreCommand` | `book-store:command` | +| `ImportCommands` | `ImportCommandsCommand` | `import-commands:command` | +| `MyCommandHandler` | `MyCommandHandlerCommand` | `my-command-handler:command` | + +## Next steps + +Once the Command is created, `dot-maker` will display the tasks that need to be performed manually, for example: + +```text +Next steps: +=========== +- add to config/autoload/cli.global.php under dot_cli.commands: + \ExistingModule\Command\NewCommand::getDefaultName() => \ExistingModule\Command\NewCommand::class, +``` + +When you create more than one Command in the same run, each one is listed. diff --git a/docs/book/v3/component/entity.md b/docs/book/v3/component/entity.md new file mode 100644 index 0000000..e5bb91d --- /dev/null +++ b/docs/book/v3/component/entity.md @@ -0,0 +1,93 @@ +# Create Entity + +> This page assumes that you have created a Composer "make" script as described on the [Setup page](../setup.md#add-dot-maker-to-composerjson). + +## Run the command + +To create an Entity, use either of the following commands: + +```shell +composer make entity +``` + +OR + +```shell +./vendor/bin/dot-maker entity +``` + +## Identify the target module + +`dot-maker` needs to know in which module you want to create the new Entity. +To determine this, it will prompt you to enter the name of an existing module: + +> Existing module name: + +If you input a module name which does not exist (like, "NonExistentModule"), an error will be thrown: + +> Module "NonExistentModule" not found + +and will keep prompting for a valid module name until you provide one. + +Once an existing module name (like, "ExistingModule") is provided, `dot-maker` will output a success message: + +> Found Module "ExistingModule" + +## Name the Entity + +Once the target module has been identified, you will be prompted to input a name for the Entity: + +> Entity name: + +**The name must start with a letter, contain only letters and numbers, and must not be a PHP reserved word (for example `List`, `Class` or `Int`), with or without the component suffix.** + +> You don't have to append "Entity" to the name. +> It is automatically appended when necessary. +> See our [Naming Standards](../naming-standards.md) page for more information. + +If you leave the name blank, the process will exit. + +If you input an invalid name (like, "."), an error will be thrown: + +> Invalid Entity name: "." + +If you input the name of an existing Entity (like, "Existing"), an error will be thrown: + +- for projects compatible with the Core architecture: + +> Class "Existing" already exists at /path/to/project/src/Core/src/ExistingModule/src/Entity/Existing.php + +- for projects which are NOT compatible with the Core architecture: + +> Class "Existing" already exists at /path/to/project/src/ExistingModule/src/Entity/Existing.php + +If you input a valid name (like, "Book"), `dot-maker` will create the Entity and output a success message. +The Entity class is named without a suffix, so "BookEntity" also creates `Book.php`: + +- for projects compatible with the Core architecture: + +> Created Entity: /path/to/project/src/Core/src/ExistingModule/src/Entity/Book.php +> Created Repository: /path/to/project/src/Core/src/ExistingModule/src/Repository/BookRepository.php + +- for projects which are NOT compatible with the Core architecture: + +> Created Entity: /path/to/project/src/ExistingModule/src/Entity/Book.php +> Created Repository: /path/to/project/src/ExistingModule/src/Repository/BookRepository.php + +## Create multiple Entities + +To allow the creation of multiple Entities, the process will loop until you leave the name blank. +Each iteration creates a new pair of Entity and Repository under the same module. + +## Next steps + +Once the Entity is created, `dot-maker` will display the tasks that need to be performed manually, for example: + +```text +Next steps: +=========== +- generate Doctrine migration: + php ./vendor/bin/doctrine-migrations diff +``` + +When you create more than one Entity in the same run, each one is listed. diff --git a/docs/book/v3/component/form.md b/docs/book/v3/component/form.md new file mode 100644 index 0000000..b81ce2d --- /dev/null +++ b/docs/book/v3/component/form.md @@ -0,0 +1,106 @@ +# Create Form + +> This page assumes that you have created a Composer "make" script as described on the [Setup page](../setup.md#add-dot-maker-to-composerjson). + +> Forms cannot be created in APIs. +> In an API project, `dot-maker form` stops before asking for a module, prints `Cannot create Forms in an API` and exits with code 1. + +To create a Form, use either of the following commands: + +## Run the command + +```shell +composer make form +``` + +OR + +```shell +./vendor/bin/dot-maker form +``` + +## Identify the target module + +`dot-maker` needs to know in which module you want to create the new Form. +To determine this, it will prompt you to enter the name of an existing module: + +> Existing module name: + +If you input a module name which does not exist (like, "NonExistentModule"), an error will be thrown: + +> Module "NonExistentModule" not found + +and will keep prompting for a valid module name until you provide one. + +Once an existing module name (like, "ExistingModule") is provided, `dot-maker` will output a success message: + +> Found Module "ExistingModule" + +## Name the Form + +Once the target module has been identified, you will be prompted to input a name for the Form: + +> Form name: + +**The name must start with a letter, contain only letters and numbers, and must not be a PHP reserved word (for example `List`, `Class` or `Int`), with or without the component suffix.** + +> You don't have to append "Form" to the name. +> It is automatically appended when necessary. +> See our [Naming Standards](../naming-standards.md) page for more information. + +If you leave the name blank, the process will exit. + +If you input an invalid name (like, "."), an error will be thrown: + +> Invalid Form name: "." + +If you input the name of an existing Form (like, "ExistingForm"), an error will be thrown: + +> Class "ExistingForm" already exists at /path/to/project/src/ExistingModule/src/Form/ExistingForm.php + +Once you input a valid name (like, "Book"), `dot-maker` will prompt you to confirm which CRUD operations will be performed on the resource: + +### Create resources + +The prompt asks you whether you want to create resources: + +> Allow creating Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src/ExistingModule/src/Form/CreateBookForm.php` +- `src/ExistingModule/src/InputFilter/CreateBookInputFilter.php` + +Without confirmation, the process will skip to the next component. + +### Delete resources + +The prompt asks you whether you want to delete resources: + +> Allow deleting Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src/ExistingModule/src/Form/DeleteBookForm.php` +- `src/ExistingModule/src/InputFilter/DeleteBookInputFilter.php` +- `src/ExistingModule/src/InputFilter/Input/ConfirmDeleteBookInput.php` + +Without confirmation, the process will skip to the next component. + +### Edit resources + +The prompt asks you whether you want to edit resources: + +> Allow editing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src/ExistingModule/src/Form/EditBookForm.php` +- `src/ExistingModule/src/InputFilter/EditBookInputFilter.php` + +Without confirmation, the process will skip to the next component. + +## Create multiple Forms + +To allow the creation of multiple Forms, the process will loop until you leave the name blank. +Each iteration creates a new set of Forms, InputFilter and Inputs under the same module. diff --git a/docs/book/v3/component/handler.md b/docs/book/v3/component/handler.md new file mode 100644 index 0000000..d7f120d --- /dev/null +++ b/docs/book/v3/component/handler.md @@ -0,0 +1,243 @@ +# Create Handler + +> This page assumes that you have created a Composer "make" script as described on the [Setup page](../setup.md#add-dot-maker-to-composerjson). + +> `dot-maker` will look for a matching ServiceInterface in the module (e.g.: BookServiceInterface — BookHandler). +> If it finds one, it will automatically inject it into the Handler. + +To create a Handler, use either of the following commands: + +## Run the command + +```shell +composer make handler +``` + +OR + +```shell +./vendor/bin/dot-maker handler +``` + +## Identify the target module + +`dot-maker` needs to know in which module you want to create the new Handler. +To determine this, it will prompt you to enter the name of an existing module: + +> Existing module name: + +If you input a module name which does not exist (like, "NonExistentModule"), an error will be thrown: + +> Module "NonExistentModule" not found + +and will keep prompting for a valid module name until you provide one. + +Once an existing module name (like, "ExistingModule") is provided, `dot-maker` will output a success message: + +> Found Module "ExistingModule" + +## Name the Handler + +Once the target module has been identified, you will be prompted to input a name for the Handler: + +> Handler name: + +**The name must start with a letter, contain only letters and numbers, and must not be a PHP reserved word (for example `List`, `Class` or `Int`), with or without the component suffix.** + +> You don't have to append "Handler" to the name. +> It is automatically appended when necessary. +> See our [Naming Standards](../naming-standards.md) page for more information. + +If you leave the name blank, the process will exit. + +If you input an invalid name (like, "."), an error will be thrown: + +> Invalid Handler name: "." + +If you input the name of an existing Handler (like, "ExistingHandler"), an error will be thrown: + +> Class "ExistingHandler" already exists at /path/to/project/src/ExistingModule/src/Handler/ExistingHandler.php + +Once you input a valid name (like, "Book"), the process will iterate over a list of CRUD operations, asking you to confirm whether the Module needs a request Handler for each operation. + +### API projects + +#### List resources + +The prompt asks you whether you want to list resources: + +> Allow listing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src/ExistingModule/src/Collection/BookCollection.php`: describes a resource-specific collection +- `src/ExistingModule/src/Handler/Book/GetBookCollectionHandler.php`: handles the resource collection representation + +The matching Collection and ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +#### View resources + +The prompt asks you whether you want to view resources: + +> Allow viewing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following file: + +- `src/ExistingModule/src/Handler/Book/GetBookResourceHandler.php`: handles the resource representation + +The matching ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +#### Create resources + +The prompt asks you whether you want to create resources: + +> Allow creating Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src/ExistingModule/src/Handler/Book/PostBookResourceHandler.php`: handles the resource creation +- `src/ExistingModule/src/InputFilter/CreateBookInputFilter.php`: request payload validators + +The matching InputFilter and ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +#### Delete resources + +The prompt asks you whether you want to delete resources: + +> Allow deleting Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src/ExistingModule/src/Handler/Book/DeleteBookResourceHandler.php`: handles the resource deletion + +The matching ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +#### Edit resources + +The prompt asks you whether you want to edit resources: + +> Allow editing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src/ExistingModule/src/Handler/Book/PatchBookResourceHandler.php`: handles the resource update +- `src/ExistingModule/src/InputFilter/EditBookInputFilter.php`: request payload validators + +The matching InputFilter and ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +#### Replace resources + +The prompt asks you whether you want to replace resources: + +> Allow replacing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src/ExistingModule/src/Handler/Book/PutBookResourceHandler.php`: handles the resource replacement +- `src/ExistingModule/src/InputFilter/ReplaceBookInputFilter.php`: request payload validators + +The matching InputFilter and ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +### Non-API projects + +#### List resources + +The prompt asks you whether you want to list resources: + +> Allow listing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src/ExistingModule/src/Handler/Book/GetBookListHandler.php`: renders the resource list page +- `src/ExistingModule/templates/existing-module/book-list.html.twig`: renders the resource list + +The matching ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +#### View resources + +The prompt asks you whether you want to view resources: + +> Allow viewing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src/ExistingModule/src/Handler/Book/GetBookViewHandler.php`: renders the resource page +- `src/ExistingModule/templates/existing-module/book-view.html.twig`: renders the resource + +The matching ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +#### Create resources + +The prompt asks you whether you want to create resources: + +> Allow creating Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src/ExistingModule/src/Handler/Book/GetBookCreateFormHandler.php`: renders the resource creation form page +- `src/ExistingModule/src/Handler/Book/PostBookCreateHandler.php`: handles the resource creation +- `src/ExistingModule/src/Form/CreateBookForm.php`: form fields +- `src/ExistingModule/src/InputFilter/CreateBookInputFilter.php`: form field validators +- `src/ExistingModule/templates/existing-module/book-view.html.twig`: renders the resource creation form + +The matching Form and ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +#### Delete resources + +The prompt asks you whether you want to delete resources: + +> Allow deleting Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src/ExistingModule/src/Handler/Book/GetBookDeleteFormHandler.php`: renders the resource deletion form page +- `src/ExistingModule/src/Handler/Book/PostBookDeleteHandler.php`: handles the resource deletion +- `src/ExistingModule/src/Form/DeleteBookForm.php`: form fields +- `src/ExistingModule/src/InputFilter/DeleteBookInputFilter.php`: form field validators +- `src/ExistingModule/src/InputFilter/Input/ConfirmDeleteBookInput.php`: checkbox input for deletion confirmation +- `src/ExistingModule/templates/existing-module/book-delete-form.html.twig`: renders the resource deletion form + +The matching ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +#### Edit resources + +The prompt asks you whether you want to edit resources: + +> Allow editing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src/ExistingModule/src/Handler/Book/GetBookEditFormHandler.php`: renders the resource edit form page +- `src/ExistingModule/src/Handler/Book/PostBookEditHandler.php`: handles the resource update +- `src/ExistingModule/src/Form/EditBookForm.php`: form fields +- `src/ExistingModule/src/InputFilter/EditBookInputFilter.php`: form field validators +- `src/ExistingModule/templates/existing-module/book-edit-form.html.twig`: renders the resource creation form + +The matching InputFilter and ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +## Create multiple Handlers + +To allow the creation of multiple Handlers, the process will loop until you leave the name blank. +Each iteration creates a new set of Handlers(, Forms), InputFilters and Inputs under the same module. diff --git a/docs/book/v3/component/input-filter.md b/docs/book/v3/component/input-filter.md new file mode 100644 index 0000000..fc164ab --- /dev/null +++ b/docs/book/v3/component/input-filter.md @@ -0,0 +1,113 @@ +# Create InputFilter + +> This page assumes that you have created a Composer "make" script as described on the [Setup page](../setup.md#add-dot-maker-to-composerjson). + +To create an InputFilter, use either of the following commands: + +## Run the command + +```shell +composer make input-filter +``` + +OR + +```shell +./vendor/bin/dot-maker input-filter +``` + +## Identify the target module + +`dot-maker` needs to know in which module you want to create the new InputFilter. +To determine this, it will prompt you to enter the name of an existing module: + +> Existing module name: + +If you input a module name which does not exist (like, "NonExistentModule"), an error will be thrown: + +> Module "NonExistentModule" not found + +and will keep prompting for a valid module name until you provide one. + +Once an existing module name (like, "ExistingModule") is provided, `dot-maker` will output a success message: + +> Found Module "ExistingModule" + +## Name the InputFilter + +Once the target module has been identified, you will be prompted to input a name for the InputFilter: + +> InputFilter name: + +**The name must start with a letter, contain only letters and numbers, and must not be a PHP reserved word (for example `List`, `Class` or `Int`), with or without the component suffix.** + +> You don't have to append "InputFilter" to the name. +> It is automatically appended when necessary. +> See our [Naming Standards](../naming-standards.md) page for more information. + +If you leave the name blank, the process will exit. + +If you input an invalid name (like, "."), an error will be thrown: + +> Invalid InputFilter name: "." + +If you input the name of an existing InputFilter (like, "ExistingInputFilter"), an error will be thrown: + +> Class "ExistingInputFilter" already exists at /path/to/project/src/ExistingModule/src/InputFilter/ExistingInputFilter.php + +Once you input a valid name (like, "Book"), `dot-maker` will prompt you to confirm which CRUD operations will be performed on the resource: + +### Create resources + +The prompt asks you whether you want to create resources: + +> Allow creating Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following file: + +- `src/ExistingModule/src/InputFilter/CreateBookInputFilter.php` + +Without confirmation, the process will skip to the next component. + +### Delete resources + +The prompt asks you whether you want to delete resources: + +> Allow deleting Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following file: + +- `src/ExistingModule/src/InputFilter/DeleteBookInputFilter.php` + +Without confirmation, the process will skip to the next component. + +### Edit resources + +The prompt asks you whether you want to edit resources: + +> Allow editing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following file: + +- `src/ExistingModule/src/InputFilter/EditBookInputFilter.php` + +Without confirmation, the process will skip to the next component. + +### Replace resources + +> This file is created only when the project type is API. + +The prompt asks you whether you want to replace resources: + +> Allow replacing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following file: + +- `src/ExistingModule/src/InputFilter/ReplaceBookInputFilter.php` + +Without confirmation, the process will skip to the next component. + +## Create multiple InputFilters + +To allow the creation of multiple InputFilters, the process will loop until you leave the name blank. +Each iteration creates a new set of InputFilters under the same module. diff --git a/docs/book/v3/component/input.md b/docs/book/v3/component/input.md new file mode 100644 index 0000000..4acdd0d --- /dev/null +++ b/docs/book/v3/component/input.md @@ -0,0 +1,65 @@ +# Create Input + +> This page assumes that you have created a Composer "make" script as described on the [Setup page](../setup.md#add-dot-maker-to-composerjson). + +To create an Input, use either of the following commands: + +## Run the command + +```shell +composer make input +``` + +OR + +```shell +./vendor/bin/dot-maker input +``` + +## Identify the target module + +`dot-maker` needs to know in which module you want to create the new Input. +To determine this, it will prompt you to enter the name of an existing module: + +> Existing module name: + +If you input a module name which does not exist (like, "NonExistentModule"), an error will be thrown: + +> Module "NonExistentModule" not found + +and will keep prompting for a valid module name until you provide one. + +Once an existing module name (like, "ExistingModule") is provided, `dot-maker` will output a success message: + +> Found Module "ExistingModule" + +## Name the Input + +Once the target module has been identified, you will be prompted to input a name for the Input: + +> Input name: + +**The name must start with a letter, contain only letters and numbers, and must not be a PHP reserved word (for example `List`, `Class` or `Int`), with or without the component suffix.** + +> You don't have to append "Input" to the name. +> It is automatically appended when necessary. +> See our [Naming Standards](../naming-standards.md) page for more information. + +If you leave the name blank, the process will exit. + +If you input an invalid name (like, "."), an error will be thrown: + +> Invalid Input name: "." + +If you input the name of an existing Input (like, "ExistingInput"), an error will be thrown: + +> Class "ExistingInput" already exists at /path/to/project/src/ExistingModule/src/InputFilter/Input/ExistingInput.php + +If you input a valid name (like, "NewInput"), `dot-maker` will create the Input and output a success message: + +> Created Input: /path/to/project/src/ExistingModule/src/InputFilter/Input/NewInput.php + +## Create multiple Inputs + +To allow the creation of multiple Inputs, the process will loop until you leave the name blank. +Each iteration creates a new Input under the same module. diff --git a/docs/book/v3/component/middleware.md b/docs/book/v3/component/middleware.md new file mode 100644 index 0000000..3062cad --- /dev/null +++ b/docs/book/v3/component/middleware.md @@ -0,0 +1,78 @@ +# Create Middleware + +> This page assumes that you have created a Composer "make" script as described on the [Setup page](../setup.md#add-dot-maker-to-composerjson). + +To create a Middleware, use either of the following commands: + +## Run the command + +```shell +composer make middleware +``` + +OR + +```shell +./vendor/bin/dot-maker middleware +``` + +## Identify the target module + +`dot-maker` needs to know in which module you want to create the new Middleware. +To determine this, it will prompt you to enter the name of an existing module: + +> Existing module name: + +If you input a module name which does not exist (like, "NonExistentModule"), an error will be thrown: + +> Module "NonExistentModule" not found + +and will keep prompting for a valid module name until you provide one. + +Once an existing module name (like, "ExistingModule") is provided, `dot-maker` will output a success message: + +> Found Module "ExistingModule" + +## Name the Middleware + +Once the target module has been identified, you will be prompted to input a name for the Middleware: + +> Middleware name: + +**The name must start with a letter, contain only letters and numbers, and must not be a PHP reserved word (for example `List`, `Class` or `Int`), with or without the component suffix.** + +> You don't have to append "Middleware" to the name. +> It is automatically appended when necessary. +> See our [Naming Standards](../naming-standards.md) page for more information. + +If you leave the name blank, the process will exit. + +If you input an invalid name (like, "."), an error will be thrown: + +> Invalid Middleware name: "." + +If you input the name of an existing Middleware (like, "ExistingMiddleware"), an error will be thrown: + +> Class "ExistingMiddleware" already exists at /path/to/project/src/ExistingModule/src/Middleware/ExistingMiddleware.php + +If you input a valid name (like, "NewMiddleware"), `dot-maker` will create the Middleware and output a success message: + +> Created Middleware: /path/to/project/src/ExistingModule/src/Middleware/NewMiddleware.php + +## Create multiple Middleware + +To allow the creation of multiple Middleware, the process will loop until you leave the name blank. +Each iteration creates a new Middleware under the same module. + +## Next steps + +Once the Middleware is created, `dot-maker` will display the tasks that need to be performed manually, for example: + +```text +Next steps: +=========== +- add to config/pipeline.php: + $app->pipe(\ExistingModule\Middleware\NewMiddleware::class); +``` + +When you create more than one Middleware in the same run, each one is listed. diff --git a/docs/book/v3/component/module.md b/docs/book/v3/component/module.md new file mode 100644 index 0000000..4ca5813 --- /dev/null +++ b/docs/book/v3/component/module.md @@ -0,0 +1,359 @@ +# Create Module + +> This page assumes that you have created a Composer "make" script as described on the [Setup page](../setup.md#add-dot-maker-to-composerjson). + +To create a Module, use either of the following commands: + +## Run the command + +```shell +composer make module +``` + +OR + +```shell +./vendor/bin/dot-maker module +``` + +## Name the Module + +You will be prompted to input a name for the Module: + +> New module name: + +**The name must start with a letter, contain only letters and numbers, and must not be a PHP reserved word (for example `List`, `Class` or `Int`), with or without the component suffix.** + +If you leave the name blank, the process will exit. + +If you input an invalid name (like, "."), an error will be thrown: + +> Invalid Module name: "." + +If you input the name of an existing Module (like, "ExistingModule"), an error will be thrown: + +> Module "ExistingModule" already exists at /path/to/project/src/ExistingModule + +If you input a valid name (like, "NewModule"), `dot-maker` will create the Module and output a success message: + +> Created directory: /path/to/project/src/NewModule + +## Create Module files + +From here, the process will run through a predefined set of files to create the Module components. + +> The process will not ask for file names because they will be generated from the Module name. + +### Entity and Repository + +Next, you will be asked to confirm whether the Module needs an Entity (and its matching Repository): + +> Create entity and repository? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- for projects compatible with the Core architecture: + - `src/Core/src//src/Entity/.php` + - `src/Core/src//src/Repository/Repository.php` +- for projects which are NOT compatible with the Core architecture: + - `src//src/Entity/.php` + - `src//src/Repository/Repository.php` + +Without confirmation, the process will skip to the next component. + +### Service and ServiceInterface + +Next, you will be asked to confirm whether the Module needs a Service (and its matching ServiceInterface): + +> Create service and service interface? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src//src/Service/Service.php` +- `src//src/Service/ServiceInterface.php` + +If, at the previous step, you chose to create a Repository, it will be automatically injected into the Service. +Also, some common methods will be added to the Service and the ServiceInterface. + +Without confirmation, the process will skip to the next component. + +### Command + +Next, you will be asked to confirm whether the Module needs a Command: + +> Create command? [Y(es)/n(o)]: + +On confirmation, the process will create the following file: + +- `src//src/Command/Command.php` + +Without confirmation, the process will skip to the next component. + +### Middleware + +Next, you will be asked to confirm whether the Module needs a Middleware: + +> Create middleware? [Y(es)/n(o)]: + +On confirmation, the process will create the following file: + +- `src//src/Middleware/Middleware.php` + +If, previously you chose to create a ServiceInterface, it will be automatically injected into the Middleware. + +Without confirmation, the process will skip to the next component. + +### Handler + +Next, you will be asked to confirm whether the Module needs request Handlers: + +> Create handler? [Y(es)/n(o)]: + +On confirmation, depending on the project type, the process will iterate over a list of CRUD operations, asking you to confirm whether the Module needs a request Handler for each operation. + +#### API projects + +##### List resources + +The prompt asks you whether you want to list resources: + +> Allow listing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src//src/Collection/Collection.php`: describes a resource-specific collection +- `src//src/Handler//GetCollectionHandler.php`: handles the resource collection representation + +The matching Collection and ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +##### View resources + +The prompt asks you whether you want to view resources: + +> Allow viewing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following file: + +- `src//src/Handler//GetResourceHandler.php`: handles the resource representation + +The matching ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +##### Create resources + +The prompt asks you whether you want to create resources: + +> Allow creating Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src//src/Handler//PostResourceHandler.php`: handles the resource creation +- `src//src/InputFilter/CreateInputFilter.php`: request payload validators + +The matching InputFilter and ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +##### Delete resources + +The prompt asks you whether you want to delete resources: + +> Allow deleting Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src//src/Handler//DeleteResourceHandler.php`: handles the resource deletion + +The matching ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +##### Edit resources + +The prompt asks you whether you want to edit resources: + +> Allow editing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src//src/Handler//PatchResourceHandler.php`: handles the resource update +- `src//src/InputFilter/EditInputFilter.php`: request payload validators + +The matching InputFilter and ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +##### Replace resources + +The prompt asks you whether you want to replace resources: + +> Allow replacing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src//src/Handler//PutResourceHandler.php`: handles the resource replacement +- `src//src/InputFilter/ReplaceInputFilter.php`: request payload validators + +The matching InputFilter and ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +#### Non-API projects + +##### List resources + +The prompt asks you whether you want to list resources: + +> Allow listing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src//src/Handler//GetListHandler.php`: renders the resource list page +- `src//templates//-list.html.twig`: renders the resource list + +The matching ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +##### View resources + +The prompt asks you whether you want to view resources: + +> Allow viewing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src//src/Handler//GetViewHandler.php`: renders the resource page +- `src//templates//-view.html.twig`: renders the resource + +The matching ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +##### Create resources + +The prompt asks you whether you want to create resources: + +> Allow creating Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src//src/Handler//GetCreateFormHandler.php`: renders the resource creation form page +- `src//src/Handler//PostCreateHandler.php`: handles the resource creation +- `src//src/Form/CreateForm.php`: form fields +- `src//src/InputFilter/CreateInputFilter.php`: form field validators +- `src//templates//-view.html.twig`: renders the resource creation form + +The matching Form and ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +##### Delete resources + +The prompt asks you whether you want to delete resources: + +> Allow deleting Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src//src/Handler//GetDeleteFormHandler.php`: renders the resource deletion form page +- `src//src/Handler//PostDeleteHandler.php`: handles the resource deletion +- `src//src/Form/DeleteForm.php`: form fields +- `src//src/InputFilter/DeleteInputFilter.php`: form field validators +- `src//src/InputFilter/Input/ConfirmDeleteInput.php`: checkbox input for deletion confirmation +- `src//templates//-delete-form.html.twig`: renders the resource deletion form + +The matching ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +##### Edit resources + +The prompt asks you whether you want to edit resources: + +> Allow editing Resources? [Y(es)/n(o)]: + +On confirmation, the process will create the following files: + +- `src//src/Handler//GetEditFormHandler.php`: renders the resource edit form page +- `src//src/Handler//PostEditHandler.php`: handles the resource update +- `src//src/Form/EditForm.php`: form fields +- `src//src/InputFilter/EditInputFilter.php`: form field validators +- `src//templates//-edit-form.html.twig`: renders the resource creation form + +The matching InputFilter and ServiceInterface will be automatically injected into the Handler. + +Without confirmation, the process will skip to the next component. + +### RoutesDelegator + +This component is created only if you chose to create request Handlers. +It is generated automatically and contains the basic CRUD operations based on the selected actions during Handler creation. + +Location: `src//src/RoutesDelegator.php` + +### OpenAPI + +> This component is created only when a project type is API. + +It is generated automatically and contains the basic description of the API endpoints found in this Module. +Each endpoint gets an `operationId`, a name unique within the Module, built from its handler class name without the `Handler` suffix and with a lowercase first letter (for example `getBookCollection` for `GetBookCollectionHandler`). +Keep it unique across the whole API as well, which holds as long as your entity names are unique. +Once you extend the entities with additional fields, you will need to update the OpenAPI file manually. + +Location: `src//src/OpenAPI.php` + +### ConfigProvider + +It is generated automatically and contains all the delegators, factories and service aliases for this Module. +Once you add new files that need dependency injection, you will need to update the ConfigProvider manually. + +Location: `src//src/ConfigProvider.php` + +### Core ConfigProvider + +> This component is created only when a project uses the Core architecture. + +It is generated automatically and contains all the delegators, factories and service aliases for this Module. +Once you add new files that need dependency injection, you will need to update the ConfigProvider manually. + +Location: `src/Core/src//src/ConfigProvider.php` + +### Templates + +> This file structure is NOT created when the project type is API. + +Location: `src//templates//*.html.twig` + +## Next steps + +Once the Module is created, `dot-maker` will display a list of tasks that need to be performed manually: + +```text +Next steps: +=========== +- add to config/config.php: + \\ConfigProvider::class, +- add to config/config.php: + Core\\ConfigProvider::class, +- add to config/autoload/cli.global.php under dot_cli.commands: + \\Command\Command::getDefaultName() => \\Command\Command::class, +- add to config/pipeline.php: + $app->pipe(\\Middleware\Middleware::class); +- add to config/autoload/authorization.global.php (OR config/autoload/authorization-guards.global.php) + the routes registered in /path/to/project/src//src/RoutesDelegator.php +- add to composer.json under autoload.psr-4: + "\\\\": "src//src/" +- add to composer.json under autoload.psr-4: + "Core\\\\": "src/Core/src//src/" +- dump Composer autoloader by executing this command: + composer dump +- generate Doctrine migration: + php ./vendor/bin/doctrine-migrations diff +- Review each new file, verify their contents and start adding logic to them. +``` + +where `` is the project type (**API**, **Admin**, **Frontend**, **Light** or **Queue**) and `` is the name of the Module. diff --git a/docs/book/v3/component/repository.md b/docs/book/v3/component/repository.md new file mode 100644 index 0000000..d4d54e2 --- /dev/null +++ b/docs/book/v3/component/repository.md @@ -0,0 +1,79 @@ +# Create Repository + +> This page assumes that you have created a Composer "make" script as described on the [Setup page](../setup.md#add-dot-maker-to-composerjson). + +## Run the command + +To create a Repository, use either of the following commands: + +```shell +composer make repository +``` + +OR + +```shell +./vendor/bin/dot-maker repository +``` + +## Identify the target module + +`dot-maker` needs to know in which module you want to create the new Repository. +To determine this, it will prompt you to enter the name of an existing module: + +> Existing module name: + +If you input a module name which does not exist (like, "NonExistentModule"), an error will be thrown: + +> Module "NonExistentModule" not found + +and will keep prompting for a valid module name until you provide one. + +Once an existing module name (like, "ExistingModule") is provided, `dot-maker` will output a success message: + +> Found Module "ExistingModule" + +## Name the Repository + +Once the target module has been identified, you will be prompted to input a name for the Repository: + +> Repository name: + +**The name must start with a letter, contain only letters and numbers, and must not be a PHP reserved word (for example `List`, `Class` or `Int`), with or without the component suffix.** + +> You don't have to append "Repository" to the name. +> It is automatically appended when necessary. +> See our [Naming Standards](../naming-standards.md) page for more information. + +If you leave the name blank, the process will exit. + +If you input an invalid name (like, "."), an error will be thrown: + +> Invalid Repository name: "." + +If you input the name of an existing Repository (like, "ExistingRepository"), an error will be thrown: + +- for projects compatible with the Core architecture: + +> Class "ExistingRepository" already exists at /path/to/project/src/Core/src/ExistingModule/src/Repository/ExistingRepository.php + +- for projects which are NOT compatible with the Core architecture: + +> Class "ExistingRepository" already exists at /path/to/project/src/ExistingModule/src/Repository/ExistingRepository.php + +If you input a valid name (like, "NewRepository"), `dot-maker` will create the Repository and output a success message: + +- for projects compatible with the Core architecture: + +> Created Entity: /path/to/project/src/Core/src/ExistingModule/src/Entity/NewEntity.php +> Created Repository: /path/to/project/src/Core/src/ExistingModule/src/Repository/NewEntityRepository.php + +- for projects which are NOT compatible with the Core architecture: + +> Created Entity: /path/to/project/src/ExistingModule/src/Entity/NewEntity.php +> Created Repository: /path/to/project/src/ExistingModule/src/Repository/NewEntityRepository.php + +## Create multiple Repositories + +To allow the creation of multiple Repositories, the process will loop until you leave the name blank. +Each iteration creates a new pair of Entity and Repository under the same module. diff --git a/docs/book/v3/component/service-interface.md b/docs/book/v3/component/service-interface.md new file mode 100644 index 0000000..f831f02 --- /dev/null +++ b/docs/book/v3/component/service-interface.md @@ -0,0 +1,70 @@ +# Create ServiceInterface + +> This page assumes that you have created a Composer "make" script as described on the [Setup page](../setup.md#add-dot-maker-to-composerjson). + +> `dot-maker` will look for a matching Repository in the module (e.g.: BookRepository — BookService). +> If it finds one, it will automatically inject it into the Service. +> Also, some common methods will be added to the Service and the ServiceInterface. + +## Run the command + +To create a ServiceInterface, use either of the following commands: + +```shell +composer make service-interface +``` + +OR + +```shell +./vendor/bin/dot-maker service-interface +``` + +## Identify the target module + +`dot-maker` needs to know in which module you want to create the new ServiceInterface. +To determine this, it will prompt you to enter the name of an existing module: + +> Existing module name: + +If you input a module name which does not exist (like, "NonExistentModule"), an error will be thrown: + +> Module "NonExistentModule" not found + +and will keep prompting for a valid module name until you provide one. + +Once an existing module name (like, "ExistingModule") is provided, `dot-maker` will output a success message: + +> Found Module "ExistingModule" + +## Name the ServiceInterface + +Once the target module has been identified, you will be prompted to input a name for the ServiceInterface: + +> ServiceInterface name: + +**The name must start with a letter, contain only letters and numbers, and must not be a PHP reserved word (for example `List`, `Class` or `Int`), with or without the component suffix.** + +> You don't have to append "ServiceInterface" to the name. +> It is automatically appended when necessary. +> See our [Naming Standards](../naming-standards.md) page for more information. + +If you leave the name blank, the process will exit. + +If you input an invalid name (like, "."), an error will be thrown: + +> Invalid ServiceInterface name: "." + +If you input the name of an existing ServiceInterface (like, "ExistingServiceInterface"), an error will be thrown: + +> Class "ExistingServiceInterface" already exists at /path/to/project/src/ExistingModule/src/Service/ExistingServiceInterface.php + +If you input a valid name (like, "NewServiceInterface"), `dot-maker` will create the ServiceInterface and output a success message: + +> Created ServiceInterface: /path/to/project/src/ExistingModule/src/Service/NewServiceInterface.php +> Created Service: /path/to/project/src/ExistingModule/src/Service/NewService.php + +## Create multiple ServiceInterfaces + +To allow the creation of multiple ServiceInterfaces, the process will loop until you leave the name blank. +Each iteration creates a new pair of Service and ServiceInterface under the same module. diff --git a/docs/book/v3/component/service.md b/docs/book/v3/component/service.md new file mode 100644 index 0000000..d1d0d7f --- /dev/null +++ b/docs/book/v3/component/service.md @@ -0,0 +1,70 @@ +# Create Service + +> This page assumes that you have created a Composer "make" script as described on the [Setup page](../setup.md#add-dot-maker-to-composerjson). + +> `dot-maker` will look for a matching Repository in the module (e.g.: BookRepository — BookService). +> If it finds one, it will automatically inject it into the Service. +> Also, some common methods will be added to the Service and the ServiceInterface. + +## Run the command + +To create a Service, use either of the following commands: + +```shell +composer make service +``` + +OR + +```shell +./vendor/bin/dot-maker service +``` + +## Identify the target module + +`dot-maker` needs to know in which module you want to create the new Service. +To determine this, it will prompt you to enter the name of an existing module: + +> Existing module name: + +If you input a module name which does not exist (like, "NonExistentModule"), an error will be thrown: + +> Module "NonExistentModule" not found + +and will keep prompting for a valid module name until you provide one. + +Once an existing module name (like, "ExistingModule") is provided, `dot-maker` will output a success message: + +> Found Module "ExistingModule" + +## Name the Service + +Once the target module has been identified, you will be prompted to input a name for the Service: + +> Service name: + +**The name must start with a letter, contain only letters and numbers, and must not be a PHP reserved word (for example `List`, `Class` or `Int`), with or without the component suffix.** + +> You don't have to append "Service" to the name. +> It is automatically appended when necessary. +> See our [Naming Standards](../naming-standards.md) page for more information. + +If you leave the name blank, the process will exit. + +If you input an invalid name (like, "."), an error will be thrown: + +> Invalid Service name: "." + +If you input the name of an existing Service (like, "ExistingService"), an error will be thrown: + +> Class "ExistingService" already exists at /path/to/project/src/ExistingModule/src/Service/ExistingService.php + +If you input a valid name (like, "NewService"), `dot-maker` will create the Service and output a success message: + +> Created Service: /path/to/project/src/ExistingModule/src/Service/NewService.php +> Created ServiceInterface: /path/to/project/src/ExistingModule/src/Service/NewServiceInterface.php + +## Create multiple Services + +To allow the creation of multiple Services, the process will loop until you leave the name blank. +Each iteration creates a new pair of Service and ServiceInterface under the same module. diff --git a/docs/book/v3/installation.md b/docs/book/v3/installation.md new file mode 100644 index 0000000..3dc9ae8 --- /dev/null +++ b/docs/book/v3/installation.md @@ -0,0 +1,9 @@ +# Installation + +`dotkernel/dot-maker` 3.x requires PHP 8.3, 8.4, 8.5 or 8.6. + +Install `dotkernel/dot-maker` by executing the following Composer command: + +```shell +composer require --dev dotkernel/dot-maker +``` diff --git a/docs/book/v3/io/input.md b/docs/book/v3/io/input.md new file mode 100644 index 0000000..c23cfe9 --- /dev/null +++ b/docs/book/v3/io/input.md @@ -0,0 +1,48 @@ +# Input data + +`dot-maker` uses two types of input: + +- prompt: where the user has to enter some data and press **Enter** +- confirm: where the user has to enter one of the predefined options and/or press **Enter** + +## Prompt + +The user is presented with a message, for example: + +> Input file name: + +and they must enter some data and press **Enter**. + +Whether the command accepts blank input depends on the command. +Some will accept blank input and exit, others will keep prompting until the user enters some valid data. + +## Confirm + +> Confirmations are case-insensitive, so the user may enter lowercase, uppercase or mixed-case letters. + +The user is presented with a message, for example: + +> Perform an action? [Y(es)/n(o)]: + +OR + +> Perform an action? [y(es)/N(o)]: + +and they must enter one of the predefined options and/or press **Enter**. + +The valid options are: `y`, `yes`, `n`, `no` and blank. +If the user enters an invalid value, the command will loop until it receives a valid input. + +If the user submits a blank input, the default value is used. +The default value can be identified by finding the branch starting with a capital letter. +So, for `[Y(es)/n(o)]` the default value is `yes` and for `[y(es)/N(o)]` the default value is `no`. + +## End of input + +When the input ends (for example after **Ctrl+D**, or when answers are piped in and run out), every remaining prompt receives a blank answer: + +- a prompt that accepts blank input exits, as described above +- a confirmation uses its default value +- the **Existing module name** prompt, which needs an answer, stops the run with this error and exit code 1: + +> No module name given before the end of input. diff --git a/docs/book/v3/io/output.md b/docs/book/v3/io/output.md new file mode 100644 index 0000000..d8d2827 --- /dev/null +++ b/docs/book/v3/io/output.md @@ -0,0 +1,33 @@ +# Output data + +`dot-maker` aims to deliver a simple and intuitive user experience. +Each user input can result in one of the following outputs: + +- on success: the message is green and shows what file was created +- on failure: the message is red and shows what went wrong + +## Debug info + +On executing a create component command, the first output you will see is related to project detection. + +The first line is an info message confirming the project type, for example: + +> Detected project type: Api + +The second line is an info message confirming whether the project uses Core architecture, for example: + +> Core architecture: Yes + +These are detected by looking at the modules registered in `composer.json` under **autoload**.**psr-4**. +At least one namespace that does not start with `Core\` must be registered there, otherwise `dot-maker` stops with an error. + +## Next steps + +After creating a component that needs manual registration (a Module, Command, Middleware or Entity), `dot-maker` prints a **Next steps** list with the tasks to perform, such as registering a Command in `config/autoload/cli.global.php`. + +## Exit codes + +- `0`: the command finished successfully +- `1`: the command failed, for example because of an unknown component or an invalid `composer.json` + +Use the exit code when running `dot-maker` from scripts. diff --git a/docs/book/v3/naming-standards.md b/docs/book/v3/naming-standards.md new file mode 100644 index 0000000..9fb93cd --- /dev/null +++ b/docs/book/v3/naming-standards.md @@ -0,0 +1,235 @@ +# Naming Standards + +Inside the Dotkernel ecosystem, we strictly follow the following standards to make sure that we provide clean and easy-to-follow code: + +- [PSR-4](https://www.php-fig.org/psr/psr-4/): the autoloading standard—for easy autoloading of classes. +- [PSR-12](https://www.php-fig.org/psr/psr-12/): the extended coding style—for suggestive file names. + +## Valid names + +Every name you input in `dot-maker` becomes part of a PHP class name, so it must: + +- start with a letter +- contain only letters and numbers +- not be a PHP reserved word, such as `List`, `Class`, `Function`, `Match`, `Int` or `Self`, with or without the component suffix (so `ListEntity` is rejected too) + +A trailing component suffix is removed and added back where the pattern requires it, so `Book` and `BookCommand` both create `BookCommand`. +A name that is only the suffix is kept as it is: `Entity` creates the Entity `Entity`. + +Generated files follow the [Laminas Coding Standard](https://github.com/laminas/laminas-coding-standard) used by Dotkernel projects. + +## Collections + +> Can only be created in API projects. + +These are files that are used to contain a set of resources of the same type. + +- location: `src//src/Collection` +- pattern: _Name_ + `Collection` +- example: `src//src/Collection/ExampleCollection.php` + +## Commands + +These are CLI scripts that are used to perform a specific task. + +- location: `src//src/Command` +- pattern: _Name_ + `Command` +- example: `src//src/Command/ExampleCommand.php` +- console name: kebab-case class name without the trailing `-command`, plus `:command` (for example `example:command`) + +Core-compatible projects MAY also have Core Commands: + +- location: `src/Core/src//src/Command` +- pattern: _Name_ + `Command` +- example: `src/Core/src//src/Command/ExampleCommand.php` + +## ConfigProvider + +These are configuration classes where aliases, delegators, factories and template paths are registered. + +- location: `src//src` +- pattern: `ConfigProvider` +- example: `src//src/ConfigProvider.php` + +Core-compatible projects also have a Core ConfigProvider: + +- location: `src/Core/src//src` +- pattern: `ConfigProvider` +- example: `src/Core/src//src/ConfigProvider.php` + +When this file exists, Doctrine entity configurations are stored here. +Else, those too are stored in `src//src/ConfigProvider.php`. + +## Entities + +These are classes that represent a single resource and are used to store and retrieve data in a database. + +- location: `src/Core/src/ModuleName/Entity` +- pattern: _Name_ +- example: `src/Core/src/ModuleName/Entity/Example.php` + +### Legacy projects + +- location: `src//src/Entity` +- pattern: _Name_ +- example: `src//src/Entity/Example.php` + +## Factories + +These are classes responsible for instantiating specific objects. + +- location: `src//src/Factory` +- pattern: _Name_ + `Factory` +- example: `src//src/Factory/ExampleFactory.php` + +Core-compatible projects MAY also have Core Factories: + +- location: `src/Core/src//src/Factory` +- pattern: _Name_ + `Factory` +- example: `src/Core/src//src/Factory/ExampleFactory.php` + +## Fixtures + +These are classes used to populate the database with test data. + +- location: `src/Core/src/App/src/Fixture` +- pattern: _Name_ + `Loader` +- example: `src/Core/src/App/src/Fixture/ExampleLoader.php` + +## Forms + +> Cannot be created in API projects. + +These are objectual representations of an HTML form. + +- location: `src//src/Form` +- pattern: _Name_ + `Form` +- example: `src//src/Form/ExampleForm.php` + +## Handlers + +These are classes responsible for handling a specific HTTP request. + +- location: `src//src/Handler/` +- pattern: _Verb_ + _Name_ + _Action_ + `Handler` +- example: `src//src/Handler/PostCreateHandler.php` + +### API projects + +- location: `src//src/Handler/` +- pattern: + - resources: _Verb_ + _Name_ + `ResourceHandler` + - collections: _Verb_ + _Name_ + `CollectionHandler` +- example: + - resources: `src//src/Handler//CreateResourceHandler.php` + - collections: `src//src/Handler//GetCollectionHandler.php` + +## Inputs + +These are objectual representations of an HTML form input. + +- location: `src//src/InputFilter/Input` +- pattern: _Name_ + `Input` +- example: `src//src/InputFilter/Input/ExampleInput.php` + +Core-compatible projects MAY also have Core Inputs: + +- location: `src/Core/src//src/InputFilter/Input` +- pattern: _Name_ + `Input` +- example: `src/Core/src//src/InputFilter/Input/ExampleInput.php` + +## InputFilters + +These are classes that are used to validate and filter form data. + +- location: `src//src/InputFilter` +- pattern: _Name_ + `InputFilter` +- example: `src//src/InputFilter/ExampleInputFilter.php` + +Core-compatible projects MAY also have Core InputFilters: + +- location: `src/Core/src//src/InputFilter` +- pattern: _Name_ + `InputFilter` +- example: `src/Core/src//src/InputFilter/ExampleInputFilter.php` + +## Middleware + +These are classes that can be used to perform actions before and after a request has been handled. + +- location: `src//src/Middleware` +- pattern: _Name_ + `Middleware` +- example: `src//src/Middleware/ExampleMiddleware.php` + +Core-compatible projects MAY also have Core Middleware: + +- location: `src/Core/src//src/Middleware` +- pattern: _Name_ + `Middleware` +- example: `src/Core/src//src/Middleware/ExampleMiddleware.php` + +## Migrations + +These are classes used to modify the database schema. + +- location: `src/Core/src/App/src/Migration` +- pattern: `Version` + _Timestamp_ +- example: `src/Core/src/App/src/Migration/Version20250407142911.php` + +## OpenAPI + +> Can only be created in API projects. + +These are configuration classes where OpenAPI specifications are registered. + +- location: `src//src` +- pattern: `OpenAPI` +- example: `src//src/OpenAPI.php` + +## Repositories + +These are classes that represent an intermediary layer between the database and the entities. + +- location: `src/Core/src/ModuleName/Repository` +- pattern: _Name_ + `Repository` +- example: `src/Core/src/ModuleName/Repository/ExampleRepository.php` + +### Legacy projects + +- location: `src//src/Repository` +- pattern: _Name_ + `Repository` +- example: `src//src/Repository/ExampleRepository.php` + +## RoutesDelegator + +These are configuration classes where HTTP request routes are registered. + +- location: `src//src` +- pattern: `RoutesDelegator` +- example: `src//src/RoutesDelegator.php` + +## Services + +These are classes that contain task-specific methods to be reused across the application. + +- location: `src//src/Service` +- pattern: _Name_ + `Service` +- example: `src//src/Service/ExampleService.php` + +Core-compatible projects MAY also have Core Services: + +- location: `src/Core/src//src/Service` +- pattern: _Name_ + `Service` +- example: `src/Core/src//src/Service/ExampleService.php` + +## ServiceInterfaces + +These are interfaces that serve as contracts for services. + +- location: `src//src/ServiceInterface` +- pattern: _Name_ + `ServiceInterface` +- example: `src//src/Service/ExampleServiceInterface.php` + +Core-compatible projects MAY also have Core ServiceInterfaces: + +- location: `src/Core/src//src/Service` +- pattern: _Name_ + `Service` +- example: `src/Core/src//src/Service/ExampleServiceInterface.php` diff --git a/docs/book/v3/overview.md b/docs/book/v3/overview.md new file mode 100644 index 0000000..2f0d21e --- /dev/null +++ b/docs/book/v3/overview.md @@ -0,0 +1,23 @@ +# Overview + +Programmatically generate Dotkernel project files and directories. + +## Badges + +![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-maker) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-maker/3.0.0) + +[![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-maker)](https://github.com/dotkernel/dot-maker/issues) +[![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-maker)](https://github.com/dotkernel/dot-maker/network) +[![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-maker)](https://github.com/dotkernel/dot-maker/stargazers) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-maker)](https://github.com/dotkernel/dot-maker/blob/3.0/LICENSE) + +[![Build Static](https://github.com/dotkernel/dot-maker/actions/workflows/continuous-integration.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-maker/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-maker/graph/badge.svg?token=KT9UA402B4)](https://codecov.io/gh/dotkernel/dot-maker) +[![PHPStan](https://github.com/dotkernel/dot-maker/actions/workflows/static-analysis.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-maker/actions/workflows/static-analysis.yml) + +Make sure you run through our guides on using the [inputs](./io/input.md) and the [outputs](./io/output.md). + + + + diff --git a/docs/book/v3/setup.md b/docs/book/v3/setup.md new file mode 100644 index 0000000..33fcdf1 --- /dev/null +++ b/docs/book/v3/setup.md @@ -0,0 +1,20 @@ +# Setup + +Once installed, `dot-maker` is ready for usage, no need for extra configurations. + +## Add dot-maker to composer.json + +> This step is optional but recommended. + +Open your project's `composer.json` and locate the `scripts` section. +If it does not exist, create it at the document's root level. + +Register a new script by appending `"alias": "dot-maker"` to the `scripts` section, where **alias** can be any string you want; like, for example, **make**. + +```json +{ + "scripts": { + "make": "dot-maker" + } +} +``` diff --git a/docs/book/v3/upgrading.md b/docs/book/v3/upgrading.md new file mode 100644 index 0000000..81f6e47 --- /dev/null +++ b/docs/book/v3/upgrading.md @@ -0,0 +1,37 @@ +# Upgrading from 2.x to 3.x + +`dot-maker` 3.x supports PHP 8.3, 8.4, 8.5 and 8.6. +Update the constraint in your project's `composer.json`: + +```shell +composer require --dev dotkernel/dot-maker:^3.0 +``` + +## Changes that can affect you + +| Change | Symptom | Fix | +| --- | --- | --- | +| Stricter names | `Invalid ... name` for names such as `1Book`, `List`, `Class` or `ListEntity` | Use a name that starts with a letter and is not a PHP reserved word, with or without the component suffix | +| A name that is only the suffix keeps it | `Entity` creates the Entity `Entity` instead of a file called `.php` | Nothing to do; the old behaviour produced a broken file | +| End of input at the module prompt | Piped input that ends before the module name stops with "No module name given before the end of input." and exit code 1 | Provide the module name in the input | +| Exit codes | Scripts that ignored failures now fail, because `dot-maker` exits with 1 on errors | Check the exit code, or fix the reported error | +| Command console name | A Command whose name contains `Command` before the end (for example `MyCommandHandler`) gets a different `name:` | Rename the generated name only if you depend on the old one | +| Template variable in GET form handlers | Generated `GetEdit...FormHandler` and `GetDelete...FormHandler` pass the entity as `bookStore` instead of `book-store` | Use the camelCase variable in your templates, as the POST handlers already do | +| Generated array alignment | Generated arrays are aligned to the Laminas Coding Standard | Nothing to do; `composer cs-check` passes on generated files | +| Forms in API projects | `dot-maker form` in an API project stops before the module prompt, with exit code 1 | Nothing to do; Forms are not created in APIs | +| `composer.json` detection | `RuntimeException` when `autoload.psr-4` has no namespace outside `Core\` | Register your application module under `autoload.psr-4` | + +## Changes for code that extends dot-maker + +These only matter if you wrote your own classes on top of `dot-maker`. + +| Change | Symptom | Fix | +| --- | --- | --- | +| `FileInterface::create()` returns `File` instead of `?File` | Fatal error in a class that implements `FileInterface` and declares `?File` | Declare and return `File` | +| `Context::getRootNamespace()` and `Context::getProjectType()` return `string` | Static analysis reports always-true null checks | Remove the null checks | +| `Module::getMessages()` returns `array>` | Code that reads the messages gets arrays instead of strings | Iterate the nested arrays (priority, then message) | +| `Component` rejects an empty class name | `InvalidArgumentException` | Pass a non-empty class name | +| `FileSystem::getModuleName()` before `setModuleName()` | `RuntimeException('No module selected.')` instead of an engine `Error` | Call `setModuleName()` first | +| `Input::isExhausted()` added | None | Use it to detect the end of input in custom prompts | +| `Entity::getNumericIdentifierTraitFqcn()` removed (it was never called) | Fatal error "Call to undefined method" | Use `sprintf(Import::ROOT_APP_ENTITY_NUMERICIDENTIFIERTRAIT, $namespace)` | +| `FileSystem::coreModule()` removed (it was never called) | Fatal error "Call to undefined method" | Create the `Directory` yourself: `new Directory($name, $projectPath . '/src/Core/src')` | diff --git a/docs/book/v3/usage.md b/docs/book/v3/usage.md new file mode 100644 index 0000000..cef812c --- /dev/null +++ b/docs/book/v3/usage.md @@ -0,0 +1,8 @@ +# Usage + +Invoke `dot-maker` by executing: + +- the bin file in your vendor directory `./vendor/bin/dot-maker` +- the (optional) Composer script created during [Setup](setup.md#add-dot-maker-to-composerjson): `composer make` + +Follow the instructions on the screen to create a specific Dotkernel project component. diff --git a/mkdocs.yml b/mkdocs.yml index 7f24577..52bcb2d 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -2,14 +2,38 @@ docs_dir: docs/book site_dir: docs/html extra: project: Packages - current_version: v2 + current_version: v3 versions: + - v3 - v2 - v1 installation: composer_dev: true nav: - Home: index.md + - v3: + - Overview: v3/overview.md + - Installation: v3/installation.md + - Setup: v3/setup.md + - Usage: v3/usage.md + - Component: + - Create Collection: v3/component/collection.md + - Create Command: v3/component/command.md + - Create Entity: v3/component/entity.md + - Create Form: v3/component/form.md + - Create Handler: v3/component/handler.md + - Create Input: v3/component/input.md + - Create InputFilter: v3/component/input-filter.md + - Create Middleware: v3/component/middleware.md + - Create Module: v3/component/module.md + - Create Repository: v3/component/repository.md + - Create Service: v3/component/service.md + - Create ServiceInterface: v3/component/service-interface.md + - IO: + - Input: v3/io/input.md + - Output: v3/io/output.md + - Naming Standards: v3/naming-standards.md + - Upgrading: v3/upgrading.md - v2: - Overview: v2/overview.md - Installation: v2/installation.md diff --git a/phpstan.neon b/phpstan.neon index 701a4a2..08d6acd 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,12 +1,8 @@ includes: - vendor/phpstan/phpstan-phpunit/extension.neon parameters: - level: 5 + level: 8 paths: - src - test treatPhpDocTypesAsCertain: false - ignoreErrors: - - - message: '#Call to an undefined method org\\bovigo\\vfs\\vfsStreamContent::getChild\(\).#' - path: %currentWorkingDirectory%/test/FileSystem/FileTest.php diff --git a/phpunit.xml b/phpunit.xml index 52cc404..7ae2ddf 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,16 +1,23 @@ + cacheDirectory=".phpunit.cache" + colors="true" + failOnDeprecation="true" + failOnNotice="true" + failOnWarning="true" + failOnRisky="true" + failOnPhpunitDeprecation="true" + failOnPhpunitNotice="true" + displayDetailsOnAllIssues="true"> ./test ./test/Helper.php - - + ./src diff --git a/src/Component.php b/src/Component.php index 1b9153d..b3c0a67 100644 --- a/src/Component.php +++ b/src/Component.php @@ -4,13 +4,15 @@ namespace Dot\Maker; +use InvalidArgumentException; + use function implode; use function in_array; use function lcfirst; use function preg_match; -use function preg_replace; use function preg_split; use function sprintf; +use function str_ends_with; use function str_replace; use function strlen; use function strtolower; @@ -20,12 +22,26 @@ class Component { + /** @var non-empty-string $className */ + private readonly string $className; + + /** + * @throws InvalidArgumentException + */ public function __construct( private readonly string $namespace, - private readonly string $className, + string $className, ) { + if ($className === '') { + throw new InvalidArgumentException('Class name must not be empty.'); + } + + $this->className = $className; } + /** + * @return non-empty-string + */ public function getClassName(): string { return $this->className; @@ -51,6 +67,9 @@ public function getFindMethodName(): string return sprintf('find%s', ucfirst($this->className)); } + /** + * @return non-empty-string + */ public function getFqcn(): string { return sprintf('%s\\%s', $this->namespace, $this->className); @@ -83,6 +102,10 @@ public function getVariable(bool $noInterface = true): string public static function pluralize(string $name): string { + if ($name === '') { + return $name; + } + $lastLetter = strtolower($name[strlen($name) - 1]); if (in_array($lastLetter, ['s', 'x', 'z']) || preg_match('/(sh|ch)$/i', $name)) { @@ -94,11 +117,23 @@ public static function pluralize(string $name): string } } + /** + * Remove $suffix from the end of $name, unless $name is exactly $suffix. + */ + public static function stripSuffix(string $name, string $suffix): string + { + if ($name !== $suffix && str_ends_with($name, $suffix)) { + return substr($name, 0, -strlen($suffix)); + } + + return $name; + } + public function toCamelCase(bool $noInterface = false): string { $property = lcfirst($this->className); if ($noInterface) { - return preg_replace('/Interface$/', '', $property); + return self::stripSuffix($property, 'Interface'); } return $property; @@ -106,9 +141,10 @@ public function toCamelCase(bool $noInterface = false): string public function toKebabCase(bool $noInterface = true): string { - $parts = preg_split('/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/', $this->toCamelCase($noInterface)); + $camelCase = $this->toCamelCase($noInterface); + $parts = preg_split('/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/', $camelCase); - return strtolower(implode('-', $parts)); + return strtolower(implode('-', $parts === false ? [$camelCase] : $parts)); } public function toPlural(): string diff --git a/src/Component/ArrayAligner.php b/src/Component/ArrayAligner.php new file mode 100644 index 0000000..8f13f53 --- /dev/null +++ b/src/Component/ArrayAligner.php @@ -0,0 +1,79 @@ +\s*(.*)$/'; + + public static function align(string $code): string + { + $lines = explode("\n", $code); + + /** @var list> $groups */ + $groups = []; + foreach ($lines as $index => $line) { + if ($groups !== [] && preg_match(self::KEY_PATTERN, $line, $matches) === 1) { + $groups[array_key_last($groups)][] = [$index, $matches[1], $matches[2], $matches[3]]; + } + + $depth = self::bracketBalance($line); + for (; $depth > 0; $depth--) { + $groups[] = []; + } + for (; $depth < 0 && $groups !== []; $depth++) { + self::alignGroup($lines, (array) array_pop($groups)); + } + } + + return implode("\n", $lines); + } + + /** + * @param array $lines + * @param list $group + */ + private static function alignGroup(array &$lines, array $group): void + { + if ($group === []) { + return; + } + + $width = max(array_map(static fn (array $item): int => strlen($item[2]), $group)); + foreach ($group as [$index, $indent, $key, $value]) { + $lines[$index] = sprintf('%s%s%s=> %s', $indent, $key, str_repeat(' ', $width - strlen($key) + 1), $value); + } + } + + /** + * Opening minus closing square brackets on a line, ignoring brackets inside quoted strings. + */ + private static function bracketBalance(string $line): int + { + $code = (string) preg_replace('/\'(?:[^\'\\\\]|\\\\.)*\'|"(?:[^"\\\\]|\\\\.)*"/', '', $line); + + return substr_count($code, '[') - substr_count($code, ']'); + } +} diff --git a/src/Component/ClassFile.php b/src/Component/ClassFile.php index b14b4fa..f6c6369 100644 --- a/src/Component/ClassFile.php +++ b/src/Component/ClassFile.php @@ -4,6 +4,8 @@ namespace Dot\Maker\Component; +use InvalidArgumentException; + use function array_key_exists; use function array_map; use function count; @@ -68,14 +70,14 @@ public function addInterface(string $interface): self public function addMethod(MethodInterface $method): self { - $this->methods[$method->getName()] = $method; + $this->methods[self::assertName($method->getName())] = $method; return $this; } public function addProperty(ParameterInterface $property): self { - $this->properties[$property->getName()] = $property; + $this->properties[self::assertName($property->getName())] = $property; return $this; } @@ -92,41 +94,65 @@ public function addTrait(string $trait): self return $this; } + /** + * @return list + */ public function getInjects(): array { return $this->injects; } + /** + * @return array + */ public function getMethods(): array { return $this->methods; } + /** + * @return array + */ public function getProperties(): array { return $this->properties; } + /** + * @return array + */ public function getClassUses(): array { return $this->classUses; } + /** + * @return array + */ public function getConstantUses(): array { return $this->constantUses; } + /** + * @return array + */ public function getFunctionUses(): array { return $this->functionUses; } + /** + * @return array + */ public function getInterfaces(): array { return $this->interfaces; } + /** + * @return array + */ public function getTraits(): array { return $this->traits; @@ -257,7 +283,20 @@ public function render(): string $class .= '}' . PHP_EOL; - return $class; + return ArrayAligner::align($class); + } + + /** + * @return non-empty-string + * @throws InvalidArgumentException + */ + private static function assertName(string $name): string + { + if ($name === '') { + throw new InvalidArgumentException('Name must not be empty.'); + } + + return $name; } public function setAbstract(bool $abstract): self diff --git a/src/Component/Declaration.php b/src/Component/Declaration.php index b9e0e46..5a21d5c 100644 --- a/src/Component/Declaration.php +++ b/src/Component/Declaration.php @@ -13,7 +13,7 @@ class Declaration { - /** @var ParameterInterface[] $parameters */ + /** @var list $parameters */ private array $parameters = []; private bool $nullable = false; private string $returnType = 'void'; @@ -41,6 +41,9 @@ public function getComment(): string return $this->comment; } + /** + * @return list + */ public function getParameters(): array { return $this->parameters; diff --git a/src/Component/Import.php b/src/Component/Import.php index 0ebec66..e6516be 100644 --- a/src/Component/Import.php +++ b/src/Component/Import.php @@ -79,11 +79,17 @@ public function __construct( ) { } + /** + * @return non-empty-string + */ public function getAbstractFormFqcn(): string { return sprintf(self::ROOT_APP_FORM_ABSTRACTFORM, $this->context->getRootNamespace()); } + /** + * @return non-empty-string + */ public function getAbstractInputFilterFqcn(): string { $format = self::ROOT_APP_INPUTFILTER_ABSTRACTINPUTFILTER; @@ -95,11 +101,17 @@ public function getAbstractInputFilterFqcn(): string return sprintf($format, $this->context->getRootNamespace()); } + /** + * @return non-empty-string + */ public function getAbstractHandlerFqcn(): string { return sprintf(self::ROOT_APP_HANDLER_ABSTRACTHANDLER, $this->context->getRootNamespace()); } + /** + * @return non-empty-string + */ public function getAbstractRepositoryFqcn(): string { $format = self::ROOT_APP_REPOSITORY_ABSTRACTREPOSITORY; @@ -111,6 +123,9 @@ public function getAbstractRepositoryFqcn(): string return sprintf($format, $this->context->getRootNamespace()); } + /** + * @return non-empty-string + */ public function getAppHelperPaginatorFqcn(): string { $format = self::ROOT_APP_HELPER_PAGINATOR; @@ -122,6 +137,9 @@ public function getAppHelperPaginatorFqcn(): string return sprintf($format, $this->context->getRootNamespace()); } + /** + * @return non-empty-string + */ public function getAppMessageFqcn(): string { $format = self::ROOT_APP_MESSAGE; @@ -133,11 +151,17 @@ public function getAppMessageFqcn(): string return sprintf($format, $this->context->getRootNamespace()); } + /** + * @return non-empty-string + */ public function getBadRequestExceptionFqcn(): string { return sprintf(self::ROOT_APP_EXCEPTION_BADREQUESTEXCEPTION, $this->context->getRootNamespace()); } + /** + * @return non-empty-string + */ public function getConfigProviderFqcn(bool $core = false): string { if ($core && $this->context->hasCore()) { @@ -149,31 +173,49 @@ public function getConfigProviderFqcn(bool $core = false): string return sprintf(self::ROOT_APP_CONFIGPROVIDER, $rootNamespace); } + /** + * @return non-empty-string + */ public function getConflictExceptionFqcn(): string { return sprintf(self::ROOT_APP_EXCEPTION_CONFLICTEXCEPTION, $this->context->getRootNamespace()); } + /** + * @return non-empty-string + */ public function getCsrfInputFqcn(): string { return sprintf(self::ROOT_APP_INPUTFILTER_INPUT_CSRFINPUT, $this->context->getRootNamespace()); } + /** + * @return non-empty-string + */ public function getHandlerDelegatorFactoryFqcn(): string { return sprintf(self::ROOT_APP_FACTORY_HANDLERDELEGATORFACTORY, $this->context->getRootNamespace()); } + /** + * @return non-empty-string + */ public function getNotFoundExceptionFqcn(): string { return sprintf(self::ROOT_APP_EXCEPTION_NOTFOUNDEXCEPTION, $this->context->getRootNamespace()); } + /** + * @return non-empty-string + */ public function getResourceAttributeFqcn(): string { return sprintf(self::ROOT_APP_ATTRIBUTE_RESOURCE, $this->context->getRootNamespace()); } + /** + * @return non-empty-string + */ public function getResourceCollectionFqcn(): string { return sprintf(self::ROOT_APP_COLLECTION_RESOURCECOLLECTION, $this->context->getRootNamespace()); diff --git a/src/Component/Inject.php b/src/Component/Inject.php index 27fb508..d839db0 100644 --- a/src/Component/Inject.php +++ b/src/Component/Inject.php @@ -14,7 +14,9 @@ class Inject { - private array $namedArguments = []; + /** @var array $namedArguments */ + private array $namedArguments = []; + /** @var list $positionalArguments */ private array $positionalArguments = []; public function __construct( @@ -33,11 +35,17 @@ public function addArgument(string $argument, ?string $name = null): self return $this; } + /** + * @return array + */ public function getNamedArguments(): array { return $this->namedArguments; } + /** + * @return list + */ public function getPositionalArguments(): array { return $this->positionalArguments; diff --git a/src/Component/InterfaceFile.php b/src/Component/InterfaceFile.php index a5ea24d..9e0b14a 100644 --- a/src/Component/InterfaceFile.php +++ b/src/Component/InterfaceFile.php @@ -4,6 +4,8 @@ namespace Dot\Maker\Component; +use InvalidArgumentException; + use function array_map; use function count; use function implode; @@ -40,11 +42,18 @@ public function __toString(): string public function addDeclaration(Declaration $declaration): self { + if ($declaration->name === '') { + throw new InvalidArgumentException('Name must not be empty.'); + } + $this->declarations[$declaration->name] = $declaration; return $this; } + /** + * @param non-empty-string $interface + */ public function addInterface(string $interface): self { $this->interfaces[$interface] = $interface; @@ -52,26 +61,41 @@ public function addInterface(string $interface): self return $this; } + /** + * @return array + */ public function getDeclarations(): array { return $this->declarations; } + /** + * @return array + */ public function getClassUses(): array { return $this->classUses; } + /** + * @return array + */ public function getConstantUses(): array { return $this->constantUses; } + /** + * @return array + */ public function getFunctionUses(): array { return $this->functionUses; } + /** + * @return array + */ public function getInterfaces(): array { return $this->interfaces; diff --git a/src/Component/Method.php b/src/Component/Method.php index bf6aa6e..64479f1 100644 --- a/src/Component/Method.php +++ b/src/Component/Method.php @@ -18,9 +18,9 @@ class Method implements MethodInterface { protected VisibilityEnum $visibility = VisibilityEnum::Public; - /** @var ParameterInterface[] $parameters */ + /** @var list $parameters */ protected array $parameters = []; - /** @var Inject[] $injects */ + /** @var list $injects */ protected array $injects = []; protected string $body = ''; protected string $comment = ''; @@ -79,6 +79,9 @@ public function getComment(): string return $this->comment; } + /** + * @return list + */ public function getInjects(): array { return $this->injects; @@ -94,6 +97,9 @@ public function isNullable(): bool return $this->nullable; } + /** + * @return list + */ public function getParameters(): array { return $this->parameters; diff --git a/src/Config.php b/src/Config.php index 3a3a6cf..e646473 100644 --- a/src/Config.php +++ b/src/Config.php @@ -8,6 +8,7 @@ use function array_key_exists; use function file_exists; +use function is_array; use function sprintf; class Config @@ -26,8 +27,8 @@ public function __construct( } $config = require $configPath; - if (! array_key_exists(Maker::class, $config)) { - throw new RuntimeException(sprintf('%s: key "Maker::class" not found', $configPath)); + if (! is_array($config) || ! array_key_exists(Maker::class, $config)) { + throw new RuntimeException(sprintf('%s: key "%s" not found', $configPath, Maker::class)); } } diff --git a/src/Context.php b/src/Context.php index d78a6d7..fa5d31a 100644 --- a/src/Context.php +++ b/src/Context.php @@ -4,16 +4,21 @@ namespace Dot\Maker; +use JsonException; use RuntimeException; -use function array_key_exists; +use function array_keys; use function explode; use function file_exists; use function file_get_contents; +use function is_array; +use function is_readable; use function json_decode; use function sprintf; use function str_starts_with; +use const JSON_THROW_ON_ERROR; + class Context { public const NAMESPACE_ADMIN = 'Admin'; @@ -23,9 +28,9 @@ class Context public const NAMESPACE_LIGHT = 'Light'; public const NAMESPACE_QUEUE = 'Queue'; - private bool $hasCore = false; - private ?string $projectType = null; - private ?string $rootNamespace = null; + private bool $hasCore = false; + private string $projectType; + private string $rootNamespace; /** * @throws RuntimeException @@ -38,29 +43,45 @@ public function __construct( throw new RuntimeException(sprintf('%s: not found', $composerPath)); } - $composer = json_decode(file_get_contents($composerPath), true); - if ($composer === null) { + if (! is_readable($composerPath)) { + throw new RuntimeException(sprintf('%s: not readable', $composerPath)); + } + + $contents = (string) file_get_contents($composerPath); + + try { + $composer = json_decode($contents, true, 512, JSON_THROW_ON_ERROR); + } catch (JsonException) { throw new RuntimeException(sprintf('%s: invalid JSON', $composerPath)); } - if (! array_key_exists('autoload', $composer)) { + if (! is_array($composer) || ! is_array($composer['autoload'] ?? null)) { throw new RuntimeException(sprintf('%s: key "autoload" not found', $composerPath)); } - if (! array_key_exists('psr-4', $composer['autoload'])) { + if (! is_array($composer['autoload']['psr-4'] ?? null)) { throw new RuntimeException(sprintf('%s: key "autoload"."psr-4" not found', $composerPath)); } + $rootNamespace = null; $coreNamespace = sprintf('%s\\', self::NAMESPACE_CORE); - foreach ($composer['autoload']['psr-4'] as $namespace => $modulePath) { + foreach (array_keys($composer['autoload']['psr-4']) as $namespace) { + $namespace = (string) $namespace; if (str_starts_with($namespace, $coreNamespace)) { $this->hasCore = true; continue; } - if ($this->rootNamespace === null) { - $namespace = explode('\\', $namespace, 2); - $this->rootNamespace = $namespace[0]; - $this->projectType = $namespace[0]; + if ($rootNamespace === null && $namespace !== '') { + $rootNamespace = explode('\\', $namespace, 2)[0]; } } + + if ($rootNamespace === null || $rootNamespace === '') { + throw new RuntimeException( + sprintf('%s: no application namespace found under "autoload"."psr-4"', $composerPath) + ); + } + + $this->rootNamespace = $rootNamespace; + $this->projectType = $rootNamespace; } public function getProjectPath(): string @@ -68,12 +89,12 @@ public function getProjectPath(): string return $this->projectPath; } - public function getProjectType(): ?string + public function getProjectType(): string { return $this->projectType; } - public function getRootNamespace(): ?string + public function getRootNamespace(): string { return $this->rootNamespace; } diff --git a/src/FileSystem.php b/src/FileSystem.php index 521cdd3..6b63e42 100644 --- a/src/FileSystem.php +++ b/src/FileSystem.php @@ -4,15 +4,15 @@ namespace Dot\Maker; +use Dot\Maker\Exception\RuntimeException; use Dot\Maker\FileSystem\Directory; use Dot\Maker\FileSystem\File; -use function preg_replace; use function sprintf; class FileSystem { - private string $moduleName; + private ?string $moduleName = null; public function __construct( private readonly Context $context, @@ -21,22 +21,22 @@ public function __construct( public function collection(string $name): File { - $name = preg_replace('/Collection$/', '', $name); + $name = Component::stripSuffix($name, 'Collection'); return new File( - new Directory('Collection', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Collection', $this->context->getRootNamespace(), $this->moduleName), + new Directory('Collection', $this->modulePath('src')), + sprintf('%s\\%s\\Collection', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('%sCollection', $name), ); } public function command(string $name): File { - $name = preg_replace('/Command$/', '', $name); + $name = Component::stripSuffix($name, 'Command'); return new File( - new Directory('Command', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Command', $this->context->getRootNamespace(), $this->moduleName), + new Directory('Command', $this->modulePath('src')), + sprintf('%s\\%s\\Command', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('%sCommand', $name), ); } @@ -44,8 +44,8 @@ public function command(string $name): File public function configProvider(string $name = 'ConfigProvider'): File { return new File( - new Directory('src', sprintf('%s/src/%s', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s', $this->context->getRootNamespace(), $this->moduleName), + new Directory('src', $this->modulePath()), + sprintf('%s\\%s', $this->context->getRootNamespace(), $this->getModuleName()), $name, ); } @@ -53,156 +53,151 @@ public function configProvider(string $name = 'ConfigProvider'): File public function coreConfigProvider(string $name = 'ConfigProvider'): File { return new File( - new Directory('src', sprintf('%s/src/Core/src/%s', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s', Context::NAMESPACE_CORE, $this->moduleName), + new Directory('src', $this->coreModulePath()), + sprintf('%s\\%s', Context::NAMESPACE_CORE, $this->getModuleName()), $name, ); } - public function coreModule(string $name): Directory - { - return new Directory($name, sprintf('%s/src/Core/src', $this->context->getProjectPath())); - } - public function entity(string $name): File { - $name = preg_replace('/Entity$/', '', $name); + $name = Component::stripSuffix($name, 'Entity'); if ($this->context->hasCore()) { return new File( new Directory( 'Entity', - sprintf('%s/src/Core/src/%s/src', $this->context->getProjectPath(), $this->moduleName) + $this->coreModulePath('src') ), - sprintf('%s\\%s\\Entity', Context::NAMESPACE_CORE, $this->moduleName), + sprintf('%s\\%s\\Entity', Context::NAMESPACE_CORE, $this->getModuleName()), $name, ); } return new File( - new Directory('Entity', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Entity', $this->context->getRootNamespace(), $this->moduleName), + new Directory('Entity', $this->modulePath('src')), + sprintf('%s\\%s\\Entity', $this->context->getRootNamespace(), $this->getModuleName()), $name, ); } public function form(string $name): File { - $name = preg_replace('/Form$/', '', $name); + $name = Component::stripSuffix($name, 'Form'); return new File( - new Directory('Form', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Form', $this->context->getRootNamespace(), $this->moduleName), + new Directory('Form', $this->modulePath('src')), + sprintf('%s\\%s\\Form', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('%sForm', $name), ); } public function createResourceForm(string $name): File { - $name = preg_replace('/Form$/', '', $name); + $name = Component::stripSuffix($name, 'Form'); return new File( - new Directory('Form', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Form', $this->context->getRootNamespace(), $this->moduleName), + new Directory('Form', $this->modulePath('src')), + sprintf('%s\\%s\\Form', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('Create%sForm', $name), ); } public function deleteResourceForm(string $name): File { - $name = preg_replace('/Form$/', '', $name); + $name = Component::stripSuffix($name, 'Form'); return new File( - new Directory('Form', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Form', $this->context->getRootNamespace(), $this->moduleName), + new Directory('Form', $this->modulePath('src')), + sprintf('%s\\%s\\Form', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('Delete%sForm', $name), ); } public function editResourceForm(string $name): File { - $name = preg_replace('/Form$/', '', $name); + $name = Component::stripSuffix($name, 'Form'); return new File( - new Directory('Form', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Form', $this->context->getRootNamespace(), $this->moduleName), + new Directory('Form', $this->modulePath('src')), + sprintf('%s\\%s\\Form', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('Edit%sForm', $name), ); } public function handler(string $name): File { - $name = preg_replace('/Handler$/', '', $name); + $name = Component::stripSuffix($name, 'Handler'); return new File( - new Directory('Handler', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory('Handler', $this->modulePath('src')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('%sHandler', $name), ); } public function apiDeleteResourceHandler(string $name): File { - $name = preg_replace('/Handler$/', '', $name); + $name = Component::stripSuffix($name, 'Handler'); return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('Delete%sResourceHandler', $name), ); } public function apiGetResourceHandler(string $name): File { - $name = preg_replace('/Handler$/', '', $name); + $name = Component::stripSuffix($name, 'Handler'); return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('Get%sResourceHandler', $name), ); } public function apiGetCollectionHandler(string $name): File { - $name = preg_replace('/Handler$/', '', $name); + $name = Component::stripSuffix($name, 'Handler'); return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('Get%sCollectionHandler', $name), ); } public function apiPatchResourceHandler(string $name): File { - $name = preg_replace('/Handler$/', '', $name); + $name = Component::stripSuffix($name, 'Handler'); return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('Patch%sResourceHandler', $name), ); } public function apiPostResourceHandler(string $name): File { - $name = preg_replace('/Handler$/', '', $name); + $name = Component::stripSuffix($name, 'Handler'); return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('Post%sResourceHandler', $name), ); } public function apiPutResourceHandler(string $name): File { - $name = preg_replace('/Handler$/', '', $name); + $name = Component::stripSuffix($name, 'Handler'); return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('Put%sResourceHandler', $name), ); } @@ -210,8 +205,8 @@ public function apiPutResourceHandler(string $name): File public function getCreateResourceHandler(string $name): File { return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('GetCreate%sFormHandler', $name), ); } @@ -219,8 +214,8 @@ public function getCreateResourceHandler(string $name): File public function getDeleteResourceHandler(string $name): File { return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('GetDelete%sFormHandler', $name), ); } @@ -228,8 +223,8 @@ public function getDeleteResourceHandler(string $name): File public function getEditResourceHandler(string $name): File { return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('GetEdit%sFormHandler', $name), ); } @@ -237,8 +232,8 @@ public function getEditResourceHandler(string $name): File public function getListResourcesHandler(string $name): File { return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('GetList%sHandler', $name), ); } @@ -246,8 +241,8 @@ public function getListResourcesHandler(string $name): File public function getViewResourceHandler(string $name): File { return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('GetView%sHandler', $name), ); } @@ -255,8 +250,8 @@ public function getViewResourceHandler(string $name): File public function postCreateResourceHandler(string $name): File { return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('PostCreate%sHandler', $name), ); } @@ -264,8 +259,8 @@ public function postCreateResourceHandler(string $name): File public function postDeleteResourceHandler(string $name): File { return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('PostDelete%sHandler', $name), ); } @@ -273,102 +268,102 @@ public function postDeleteResourceHandler(string $name): File public function postEditResourceHandler(string $name): File { return new File( - new Directory($name, sprintf('%s/src/%s/src/Handler', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->moduleName, $name), + new Directory($name, $this->modulePath('src/Handler')), + sprintf('%s\\%s\\Handler\\%s', $this->context->getRootNamespace(), $this->getModuleName(), $name), sprintf('PostEdit%sHandler', $name), ); } public function input(string $name): File { - $name = preg_replace('/Input$/', '', $name); + $name = Component::stripSuffix($name, 'Input'); return new File( new Directory( 'Input', - sprintf('%s/src/%s/src/InputFilter', $this->context->getProjectPath(), $this->moduleName) + $this->modulePath('src/InputFilter') ), - sprintf('%s\\%s\\InputFilter\\Input', $this->context->getRootNamespace(), $this->moduleName), + sprintf('%s\\%s\\InputFilter\\Input', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('%sInput', $name), ); } public function confirmDeleteInput(string $name): File { - $name = preg_replace('/Input$/', '', $name); + $name = Component::stripSuffix($name, 'Input'); return new File( new Directory( 'Input', - sprintf('%s/src/%s/src/InputFilter', $this->context->getProjectPath(), $this->moduleName) + $this->modulePath('src/InputFilter') ), - sprintf('%s\\%s\\InputFilter\\Input', $this->context->getRootNamespace(), $this->moduleName), + sprintf('%s\\%s\\InputFilter\\Input', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('ConfirmDelete%sInput', $name), ); } public function inputFilter(string $name): File { - $name = preg_replace('/InputFilter$/', '', $name); + $name = Component::stripSuffix($name, 'InputFilter'); return new File( - new Directory('InputFilter', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\InputFilter', $this->context->getRootNamespace(), $this->moduleName), + new Directory('InputFilter', $this->modulePath('src')), + sprintf('%s\\%s\\InputFilter', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('%sInputFilter', $name), ); } public function createResourceInputFilter(string $name): File { - $name = preg_replace('/InputFilter$/', '', $name); + $name = Component::stripSuffix($name, 'InputFilter'); return new File( - new Directory('InputFilter', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\InputFilter', $this->context->getRootNamespace(), $this->moduleName), + new Directory('InputFilter', $this->modulePath('src')), + sprintf('%s\\%s\\InputFilter', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('Create%sInputFilter', $name), ); } public function deleteResourceInputFilter(string $name): File { - $name = preg_replace('/InputFilter$/', '', $name); + $name = Component::stripSuffix($name, 'InputFilter'); return new File( - new Directory('InputFilter', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\InputFilter', $this->context->getRootNamespace(), $this->moduleName), + new Directory('InputFilter', $this->modulePath('src')), + sprintf('%s\\%s\\InputFilter', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('Delete%sInputFilter', $name), ); } public function editResourceInputFilter(string $name): File { - $name = preg_replace('/InputFilter$/', '', $name); + $name = Component::stripSuffix($name, 'InputFilter'); return new File( - new Directory('InputFilter', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\InputFilter', $this->context->getRootNamespace(), $this->moduleName), + new Directory('InputFilter', $this->modulePath('src')), + sprintf('%s\\%s\\InputFilter', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('Edit%sInputFilter', $name), ); } public function replaceResourceInputFilter(string $name): File { - $name = preg_replace('/InputFilter$/', '', $name); + $name = Component::stripSuffix($name, 'InputFilter'); return new File( - new Directory('InputFilter', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\InputFilter', $this->context->getRootNamespace(), $this->moduleName), + new Directory('InputFilter', $this->modulePath('src')), + sprintf('%s\\%s\\InputFilter', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('Replace%sInputFilter', $name), ); } public function middleware(string $name): File { - $name = preg_replace('/Middleware$/', '', $name); + $name = Component::stripSuffix($name, 'Middleware'); return new File( - new Directory('Middleware', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Middleware', $this->context->getRootNamespace(), $this->moduleName), + new Directory('Middleware', $this->modulePath('src')), + sprintf('%s\\%s\\Middleware', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('%sMiddleware', $name), ); } @@ -381,30 +376,30 @@ public function module(string $name): Directory public function openApi(string $name = 'OpenAPI'): File { return new File( - new Directory('src', sprintf('%s/src/%s', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s', $this->context->getRootNamespace(), $this->moduleName), + new Directory('src', $this->modulePath()), + sprintf('%s\\%s', $this->context->getRootNamespace(), $this->getModuleName()), $name, ); } public function repository(string $name): File { - $name = preg_replace('/Repository$/', '', $name); + $name = Component::stripSuffix($name, 'Repository'); if ($this->context->hasCore()) { return new File( new Directory( 'Repository', - sprintf('%s/src/Core/src/%s/src', $this->context->getProjectPath(), $this->moduleName) + $this->coreModulePath('src') ), - sprintf('%s\\%s\\Repository', Context::NAMESPACE_CORE, $this->moduleName), + sprintf('%s\\%s\\Repository', Context::NAMESPACE_CORE, $this->getModuleName()), sprintf('%sRepository', $name), ); } return new File( - new Directory('Repository', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Repository', $this->context->getRootNamespace(), $this->moduleName), + new Directory('Repository', $this->modulePath('src')), + sprintf('%s\\%s\\Repository', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('%sRepository', $name), ); } @@ -412,35 +407,31 @@ public function repository(string $name): File public function routesDelegator(string $name = 'RoutesDelegator'): File { return new File( - new Directory('src', sprintf('%s/src/%s', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s', $this->context->getRootNamespace(), $this->moduleName), + new Directory('src', $this->modulePath()), + sprintf('%s\\%s', $this->context->getRootNamespace(), $this->getModuleName()), $name, ); } public function service(string $name): File { - if ($name !== 'Service') { - $name = preg_replace('/Service$/', '', $name); - } + $name = Component::stripSuffix($name, 'Service'); return new File( - new Directory('Service', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Service', $this->context->getRootNamespace(), $this->moduleName), + new Directory('Service', $this->modulePath('src')), + sprintf('%s\\%s\\Service', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('%sService', $name), ); } public function serviceInterface(string $name): File { - $name = preg_replace('/Interface$/', '', $name); - if ($name !== 'Service') { - $name = preg_replace('/Service$/', '', $name); - } + $name = Component::stripSuffix($name, 'Interface'); + $name = Component::stripSuffix($name, 'Service'); return new File( - new Directory('Service', sprintf('%s/src/%s/src', $this->context->getProjectPath(), $this->moduleName)), - sprintf('%s\\%s\\Service', $this->context->getRootNamespace(), $this->moduleName), + new Directory('Service', $this->modulePath('src')), + sprintf('%s\\%s\\Service', $this->context->getRootNamespace(), $this->getModuleName()), sprintf('%sServiceInterface', $name), ); } @@ -449,7 +440,7 @@ public function templateDir(string $name): Directory { return new Directory( $name, - sprintf('%s/src/%s/templates', $this->context->getProjectPath(), $this->moduleName) + $this->modulePath('templates') ); } @@ -463,9 +454,32 @@ public function templateFile(string $subDirectory, string $name): File ); } + /** + * @throws RuntimeException + */ public function getModuleName(): string { - return $this->moduleName; + return $this->moduleName ?? throw new RuntimeException('No module selected.'); + } + + /** + * @throws RuntimeException + */ + private function modulePath(string $subPath = ''): string + { + $path = sprintf('%s/src/%s', $this->context->getProjectPath(), $this->getModuleName()); + + return $subPath === '' ? $path : sprintf('%s/%s', $path, $subPath); + } + + /** + * @throws RuntimeException + */ + private function coreModulePath(string $subPath = ''): string + { + $path = sprintf('%s/src/Core/src/%s', $this->context->getProjectPath(), $this->getModuleName()); + + return $subPath === '' ? $path : sprintf('%s/%s', $path, $subPath); } public function setModuleName(string $moduleName): self diff --git a/src/FileSystem/File.php b/src/FileSystem/File.php index 131ef6d..b2cc75a 100644 --- a/src/FileSystem/File.php +++ b/src/FileSystem/File.php @@ -91,6 +91,6 @@ public function read(): false|string public function write(string $data): bool { - return (bool) file_put_contents($this->path, $data); + return file_put_contents($this->path, $data) !== false; } } diff --git a/src/IO/Input.php b/src/IO/Input.php index 8e550dd..fe9dbeb 100644 --- a/src/IO/Input.php +++ b/src/IO/Input.php @@ -4,6 +4,7 @@ namespace Dot\Maker\IO; +use function feof; use function fgets; use function is_resource; use function sprintf; @@ -18,10 +19,22 @@ class Input /** @var resource $stream */ private static $stream = STDIN; + /** + * Returns an empty string on blank input and at the end of the input stream. + */ public static function prompt(string $prompt): string { Output::write(PHP_EOL . $prompt); - return trim((string) fgets(self::$stream)); + + return trim((string) fgets(self::getStream())); + } + + /** + * Whether the input stream has no more data, for example after Ctrl+D or at the end of piped input. + */ + public static function isExhausted(): bool + { + return feof(self::getStream()); } public static function confirm(string $prompt, string $default = 'yes'): bool diff --git a/src/IO/Output.php b/src/IO/Output.php index 16ecb33..3a05787 100644 --- a/src/IO/Output.php +++ b/src/IO/Output.php @@ -27,7 +27,7 @@ public static function error(string $message, bool $exit = false): void { $message = ColorEnum::colorize($message, ColorEnum::ForegroundBrightRed); - fwrite(self::$errorStream, $message . PHP_EOL); + fwrite(self::getErrorStream(), $message . PHP_EOL); $exit && exit(self::FAILURE); } @@ -35,7 +35,7 @@ public static function info(string $message, bool $exit = false): void { $message = ColorEnum::colorize($message, ColorEnum::ForegroundBrightBlue); - fwrite(self::$outputStream, $message . PHP_EOL); + fwrite(self::getOutputStream(), $message . PHP_EOL); $exit && exit(self::SUCCESS); } @@ -43,7 +43,7 @@ public static function success(string $message, bool $exit = false): void { $message = ColorEnum::colorize($message, ColorEnum::ForegroundBrightGreen); - fwrite(self::$outputStream, $message . PHP_EOL); + fwrite(self::getOutputStream(), $message . PHP_EOL); $exit && exit(self::SUCCESS); } @@ -51,19 +51,19 @@ public static function warning(string $message, bool $exit = false): void { $message = ColorEnum::colorize($message, ColorEnum::ForegroundBrightYellow); - fwrite(self::$outputStream, $message . PHP_EOL); + fwrite(self::getOutputStream(), $message . PHP_EOL); $exit && exit(self::SUCCESS); } public static function write(string $message = '', bool $exit = false): void { - fwrite(self::$outputStream, $message); + fwrite(self::getOutputStream(), $message); $exit && exit(self::SUCCESS); } public static function writeLine(string $message = '', bool $exit = false): void { - fwrite(self::$outputStream, $message . PHP_EOL); + fwrite(self::getOutputStream(), $message . PHP_EOL); $exit && exit(self::SUCCESS); } diff --git a/src/Maker.php b/src/Maker.php index 034009b..392d7f0 100644 --- a/src/Maker.php +++ b/src/Maker.php @@ -5,6 +5,7 @@ namespace Dot\Maker; use Dot\Maker\IO\Output; +use Dot\Maker\Type\Form; use Dot\Maker\Type\Help; use Dot\Maker\Type\Module; use Dot\Maker\Type\ModuleInterface; @@ -29,6 +30,9 @@ public function __construct( ) { } + /** + * @param list $arguments + */ public function __invoke(array $arguments): int { try { @@ -58,15 +62,24 @@ public function __invoke(array $arguments): int Output::info(sprintf('Detected project type: %s', $context->getProjectType())); Output::info(sprintf('Core architecture: %s', $context->hasCore() ? 'Yes' : 'No')); - if (! $instance->isModule()) { - $instance->setModule((new Module($fileSystem, $context, $config))->initExisting()); - } else { + if ($instance instanceof Form && $context->isApi()) { + throw new RuntimeException('Cannot create Forms in an API'); + } + + if ($instance->isModule()) { assert($instance instanceof ModuleInterface); $instance->setModule($instance); + assert(is_callable($instance)); + $instance(); + + return Output::SUCCESS; } - assert(is_callable($instance)); + $module = (new Module($fileSystem, $context, $config))->initExisting(); + $instance->setModule($module); + assert(is_callable($instance)); $instance(); + $module->renderMessages(); return Output::SUCCESS; } catch (Throwable $exception) { diff --git a/src/Type/AbstractType.php b/src/Type/AbstractType.php index db18cff..fd270f9 100644 --- a/src/Type/AbstractType.php +++ b/src/Type/AbstractType.php @@ -4,17 +4,59 @@ namespace Dot\Maker\Type; +use Dot\Maker\Component; use Dot\Maker\Component\Import; use Dot\Maker\Config; use Dot\Maker\Context; +use Dot\Maker\Exception\RuntimeException; use Dot\Maker\FileSystem; use Dot\Maker\Message; +use function in_array; +use function is_array; use function preg_match; use function sprintf; +use function strtolower; +use function token_get_all; + +use const T_STRING; abstract class AbstractType implements TypeInterface { + /** + * Type names that tokenize as T_STRING but cannot be used as class names. + */ + private const COMPONENT_SUFFIXES = [ + 'Collection', + 'Command', + 'Entity', + 'Form', + 'Handler', + 'Input', + 'InputFilter', + 'Interface', + 'Middleware', + 'Repository', + 'Service', + ]; + + private const RESERVED_TYPE_NAMES = [ + 'bool', + 'false', + 'float', + 'int', + 'iterable', + 'mixed', + 'never', + 'null', + 'object', + 'parent', + 'self', + 'string', + 'true', + 'void', + ]; + protected Import $import; public function __construct( @@ -26,8 +68,15 @@ public function __construct( $this->import = new Import($context); } + /** + * @throws RuntimeException + */ public function addMessage(Message $message): static { + if ($this->module === null) { + throw new RuntimeException('No module selected.'); + } + $this->module->addMessage($message); return $this; @@ -58,14 +107,22 @@ public function hasModule(): bool return $this->module instanceof ModuleInterface; } + /** + * @throws RuntimeException + */ public function component(TypeEnum $typeEnum): FileInterface { - return new ($typeEnum->value)( + $component = new ($typeEnum->value)( $this->fileSystem, $this->context, $this->config, $this->module, ); + if (! $component instanceof FileInterface) { + throw new RuntimeException(sprintf('%s cannot create files.', $typeEnum->value)); + } + + return $component; } public function isModule(): bool @@ -73,9 +130,35 @@ public function isModule(): bool return false; } + /** + * A valid name is a usable PHP class name, both as typed and with any component suffix removed, + * because some components (for example Entity) use the name without its suffix as the class name. + */ public function isValid(string $name): bool { - return (bool) preg_match('/^[a-z0-9]+$/i', $name); + foreach (self::COMPONENT_SUFFIXES as $suffix) { + if (! self::isClassName(Component::stripSuffix($name, $suffix))) { + return false; + } + } + + return self::isClassName($name); + } + + private static function isClassName(string $name): bool + { + if (preg_match('/^[a-z][a-z0-9]*$/i', $name) !== 1) { + return false; + } + + if (in_array(strtolower($name), self::RESERVED_TYPE_NAMES, true)) { + return false; + } + + // Rejects every keyword known to the running PHP version, for example List, Class, Match or Readonly. + $tokens = token_get_all('toKebabCase()); + $kebabCase = $command->toKebabCase(); + if (str_ends_with($kebabCase, '-command')) { + $kebabCase = substr($kebabCase, 0, -strlen('-command')); + } - return str_replace('-command', '', $defaultName); + return sprintf('%s:command', $kebabCase); } } diff --git a/src/Type/ConfigProvider.php b/src/Type/ConfigProvider.php index 96c6d90..9eb826e 100644 --- a/src/Type/ConfigProvider.php +++ b/src/Type/ConfigProvider.php @@ -90,6 +90,7 @@ public function create(string $name): File /** * @param File[] $handlers + * @param File[] $forms */ public function render( Component $configProvider, diff --git a/src/Type/Entity.php b/src/Type/Entity.php index 6966571..731906a 100644 --- a/src/Type/Entity.php +++ b/src/Type/Entity.php @@ -117,6 +117,9 @@ public function render(Component $entity, Component $repository): string return $class->render(); } + /** + * @return non-empty-string + */ public function getAbstractEntityFqcn(): string { $format = Import::ROOT_APP_ENTITY_ABSTRACTENTITY; @@ -128,17 +131,9 @@ public function getAbstractEntityFqcn(): string return sprintf($format, $this->context->getRootNamespace()); } - public function getNumericIdentifierTraitFqcn(): string - { - $format = Import::ROOT_APP_ENTITY_NUMERICIDENTIFIERTRAIT; - - if ($this->context->hasCore()) { - return sprintf($format, Context::NAMESPACE_CORE); - } - - return sprintf($format, $this->context->getRootNamespace()); - } - + /** + * @return non-empty-string + */ public function getTimestampsTraitFqcn(): string { $format = Import::ROOT_APP_ENTITY_TIMESTAMPSTRAIT; @@ -150,6 +145,9 @@ public function getTimestampsTraitFqcn(): string return sprintf($format, $this->context->getRootNamespace()); } + /** + * @return non-empty-string + */ public function getUuidIdentifierTraitFqcn(): string { $format = Import::ROOT_APP_ENTITY_UUIDIDENTIFIERTRAIT; diff --git a/src/Type/FileInterface.php b/src/Type/FileInterface.php index 50bb955..966bea3 100644 --- a/src/Type/FileInterface.php +++ b/src/Type/FileInterface.php @@ -16,5 +16,5 @@ interface FileInterface * @throws DuplicateFileException * @throws RuntimeException */ - public function create(string $name): ?File; + public function create(string $name): File; } diff --git a/src/Type/Form.php b/src/Type/Form.php index 434b563..d039663 100644 --- a/src/Type/Form.php +++ b/src/Type/Form.php @@ -10,7 +10,6 @@ use Dot\Maker\IO\Output; use Throwable; -use function preg_replace; use function sprintf; use function ucfirst; @@ -44,7 +43,7 @@ public function __invoke(): void public function create(string $name): File { - $name = preg_replace('/Form$/', '', $name); + $name = Component::stripSuffix($name, 'Form'); $form = $this->fileSystem->form($name); if ($this->context->isApi()) { diff --git a/src/Type/Handler.php b/src/Type/Handler.php index 3737fca..d887c4a 100644 --- a/src/Type/Handler.php +++ b/src/Type/Handler.php @@ -10,7 +10,6 @@ use Dot\Maker\IO\Output; use Throwable; -use function preg_replace; use function sprintf; use function ucfirst; @@ -39,7 +38,7 @@ public function __invoke(): void public function create(string $name): File { - $name = preg_replace('/Handler$/', '', $name); + $name = Component::stripSuffix($name, 'Handler'); $entity = $this->fileSystem->entity($name); diff --git a/src/Type/Handler/GetDeleteResourceHandler.php b/src/Type/Handler/GetDeleteResourceHandler.php index 01c4fe9..75f9ad5 100644 --- a/src/Type/Handler/GetDeleteResourceHandler.php +++ b/src/Type/Handler/GetDeleteResourceHandler.php @@ -118,7 +118,7 @@ public function render(Component $handler, Component $entity, Component $form, C return new HtmlResponse( \$this->template->render('{$entity->toKebabCase()}::delete-{$entity->toKebabCase()}-form', [ 'form' => \$this->{$form->toCamelCase()}->prepare(), - '{$entity->toKebabCase()}' => {$entity->getVariable()}, + '{$entity->toCamelCase()}' => {$entity->getVariable()}, ]) ); BODY); diff --git a/src/Type/Handler/GetEditResourceHandler.php b/src/Type/Handler/GetEditResourceHandler.php index a4de240..78f3679 100644 --- a/src/Type/Handler/GetEditResourceHandler.php +++ b/src/Type/Handler/GetEditResourceHandler.php @@ -120,7 +120,7 @@ public function render(Component $handler, Component $entity, Component $form, C return new HtmlResponse( \$this->template->render('{$entity->toKebabCase()}::edit-{$entity->toKebabCase()}-form', [ 'form' => \$this->{$form->toCamelCase()}->prepare(), - '{$entity->toKebabCase()}' => {$entity->getVariable()}, + '{$entity->toCamelCase()}' => {$entity->getVariable()}, ]) ); BODY); diff --git a/src/Type/InputFilter.php b/src/Type/InputFilter.php index 45aad85..6b81864 100644 --- a/src/Type/InputFilter.php +++ b/src/Type/InputFilter.php @@ -10,7 +10,6 @@ use Dot\Maker\IO\Output; use Throwable; -use function preg_replace; use function sprintf; use function ucfirst; @@ -39,7 +38,7 @@ public function __invoke(): void public function create(string $name): File { - $name = preg_replace('/InputFilter$/', '', $name); + $name = Component::stripSuffix($name, 'InputFilter'); $plural = Component::pluralize($name); if ($this->context->isApi()) { diff --git a/src/Type/Module.php b/src/Type/Module.php index e89b3e3..c341b1d 100644 --- a/src/Type/Module.php +++ b/src/Type/Module.php @@ -4,6 +4,7 @@ namespace Dot\Maker\Type; +use Dot\Maker\Exception\RuntimeException; use Dot\Maker\IO\Input; use Dot\Maker\IO\Output; use Dot\Maker\Message; @@ -16,6 +17,7 @@ class Module extends AbstractType implements ModuleInterface { + /** @var array> $messages priority => message => message */ protected array $messages = []; public function __invoke(): void @@ -112,11 +114,16 @@ public function __invoke(): void public function addMessage(Message $message): static { - $this->messages[$message->getPriority()] = (string) $message; + $text = (string) $message; + + $this->messages[$message->getPriority()][$text] = $text; return $this; } + /** + * @return array> + */ public function getMessages(): array { return $this->messages; @@ -126,6 +133,9 @@ public function initExisting(): self { while (true) { $name = ucfirst(Input::prompt('Existing module name: ')); + if ($name === '' && Input::isExhausted()) { + throw new RuntimeException('No module name given before the end of input.'); + } if (! $this->isValid($name)) { Output::error(sprintf('Invalid module name: "%s"', $name)); continue; @@ -163,8 +173,10 @@ public function renderMessages(): void Output::warning('==========='); ksort($this->messages); - foreach ($this->messages as $message) { - Output::writeLine(sprintf('- %s', $message)); + foreach ($this->messages as $messages) { + foreach ($messages as $message) { + Output::writeLine(sprintf('- %s', $message)); + } } } } diff --git a/test/BinTest.php b/test/BinTest.php new file mode 100644 index 0000000..f9ab0fd --- /dev/null +++ b/test/BinTest.php @@ -0,0 +1,71 @@ +runBin('nonsense'); + + $this->assertSame(1, $exitCode); + $this->assertStringContainsString('Unknown component: "nonsense"', $stderr); + } + + public function testHelpExitsWithSuccess(): void + { + [$exitCode] = $this->runBin(''); + + $this->assertSame(0, $exitCode); + } + + /** + * @return array{int, string} + */ + private function runBin(string $component): array + { + $repository = dirname(__DIR__); + $project = $this->createTempDirectory(); + mkdir($project . '/vendor'); + file_put_contents( + $project . '/vendor/autoload.php', + sprintf(' ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, $project); + $this->assertIsResource($process); + + stream_get_contents($pipes[1]); + $stderr = (string) stream_get_contents($pipes[2]); + + return [proc_close($process), $stderr]; + } +} diff --git a/test/ColorEnumTest.php b/test/ColorEnumTest.php index 87f94d5..531a7dc 100644 --- a/test/ColorEnumTest.php +++ b/test/ColorEnumTest.php @@ -9,18 +9,19 @@ use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function rewind; use function stream_get_contents; class ColorEnumTest extends TestCase { + use StreamTrait; + /** @var resource $outputStream */ private $outputStream; protected function setUp(): void { - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); } diff --git a/test/Component/ArrayAlignerTest.php b/test/Component/ArrayAlignerTest.php new file mode 100644 index 0000000..c8fbfd2 --- /dev/null +++ b/test/Component/ArrayAlignerTest.php @@ -0,0 +1,99 @@ + $form, + 'bookStore' => $bookStore, + 'messages' => [ + 'error' => $message, + ], + ]; + PHP; + + $expected = <<<'PHP' + return [ + 'form' => $form, + 'bookStore' => $bookStore, + 'messages' => [ + 'error' => $message, + ], + ]; + PHP; + + $this->assertSame($expected, ArrayAligner::align($code)); + } + + public function testAlignsEachNestingLevelSeparately(): void + { + $code = <<<'PHP' + return [ + 'driver' => [ + 'orm_default' => [ + 'drivers' => [ + 'Core\Book\Entity' => 'BookEntities', + ], + ], + 'BookEntities' => [ + 'class' => AttributeDriver::class, + 'paths' => [__DIR__ . '/Entity'], + ], + ], + ]; + PHP; + + $expected = <<<'PHP' + return [ + 'driver' => [ + 'orm_default' => [ + 'drivers' => [ + 'Core\Book\Entity' => 'BookEntities', + ], + ], + 'BookEntities' => [ + 'class' => AttributeDriver::class, + 'paths' => [__DIR__ . '/Entity'], + ], + ], + ]; + PHP; + + $this->assertSame($expected, ArrayAligner::align($code)); + } + + public function testAlignsClassConstantKeysAndIgnoresBracketsInStrings(): void + { + $code = <<<'PHP' + $config = [ + BookRepository::class => Factory::class, + 'x' => '[not an array', + ]; + PHP; + + $expected = <<<'PHP' + $config = [ + BookRepository::class => Factory::class, + 'x' => '[not an array', + ]; + PHP; + + $this->assertSame($expected, ArrayAligner::align($code)); + } + + public function testLeavesCodeWithoutArraysUnchanged(): void + { + $code = "\$a = foo(['id' => 1]);\n\$b = 2;\n"; + + $this->assertSame($code, ArrayAligner::align($code)); + } +} diff --git a/test/Component/ClassFileTest.php b/test/Component/ClassFileTest.php index 1693d11..d1e23a4 100644 --- a/test/Component/ClassFileTest.php +++ b/test/Component/ClassFileTest.php @@ -11,6 +11,7 @@ use Dot\Maker\Component\PromotedProperty; use Dot\Maker\Component\Property; use Dot\Maker\VisibilityEnum; +use InvalidArgumentException; use PHPUnit\Framework\TestCase; class ClassFileTest extends TestCase @@ -161,10 +162,10 @@ public function testWillRenderClass(): void ->appendBody('// add logic') ); - $this->assertSame($this->dataProviderRenderedClass(), (string) $actual); + $this->assertSame($this->expectedRenderedClass(), (string) $actual); } - private function dataProviderRenderedClass(): string + private function expectedRenderedClass(): string { return <<expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Name must not be empty.'); + + (new ClassFile('App\Module', 'ClassName'))->addMethod(new Method('')); + } + + public function testAddPropertyWithEmptyNameThrows(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Name must not be empty.'); + + (new ClassFile('App\Module', 'ClassName'))->addProperty(new Property('', 'string')); + } } diff --git a/test/Component/DeclarationTest.php b/test/Component/DeclarationTest.php index 9f24bbd..fcaf9f0 100644 --- a/test/Component/DeclarationTest.php +++ b/test/Component/DeclarationTest.php @@ -109,10 +109,10 @@ public function testWillRender(): void ->addParameter( new Parameter('param', 'string') ); - $this->assertSame($this->dataProviderRenderedDeclaration(), (string) $declaration); + $this->assertSame($this->expectedRenderedDeclaration(), (string) $declaration); } - private function dataProviderRenderedDeclaration(): string + private function expectedRenderedDeclaration(): string { return <<addDeclaration((new Declaration('getResource'))->setReturnType('Resource')); - $this->assertSame($this->dataProviderRenderedClass(), (string) $actual); + $this->assertSame($this->expectedRenderedClass(), (string) $actual); } - private function dataProviderRenderedClass(): string + private function expectedRenderedClass(): string { return <<expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Name must not be empty.'); + + (new InterfaceFile('App\Module', 'InterfaceName'))->addDeclaration(new Declaration('')); + } } diff --git a/test/Component/Method/ConstructorTest.php b/test/Component/Method/ConstructorTest.php index fa27a78..850bbda 100644 --- a/test/Component/Method/ConstructorTest.php +++ b/test/Component/Method/ConstructorTest.php @@ -58,10 +58,10 @@ public function testWillRender(): void ) ->setBody(' // do stuff'); - $this->assertSame($this->dataProviderRenderedMethod(), $constructor->render()); + $this->assertSame($this->expectedRenderedMethod(), $constructor->render()); } - private function dataProviderRenderedMethod(): string + private function expectedRenderedMethod(): string { return <<methodName)) ->setVisibility(VisibilityEnum::Private) ->setNullable(false); - $this->assertSame($this->dataProviderRenderedMethodWithoutBody(), (string) $method); + $this->assertSame($this->expectedRenderedMethodWithoutBody(), (string) $method); } public function testWillRenderMethod(): void @@ -129,10 +129,10 @@ public function testWillRenderMethod(): void COMM) ->addParameter(new Parameter('param', 'string', true, 'null')) ->setBody(' return $this;'); - $this->assertSame($this->dataProviderRenderedMethod(), (string) $method); + $this->assertSame($this->expectedRenderedMethod(), (string) $method); } - private function dataProviderRenderedMethodWithoutBody(): string + private function expectedRenderedMethodWithoutBody(): string { return <<assertSame('', (new Method('method'))->renderParameters()); + } } diff --git a/test/Component/PromotedPropertyTest.php b/test/Component/PromotedPropertyTest.php index cce09ea..09f64fd 100644 --- a/test/Component/PromotedPropertyTest.php +++ b/test/Component/PromotedPropertyTest.php @@ -29,10 +29,10 @@ public function testWillRender(): void ->setReadonly(true) ->setStatic(true) ->setComment($comment); - $this->assertSame($this->dataProviderRenderedPromotedProperty(), $promotedProperty->render()); + $this->assertSame($this->expectedRenderedPromotedProperty(), $promotedProperty->render()); } - private function dataProviderRenderedPromotedProperty(): string + private function expectedRenderedPromotedProperty(): string { return <<setReadonly(true) ->setStatic(true) ->setComment($comment); - $this->assertSame($this->dataProviderRenderedProperty(), $property->render()); + $this->assertSame($this->expectedRenderedProperty(), $property->render()); } - private function dataProviderRenderedProperty(): string + private function expectedRenderedProperty(): string { return <<assertSame('candies', Component::pluralize('candy')); $this->assertSame('books', Component::pluralize('book')); } + + public function testPluralizeEmptyStringReturnsEmptyString(): void + { + $this->assertSame('', Component::pluralize('')); + } + + public function testStripSuffix(): void + { + $this->assertSame('Book', Component::stripSuffix('BookEntity', 'Entity')); + $this->assertSame('Entity', Component::stripSuffix('Entity', 'Entity')); + $this->assertSame('Book', Component::stripSuffix('Book', 'Entity')); + $this->assertSame('EntityBook', Component::stripSuffix('EntityBook', 'Entity')); + } + + public function testEmptyClassNameIsRejected(): void + { + $this->expectException(InvalidArgumentException::class); + + new Component('Api\Book', ''); + } + + public function testToCamelCaseStripsInterfaceSuffixOnly(): void + { + $this->assertSame('bookService', (new Component('A', 'BookServiceInterface'))->toCamelCase(true)); + $this->assertSame('interfaceBook', (new Component('A', 'InterfaceBook'))->toCamelCase(true)); + } } diff --git a/test/ConfigTest.php b/test/ConfigTest.php index f0b3f32..417b519 100644 --- a/test/ConfigTest.php +++ b/test/ConfigTest.php @@ -5,6 +5,7 @@ namespace DotTest\Maker; use Dot\Maker\Config; +use Dot\Maker\Maker; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; @@ -35,9 +36,25 @@ public function testConfigFileWithoutMakerKeyWillThrowError(): void ]); $this->expectExceptionMessage( - sprintf('%s/%s: key "Maker::class" not found', $fileSystem->url(), Config::CONFIG_FILE) + sprintf('%s/%s: key "%s" not found', $fileSystem->url(), Config::CONFIG_FILE, Maker::class) ); $config = new Config($fileSystem->url()); $this->assertContainsOnlyInstancesOf(Config::class, [$config]); } + + public function testConfigFileReturningNonArrayWillThrowError(): void + { + $fileSystem = vfsStream::setup('root', 0644, [ + 'config' => [ + 'autoload' => [ + 'maker.local.php' => 'expectExceptionMessage( + sprintf('%s/%s: key "%s" not found', $fileSystem->url(), Config::CONFIG_FILE, Maker::class) + ); + new Config($fileSystem->url()); + } } diff --git a/test/ContextTest.php b/test/ContextTest.php index 6c21984..028cb8b 100644 --- a/test/ContextTest.php +++ b/test/ContextTest.php @@ -195,4 +195,49 @@ public function testWillDetectProjectTypeQueue(): void $this->assertTrue($context->isQueue()); $this->assertSame(Context::NAMESPACE_QUEUE, $context->getProjectType()); } + + public function testWillNotInstantiateWithScalarComposerJson(): void + { + $fileSystem = vfsStream::setup('root', 0644, [ + 'composer.json' => '1', + ]); + $this->expectExceptionMessage(sprintf('%s/composer.json: key "autoload" not found', $fileSystem->url())); + + new Context($fileSystem->url()); + } + + public function testWillNotInstantiateWhenAutoloadIsNotAnObject(): void + { + $fileSystem = vfsStream::setup('root', 0644, [ + 'composer.json' => '{"autoload":"x"}', + ]); + $this->expectExceptionMessage(sprintf('%s/composer.json: key "autoload" not found', $fileSystem->url())); + + new Context($fileSystem->url()); + } + + public function testWillNotInstantiateWithOnlyCoreNamespaces(): void + { + $fileSystem = vfsStream::setup('root', 0644, [ + 'composer.json' => '{"autoload":{"psr-4":{"Core\\\\App\\\\":"src/Core/src/App/src/"}}}', + ]); + $this->expectExceptionMessage( + sprintf('%s/composer.json: no application namespace found under "autoload"."psr-4"', $fileSystem->url()) + ); + + new Context($fileSystem->url()); + } + + public function testWillNotInstantiateWithUnreadableComposerJson(): void + { + $fileSystem = vfsStream::setup('root', 0755, [ + 'composer.json' => '{}', + ]); + $composer = $fileSystem->getChild('composer.json'); + $this->assertNotNull($composer); + $composer->chmod(0000); + $this->expectExceptionMessage(sprintf('%s/composer.json: not readable', $fileSystem->url())); + + new Context($fileSystem->url()); + } } diff --git a/test/FileSystem/FileTest.php b/test/FileSystem/FileTest.php index 2d186a7..e4886de 100644 --- a/test/FileSystem/FileTest.php +++ b/test/FileSystem/FileTest.php @@ -8,15 +8,11 @@ use Dot\Maker\FileSystem\Directory; use Dot\Maker\FileSystem\File; use org\bovigo\vfs\vfsStream; -use org\bovigo\vfs\vfsStreamContent; use org\bovigo\vfs\vfsStreamDirectory; use PHPUnit\Framework\TestCase; use function sprintf; -/** - * @method vfsStreamContent getChild(string $name) - */ class FileTest extends TestCase { private vfsStreamDirectory $root; @@ -50,12 +46,12 @@ public function testFailingToCreateWillThrowAnError(): void $file = $this->getMockBuilder(File::class) ->onlyMethods(['write']) ->setConstructorArgs([ - new Directory('src', $this->root->getChild('src')->getChild('App')->url()), + new Directory('src', $this->root->url() . '/src/App'), 'Api\\App', 'ConfigProvider', ]) ->getMock(); - $file->method('write')->willReturn(false); + $file->expects($this->once())->method('write')->willReturn(false); $this->assertFileDoesNotExist($file->getPath()); $this->assertFalse($file->exists()); @@ -69,7 +65,7 @@ public function testFailingToCreateWillThrowAnError(): void public function testWillCreate(): void { $file = new File( - new Directory('src', $this->root->getChild('src')->getChild('App')->url()), + new Directory('src', $this->root->url() . '/src/App'), 'Api\\App', 'ConfigProvider' ); @@ -98,7 +94,7 @@ public function testWillThrowAnErrorIfCannotCreateParentDirectory(): void public function testWillDetectExistingFile(): void { $file = new File( - new Directory('src', $this->root->getChild('src')->getChild('App')->url()), + new Directory('src', $this->root->url() . '/src/App'), 'Api\\App', 'Existing' ); @@ -112,7 +108,7 @@ public function testWillGetParentDirectory(): void 'Test', 'Test' ); - $this->assertSame($this->root->getChild('src')->url(), $file->getParentDirectory()->getPath()); + $this->assertSame($this->root->url() . '/src', $file->getParentDirectory()->getPath()); } public function testWillGetComponent(): void @@ -138,13 +134,23 @@ public function testWillGetName(): void public function testWillGetPath(): void { $file = new File( - new Directory('src', $this->root->getChild('src')->getChild('App')->url()), + new Directory('src', $this->root->url() . '/src/App'), 'Api\\App', 'Existing' ); $this->assertSame( - $this->root->getChild('src')->getChild('App')->getChild('src')->getChild('Existing.php')->url(), + $this->root->url() . '/src/App/src/Existing.php', $file->getPath() ); } + + public function testCreateWithEmptyContentSucceeds(): void + { + $file = new File(new Directory('src', $this->root->url() . '/src/App'), 'Api\App', 'Empty'); + + $file->create(''); + + $this->assertFileExists($file->getPath()); + $this->assertSame('', $file->read()); + } } diff --git a/test/FileSystemTest.php b/test/FileSystemTest.php new file mode 100644 index 0000000..0350bdb --- /dev/null +++ b/test/FileSystemTest.php @@ -0,0 +1,55 @@ + '{"autoload":{"psr-4":{"Api\\\\App\\\\":"src/App/src/"}}}', + ]); + + $this->fileSystem = new FileSystem(new Context($root->url())); + } + + public function testGetModuleNameBeforeSetModuleNameThrows(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('No module selected.'); + + $this->fileSystem->getModuleName(); + } + + public function testNameEqualToSuffixKeepsTheName(): void + { + $this->fileSystem->setModuleName('Book'); + + $this->assertSame('Entity', $this->fileSystem->entity('Entity')->getComponent()->getClassName()); + $this->assertSame('Book', $this->fileSystem->entity('BookEntity')->getComponent()->getClassName()); + $this->assertSame('CommandCommand', $this->fileSystem->command('Command')->getComponent()->getClassName()); + $this->assertSame('BookCommand', $this->fileSystem->command('BookCommand')->getComponent()->getClassName()); + } + + public function testServiceNamesStripTheirSuffixes(): void + { + $this->fileSystem->setModuleName('Book'); + + $this->assertSame('BookService', $this->fileSystem->service('BookService')->getComponent()->getClassName()); + $this->assertSame('ServiceService', $this->fileSystem->service('Service')->getComponent()->getClassName()); + $this->assertSame( + 'BookServiceInterface', + $this->fileSystem->serviceInterface('BookServiceInterface')->getComponent()->getClassName() + ); + } +} diff --git a/test/GeneratedCodeStyleTest.php b/test/GeneratedCodeStyleTest.php new file mode 100644 index 0000000..94d21d3 --- /dev/null +++ b/test/GeneratedCodeStyleTest.php @@ -0,0 +1,83 @@ +createTempDirectory(); + mkdir($project . '/src', 0777, true); + $psr4 = [$projectType . '\\App\\' => 'src/App/src/']; + if ($withCore) { + mkdir($project . '/src/Core/src', 0777, true); + $psr4['Core\\App\\'] = 'src/Core/src/App/src/'; + } + $composer = json_encode(['autoload' => ['psr-4' => $psr4]], JSON_THROW_ON_ERROR); + file_put_contents($project . '/composer.json', $composer); + + Output::setOutputStream($this->openMemoryStream()); + Output::setErrorStream($this->openMemoryStream()); + $input = $this->openMemoryStream(); + // Module name, then every confirmation answered with its default (yes) at the end of input. + fwrite($input, 'Bookcase' . PHP_EOL); + rewind($input); + Input::setStream($input); + + $this->assertSame(Output::SUCCESS, (new Maker($project))(['dot-maker', 'module'])); + + $repository = dirname(__DIR__); + $command = sprintf( + '%s %s --standard=LaminasCodingStandard --no-cache -q --report=emacs %s 2>&1', + escapeshellarg(PHP_BINARY), + escapeshellarg($repository . '/vendor/bin/phpcs'), + escapeshellarg($project . '/src') + ); + exec($command, $report, $exitCode); + + $this->assertSame(0, $exitCode, implode(PHP_EOL, $report)); + } + + /** + * @return array + */ + public static function projectProvider(): array + { + return [ + 'Api with Core' => ['Api', true], + 'Api without Core' => ['Api', false], + 'Admin with Core' => ['Admin', true], + 'Admin without Core' => ['Admin', false], + ]; + } +} diff --git a/test/IO/InputTest.php b/test/IO/InputTest.php index dbe83e7..ccd4b48 100644 --- a/test/IO/InputTest.php +++ b/test/IO/InputTest.php @@ -6,47 +6,41 @@ use Dot\Maker\IO\Input; use Dot\Maker\IO\Output; +use DotTest\Maker\StreamTrait; +use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function fwrite; use function rewind; use function stream_get_contents; -use function stream_get_meta_data; use const PHP_EOL; +use const STDIN; class InputTest extends TestCase { + use StreamTrait; + public function testWillModifyInputStream(): void { - $oldStream = Input::getStream(); - $this->assertIsResource($oldStream); - $oldMetadata = stream_get_meta_data($oldStream); - $this->assertSame('STDIO', $oldMetadata['stream_type']); - $this->assertSame('php://stdin', $oldMetadata['uri']); - - Input::setStream(fopen('php://memory', 'w+')); - - $newStream = Input::getStream(); - $this->assertIsResource($oldStream); - $newMetadata = stream_get_meta_data($newStream); - $this->assertSame('MEMORY', $newMetadata['stream_type']); - $this->assertSame('php://memory', $newMetadata['uri']); + $this->resetStreams(); + $this->assertSame(STDIN, Input::getStream()); - $this->assertNotSame($oldStream, $newStream); + $stream = $this->openMemoryStream(); + Input::setStream($stream); + $this->assertSame($stream, Input::getStream()); - fclose($oldStream); - fclose($newStream); + fclose($stream); + $this->resetStreams(); } public function testPromptWillOutputMessageAndReadInput(): void { - $outputStream = fopen('php://memory', 'w+'); + $outputStream = $this->openMemoryStream(); Output::setOutputStream($outputStream); - $inputStream = fopen('php://memory', 'w+'); + $inputStream = $this->openMemoryStream(); fwrite($inputStream, 'Test' . PHP_EOL); rewind($inputStream); Input::setStream($inputStream); @@ -60,19 +54,17 @@ public function testPromptWillOutputMessageAndReadInput(): void fclose($outputStream); } - /** - * @testWith [""] - * ["y"] - * ["yes"] - * ["Y"] - * ["Yes"] - */ + #[TestWith([''])] + #[TestWith(['y'])] + #[TestWith(['yes'])] + #[TestWith(['Y'])] + #[TestWith(['Yes'])] public function testConfirmWillOutputMessageAndReadPositiveAnswer(string $input): void { - $outputStream = fopen('php://memory', 'w+'); + $outputStream = $this->openMemoryStream(); Output::setOutputStream($outputStream); - $inputStream = fopen('php://memory', 'w+'); + $inputStream = $this->openMemoryStream(); fwrite($inputStream, $input . PHP_EOL); rewind($inputStream); Input::setStream($inputStream); @@ -86,19 +78,17 @@ public function testConfirmWillOutputMessageAndReadPositiveAnswer(string $input) fclose($outputStream); } - /** - * @testWith [""] - * ["n"] - * ["no"] - * ["N"] - * ["No"] - */ + #[TestWith([''])] + #[TestWith(['n'])] + #[TestWith(['no'])] + #[TestWith(['N'])] + #[TestWith(['No'])] public function testConfirmWillOutputMessageAndReadNegativeAnswer(string $input): void { - $outputStream = fopen('php://memory', 'w+'); + $outputStream = $this->openMemoryStream(); Output::setOutputStream($outputStream); - $inputStream = fopen('php://memory', 'w+'); + $inputStream = $this->openMemoryStream(); fwrite($inputStream, $input . PHP_EOL); rewind($inputStream); Input::setStream($inputStream); @@ -114,7 +104,7 @@ public function testConfirmWillOutputMessageAndReadNegativeAnswer(string $input) public function testWillAlwaysGetInputStream(): void { - Input::setStream(fopen('php://memory', 'w+')); + Input::setStream($this->openMemoryStream()); $stream = Input::getStream(); $this->assertIsResource($stream); @@ -123,4 +113,25 @@ public function testWillAlwaysGetInputStream(): void $stream = Input::getStream(); $this->assertIsResource($stream); } + + public function testPromptReturnsEmptyStringAtEndOfInput(): void + { + Output::setOutputStream($this->openMemoryStream()); + Input::setStream($this->openMemoryStream()); + + $this->assertSame('', Input::prompt('Name: ')); + $this->assertTrue(Input::isExhausted()); + } + + public function testIsExhaustedIsFalseWhileInputRemains(): void + { + Output::setOutputStream($this->openMemoryStream()); + $stream = $this->openMemoryStream(); + fwrite($stream, 'Book' . PHP_EOL . PHP_EOL); + rewind($stream); + Input::setStream($stream); + + $this->assertSame('Book', Input::prompt('Name: ')); + $this->assertFalse(Input::isExhausted()); + } } diff --git a/test/IO/OutputTest.php b/test/IO/OutputTest.php index 67f9b80..14e7d9e 100644 --- a/test/IO/OutputTest.php +++ b/test/IO/OutputTest.php @@ -6,65 +6,50 @@ use Dot\Maker\ColorEnum; use Dot\Maker\IO\Output; +use DotTest\Maker\StreamTrait; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function rewind; use function stream_get_contents; -use function stream_get_meta_data; use const PHP_EOL; +use const STDERR; +use const STDOUT; class OutputTest extends TestCase { + use StreamTrait; + public function testWillModifyErrorStream(): void { - $oldErrorStream = Output::getErrorStream(); - $this->assertIsResource($oldErrorStream); - $oldErrorStreamMetadata = stream_get_meta_data($oldErrorStream); - $this->assertSame('STDIO', $oldErrorStreamMetadata['stream_type']); - $this->assertSame('php://stderr', $oldErrorStreamMetadata['uri']); - - Output::setErrorStream(fopen('php://memory', 'w+')); + $this->resetStreams(); + $this->assertSame(STDERR, Output::getErrorStream()); - $newErrorStream = Output::getErrorStream(); - $this->assertIsResource($newErrorStream); - $newErrorStreamMetadata = stream_get_meta_data($newErrorStream); - $this->assertSame('MEMORY', $newErrorStreamMetadata['stream_type']); - $this->assertSame('php://memory', $newErrorStreamMetadata['uri']); + $stream = $this->openMemoryStream(); + Output::setErrorStream($stream); + $this->assertSame($stream, Output::getErrorStream()); - $this->assertNotSame($oldErrorStream, $newErrorStream); - - fclose($oldErrorStream); - fclose($newErrorStream); + fclose($stream); + $this->resetStreams(); } public function testWillModifyOutputStream(): void { - $oldOutputStream = Output::getOutputStream(); - $this->assertIsResource($oldOutputStream); - $oldOutputStreamMetadata = stream_get_meta_data($oldOutputStream); - $this->assertSame('STDIO', $oldOutputStreamMetadata['stream_type']); - $this->assertSame('php://stdout', $oldOutputStreamMetadata['uri']); + $this->resetStreams(); + $this->assertSame(STDOUT, Output::getOutputStream()); - Output::setOutputStream(fopen('php://memory', 'w+')); + $stream = $this->openMemoryStream(); + Output::setOutputStream($stream); + $this->assertSame($stream, Output::getOutputStream()); - $newOutputStream = Output::getOutputStream(); - $this->assertIsResource($newOutputStream); - $newOutputStreamMetadata = stream_get_meta_data($newOutputStream); - $this->assertSame('MEMORY', $newOutputStreamMetadata['stream_type']); - $this->assertSame('php://memory', $newOutputStreamMetadata['uri']); - - $this->assertNotSame($oldOutputStream, $newOutputStream); - - fclose($oldOutputStream); - fclose($newOutputStream); + fclose($stream); + $this->resetStreams(); } public function testWillOutputError(): void { - Output::setErrorStream(fopen('php://memory', 'w+')); + Output::setErrorStream($this->openMemoryStream()); $stream = Output::getErrorStream(); $this->assertIsResource($stream); @@ -83,7 +68,7 @@ public function testWillOutputError(): void public function testWillOutputInfo(): void { - Output::setOutputStream(fopen('php://memory', 'w+')); + Output::setOutputStream($this->openMemoryStream()); $stream = Output::getOutputStream(); $this->assertIsResource($stream); @@ -102,7 +87,7 @@ public function testWillOutputInfo(): void public function testWillOutputSuccess(): void { - Output::setOutputStream(fopen('php://memory', 'w+')); + Output::setOutputStream($this->openMemoryStream()); $stream = Output::getOutputStream(); $this->assertIsResource($stream); @@ -121,7 +106,7 @@ public function testWillOutputSuccess(): void public function testWillOutputWarning(): void { - Output::setOutputStream(fopen('php://memory', 'w+')); + Output::setOutputStream($this->openMemoryStream()); $stream = Output::getOutputStream(); $this->assertIsResource($stream); @@ -140,7 +125,7 @@ public function testWillOutputWarning(): void public function testWillWrite(): void { - Output::setOutputStream(fopen('php://memory', 'w+')); + Output::setOutputStream($this->openMemoryStream()); $stream = Output::getOutputStream(); $this->assertIsResource($stream); @@ -156,7 +141,7 @@ public function testWillWrite(): void public function testWillWriteLine(): void { - Output::setOutputStream(fopen('php://memory', 'w+')); + Output::setOutputStream($this->openMemoryStream()); $stream = Output::getOutputStream(); $this->assertIsResource($stream); @@ -172,7 +157,7 @@ public function testWillWriteLine(): void public function testWillAlwaysGetErrorStream(): void { - Output::setErrorStream(fopen('php://memory', 'w+')); + Output::setErrorStream($this->openMemoryStream()); $stream = Output::getErrorStream(); $this->assertIsResource($stream); @@ -184,7 +169,7 @@ public function testWillAlwaysGetErrorStream(): void public function testWillAlwaysGetOutputStream(): void { - Output::setOutputStream(fopen('php://memory', 'w+')); + Output::setOutputStream($this->openMemoryStream()); $stream = Output::getOutputStream(); $this->assertIsResource($stream); @@ -193,4 +178,15 @@ public function testWillAlwaysGetOutputStream(): void $stream = Output::getOutputStream(); $this->assertIsResource($stream); } + + public function testWriteFallsBackToDefaultStreamWhenStreamIsClosed(): void + { + $stream = $this->openMemoryStream(); + Output::setOutputStream($stream); + fclose($stream); + + Output::write(); + + $this->assertSame(STDOUT, Output::getOutputStream()); + } } diff --git a/test/MakerRegressionTest.php b/test/MakerRegressionTest.php new file mode 100644 index 0000000..4ba0af5 --- /dev/null +++ b/test/MakerRegressionTest.php @@ -0,0 +1,115 @@ +root = vfsStream::setup('root', 0755, [ + 'composer.json' => '{"autoload":{"psr-4":{"Api\\\\Book\\\\":"src/Book/src/"}}}', + 'src' => [ + 'Book' => [ + 'src' => [], + ], + ], + ]); + + $this->outputStream = $this->openMemoryStream(); + $this->errorStream = $this->openMemoryStream(); + Output::setOutputStream($this->outputStream); + Output::setErrorStream($this->errorStream); + } + + public function testEndOfInputAtModulePromptFailsInsteadOfLooping(): void + { + Input::setStream($this->openMemoryStream()); + + $result = (new Maker($this->root->url()))(['dot-maker', 'command']); + + $this->assertSame(Output::FAILURE, $result); + $this->assertStringContainsString('No module name given before the end of input.', $this->stderr()); + } + + public function testStandaloneCommandsPrintNextStepsForEachCommand(): void + { + $this->answer('Book', 'Import', 'Export', ''); + + $result = (new Maker($this->root->url()))(['dot-maker', 'command']); + + $this->assertSame(Output::SUCCESS, $result); + $output = $this->stdout(); + $this->assertStringContainsString('Next steps:', $output); + $this->assertStringContainsString('Api\Book\Command\ImportCommand::class', $output); + $this->assertStringContainsString('Api\Book\Command\ExportCommand::class', $output); + } + + public function testFormInApiIsRefusedBeforeAskingForAModule(): void + { + $this->answer('Book'); + + $result = (new Maker($this->root->url()))(['dot-maker', 'form']); + + $this->assertSame(Output::FAILURE, $result); + $this->assertStringContainsString('Cannot create Forms in an API', $this->stderr()); + $this->assertStringNotContainsString('Existing module name', $this->stdout()); + } + + private function answer(string ...$lines): void + { + $stream = $this->openMemoryStream(); + foreach ($lines as $line) { + fwrite($stream, $line . PHP_EOL); + } + rewind($stream); + Input::setStream($stream); + } + + private function stdout(): string + { + return $this->read($this->outputStream); + } + + private function stderr(): string + { + return $this->read($this->errorStream); + } + + /** + * @param resource $stream + */ + private function read($stream): string + { + rewind($stream); + + return (string) preg_replace('/\e\[\d+(;\d+)?m/', '', (string) stream_get_contents($stream)); + } +} diff --git a/test/MakerTest.php b/test/MakerTest.php index 194df4f..5ddc55a 100644 --- a/test/MakerTest.php +++ b/test/MakerTest.php @@ -12,7 +12,6 @@ use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function fwrite; use function rewind; use function stream_get_contents; @@ -21,6 +20,8 @@ class MakerTest extends TestCase { + use StreamTrait; + /** @var resource $outputStream */ private $outputStream; /** @var resource $inputStream */ @@ -30,13 +31,13 @@ class MakerTest extends TestCase protected function setUp(): void { - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); } @@ -60,7 +61,7 @@ public function testCallingInvokeWillOutputErrorWhenNotInCliMode(): void ->onlyMethods(['isCli']) ->setConstructorArgs(['']) ->getMock(); - $maker->method('isCli')->willReturn(false); + $maker->expects($this->once())->method('isCli')->willReturn(false); $maker([]); rewind($this->errorStream); @@ -87,7 +88,7 @@ public function testCallingInvokeWillOutputErrorWhenInvalidComponent(): void ->onlyMethods(['isCli']) ->setConstructorArgs([$root->url()]) ->getMock(); - $maker->method('isCli')->willReturn(true); + $maker->expects($this->once())->method('isCli')->willReturn(true); $maker(['', 'invalid-component']); rewind($this->errorStream); @@ -116,7 +117,7 @@ public function testCallingInvokeWithoutArgsWillOutputHelpText(): void ->onlyMethods(['isCli']) ->setConstructorArgs([$root->url()]) ->getMock(); - $maker->method('isCli')->willReturn(true); + $maker->expects($this->once())->method('isCli')->willReturn(true); $maker(['', '']); rewind($this->errorStream); @@ -147,7 +148,7 @@ public function testCallingInvokeWithArgsModuleWillOutputDebugInfo(): void ->onlyMethods(['isCli']) ->setConstructorArgs([$root->url()]) ->getMock(); - $maker->method('isCli')->willReturn(true); + $maker->expects($this->once())->method('isCli')->willReturn(true); $maker(['', 'module']); rewind($this->outputStream); @@ -187,7 +188,7 @@ public function testCallingInvokeWithValidComponentIdentifierWillSucceed(): void ->onlyMethods(['isCli']) ->setConstructorArgs([$root->url()]) ->getMock(); - $maker->method('isCli')->willReturn(true); + $maker->expects($this->once())->method('isCli')->willReturn(true); $maker(['', 'command']); rewind($this->errorStream); diff --git a/test/StreamTrait.php b/test/StreamTrait.php new file mode 100644 index 0000000..956634a --- /dev/null +++ b/test/StreamTrait.php @@ -0,0 +1,40 @@ +assertIsResource($stream); + + return $stream; + } + + /** + * Restore the default IO streams, so a stream closed by one test is never used by the next one. + */ + #[After] + public function resetStreams(): void + { + Input::setStream(STDIN); + Output::setErrorStream(STDERR); + Output::setOutputStream(STDOUT); + } +} diff --git a/test/TempDirectoryTrait.php b/test/TempDirectoryTrait.php new file mode 100644 index 0000000..f1f16f5 --- /dev/null +++ b/test/TempDirectoryTrait.php @@ -0,0 +1,57 @@ + $tempDirectories */ + private array $tempDirectories = []; + + protected function createTempDirectory(): string + { + $path = sprintf('%s/dot-maker-test-%s', sys_get_temp_dir(), uniqid()); + mkdir($path, 0777, true); + $this->tempDirectories[] = $path; + + return $path; + } + + #[After] + public function removeTempDirectories(): void + { + foreach ($this->tempDirectories as $path) { + if (! is_dir($path)) { + continue; + } + $items = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), + RecursiveIteratorIterator::CHILD_FIRST + ); + /** @var SplFileInfo $item */ + foreach ($items as $item) { + $item->isDir() ? rmdir($item->getPathname()) : unlink($item->getPathname()); + } + rmdir($path); + } + $this->tempDirectories = []; + } +} diff --git a/test/Type/AbstractTypeTest.php b/test/Type/AbstractTypeTest.php new file mode 100644 index 0000000..ea20264 --- /dev/null +++ b/test/Type/AbstractTypeTest.php @@ -0,0 +1,95 @@ + '{"autoload":{"psr-4":{"Api\\\\App\\\\":"src/App/src/"}}}', + ]); + + $context = new Context($root->url()); + $this->type = new Command(new FileSystem($context), $context, new Config($root->url())); + } + + #[DataProvider('validNameProvider')] + public function testValidNames(string $name): void + { + $this->assertTrue($this->type->isValid($name)); + } + + #[DataProvider('invalidNameProvider')] + public function testInvalidNames(string $name): void + { + $this->assertFalse($this->type->isValid($name)); + } + + /** + * @return array + */ + public static function validNameProvider(): array + { + return [ + 'simple' => ['Book'], + 'with digits' => ['Book2'], + 'soft keyword' => ['Enum'], + 'only a suffix' => ['Entity'], + 'suffix of a valid name' => ['BookEntity'], + ]; + } + + /** + * @return array + */ + public static function invalidNameProvider(): array + { + return [ + 'empty' => [''], + 'starts with a digit' => ['1Book'], + 'punctuation' => ['Book.Store'], + 'keyword class' => ['Class'], + 'keyword list' => ['List'], + 'keyword function' => ['Function'], + 'keyword match' => ['Match'], + 'keyword readonly' => ['Readonly'], + 'reserved type int' => ['Int'], + 'reserved type self' => ['Self'], + 'reserved type null' => ['Null'], + 'keyword before suffix' => ['ListEntity'], + 'digit start before suffix' => ['1Command'], + ]; + } + + public function testAddMessageWithoutModuleThrows(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('No module selected.'); + + $this->type->addMessage(new Message('test')); + } + + public function testComponentRejectsTypesThatCannotCreateFiles(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Dot\Maker\Type\Module cannot create files.'); + + $this->type->component(TypeEnum::Module); + } +} diff --git a/test/Type/CollectionTest.php b/test/Type/CollectionTest.php index bb0addd..9c4697e 100644 --- a/test/Type/CollectionTest.php +++ b/test/Type/CollectionTest.php @@ -12,11 +12,11 @@ use Dot\Maker\IO\Output; use Dot\Maker\Type\Collection; use Dot\Maker\Type\Module; +use DotTest\Maker\StreamTrait; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function fwrite; use function rewind; use function sprintf; @@ -26,6 +26,8 @@ class CollectionTest extends TestCase { + use StreamTrait; + private Config $config; private Context $context; private FileSystem $fileSystem; @@ -59,13 +61,13 @@ protected function setUp(): void $this->import = new Import($this->context); $this->module = new Module($this->fileSystem, $this->context, $this->config); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -192,7 +194,7 @@ public function testCallToInvokeWillSucceedWhenNameIsValid(): void $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProvider(), $file->read()); + $this->assertSame($this->expectedContent(), $file->read()); } public function testCallToCreateWillSucceedWhenNameIsValid(): void @@ -217,10 +219,10 @@ public function testCallToCreateWillSucceedWhenNameIsValid(): void stream_get_contents($this->outputStream) ); - $this->assertSame($this->dataProvider(), $type->read()); + $this->assertSame($this->expectedContent(), $type->read()); } - private function dataProvider(): string + private function expectedContent(): string { return <<fileSystem = (new FileSystem($this->context))->setModuleName($this->moduleName); $this->module = new Module($this->fileSystem, $this->context, $this->config); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -147,9 +151,7 @@ public function testCallToInvokeWillOutputErrorAndWillNotCreateFileWhenNameIsInv $this->assertFileDoesNotExist($file->getPath()); } - /** - * @dataProvider dataProviderWithoutService - */ + #[DataProvider('dataProviderWithoutService')] public function testCallToInvokeWithoutServiceWillSucceedWhenNameIsValid(string $expected): void { $file = $this->fileSystem->command($this->resourceName); @@ -188,12 +190,10 @@ public function testCallToInvokeWithServiceWillSucceedWhenNameIsValid(): void $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProviderWithService($serviceInterface), $file->read()); + $this->assertSame($this->expectedWithService($serviceInterface), $file->read()); } - /** - * @dataProvider dataProviderWithoutService - */ + #[DataProvider('dataProviderWithoutService')] public function testCallToCreateWithoutServiceWillSucceedWhenNameIsValid(string $expected): void { $file = $this->fileSystem->command($this->resourceName); @@ -232,9 +232,12 @@ public function testCallToCreateWithServiceWillSucceedWhenNameIsValid(): void $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProviderWithService($serviceInterface), $file->read()); + $this->assertSame($this->expectedWithService($serviceInterface), $file->read()); } + /** + * @return array + */ public static function dataProviderWithoutService(): array { $uses = [ @@ -291,7 +294,7 @@ protected function execute( ]; } - private function dataProviderWithService(File $serviceInterface): string + private function expectedWithService(File $serviceInterface): string { $uses = [ sprintf('use %s;', $serviceInterface->getComponent()->getFqcn()), @@ -348,4 +351,25 @@ protected function execute( BODY; } + + #[DataProvider('defaultNameProvider')] + public function testGetDefaultNameStripsOnlyTheClassSuffix(string $className, string $expected): void + { + $command = new Command($this->fileSystem, $this->context, $this->config, $this->module); + + $this->assertSame($expected, $command->getDefaultName(new Component('Api\App\Command', $className))); + } + + /** + * @return array + */ + public static function defaultNameProvider(): array + { + return [ + 'simple' => ['BookStoreCommand', 'book-store:command'], + 'plural inside' => ['ImportCommandsCommand', 'import-commands:command'], + 'command in the middle' => ['MyCommandHandlerCommand', 'my-command-handler:command'], + 'command first' => ['CommandCenterCommand', 'command-center:command'], + ]; + } } diff --git a/test/Type/ConfigProviderTest.php b/test/Type/ConfigProviderTest.php index 523b5f2..bba32cd 100644 --- a/test/Type/ConfigProviderTest.php +++ b/test/Type/ConfigProviderTest.php @@ -11,11 +11,11 @@ use Dot\Maker\IO\Output; use Dot\Maker\Type\ConfigProvider; use Dot\Maker\Type\Module; +use DotTest\Maker\StreamTrait; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function rewind; use function stream_get_contents; @@ -23,6 +23,8 @@ class ConfigProviderTest extends TestCase { + use StreamTrait; + private Config $config; private Context $context; private FileSystem $fileSystem; @@ -34,7 +36,7 @@ class ConfigProviderTest extends TestCase protected function setUp(): void { - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); } @@ -78,7 +80,7 @@ public function testWillCreateFileWhenProjectTypeIsApiAndUsesCore(): void ) . PHP_EOL, stream_get_contents($this->outputStream) ); - $this->assertSame($this->dataProviderWhenProjectTypeIsApiAndUsesCore(), $file->read()); + $this->assertSame($this->expectedWhenProjectTypeIsApiAndUsesCore(), $file->read()); } public function testWillCreateFileWhenProjectTypeIsNotApiAndUsesCore(): void @@ -116,7 +118,7 @@ public function testWillCreateFileWhenProjectTypeIsNotApiAndUsesCore(): void ) . PHP_EOL, stream_get_contents($this->outputStream) ); - $this->assertSame($this->dataProviderWhenProjectTypeIsNotApiAndUsesCore(), $file->read()); + $this->assertSame($this->expectedWhenProjectTypeIsNotApiAndUsesCore(), $file->read()); } public function testWillCreateFileWhenProjectTypeIsApiAndDoesNotUseCore(): void @@ -153,7 +155,7 @@ public function testWillCreateFileWhenProjectTypeIsApiAndDoesNotUseCore(): void ) . PHP_EOL, stream_get_contents($this->outputStream) ); - $this->assertSame($this->dataProviderWhenProjectTypeIsApiAndDoesNotUseCore(), $file->read()); + $this->assertSame($this->expectedWhenProjectTypeIsApiAndDoesNotUseCore(), $file->read()); } public function testWillCreateFileWhenProjectTypeIsNotApiAndDoesNotUseCore(): void @@ -190,10 +192,10 @@ public function testWillCreateFileWhenProjectTypeIsNotApiAndDoesNotUseCore(): vo ) . PHP_EOL, stream_get_contents($this->outputStream) ); - $this->assertSame($this->dataProviderWhenProjectTypeIsNotApiAndDoesNotUseCore(), $file->read()); + $this->assertSame($this->expectedWhenProjectTypeIsNotApiAndDoesNotUseCore(), $file->read()); } - private function dataProviderWhenProjectTypeIsApiAndUsesCore(): string + private function expectedWhenProjectTypeIsApiAndUsesCore(): string { // phpcs:disable Generic.Files.LineLength.TooLong return << [ Application::class => [RoutesDelegator::class], ], - 'factories' => [ + 'factories' => [ ], ]; } @@ -329,7 +331,7 @@ private function getTemplates(): array // phpcs:enable Generic.Files.LineLength.TooLong } - private function dataProviderWhenProjectTypeIsApiAndDoesNotUseCore(): string + private function expectedWhenProjectTypeIsApiAndDoesNotUseCore(): string { // phpcs:disable Generic.Files.LineLength.TooLong return << [ Application::class => [RoutesDelegator::class], ], - 'factories' => [ + 'factories' => [ ], ]; } diff --git a/test/Type/CoreConfigProviderTest.php b/test/Type/CoreConfigProviderTest.php index a2e8bc8..a25d3c7 100644 --- a/test/Type/CoreConfigProviderTest.php +++ b/test/Type/CoreConfigProviderTest.php @@ -11,11 +11,11 @@ use Dot\Maker\IO\Output; use Dot\Maker\Type\CoreConfigProvider; use Dot\Maker\Type\Module; +use DotTest\Maker\StreamTrait; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function rewind; use function stream_get_contents; @@ -23,6 +23,8 @@ class CoreConfigProviderTest extends TestCase { + use StreamTrait; + private Config $config; private Context $context; private FileSystem $fileSystem; @@ -34,7 +36,7 @@ class CoreConfigProviderTest extends TestCase protected function setUp(): void { - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); } @@ -128,7 +130,7 @@ public function testWillCreateFileWhenProjectTypeIsApi(): void ) . PHP_EOL, stream_get_contents($this->outputStream) ); - $this->assertSame($this->dataProviderWhenProjectTypeIsApi(), $file->read()); + $this->assertSame($this->expectedWhenProjectTypeIsApi(), $file->read()); } public function testWillCreateFileWhenProjectTypeIsNotApi(): void @@ -166,10 +168,10 @@ public function testWillCreateFileWhenProjectTypeIsNotApi(): void ) . PHP_EOL, stream_get_contents($this->outputStream) ); - $this->assertSame($this->dataProviderWhenProjectTypeIsNotApi(), $file->read()); + $this->assertSame($this->expectedWhenProjectTypeIsNotApi(), $file->read()); } - private function dataProviderWhenProjectTypeIsApi(): string + private function expectedWhenProjectTypeIsApi(): string { // phpcs:disable Generic.Files.LineLength.TooLong return << [ - 'orm_default' => [ + 'orm_default' => [ 'drivers' => [ 'Core\ModuleName\Entity' => 'ModuleNameEntities', ], @@ -256,7 +258,7 @@ private function getDoctrineConfig(): array // phpcs:enable Generic.Files.LineLength.TooLong } - private function dataProviderWhenProjectTypeIsNotApi(): string + private function expectedWhenProjectTypeIsNotApi(): string { // phpcs:disable Generic.Files.LineLength.TooLong return << [ - 'orm_default' => [ + 'orm_default' => [ 'drivers' => [ 'Core\ModuleName\Entity' => 'ModuleNameEntities', ], diff --git a/test/Type/DuplicateFileTest.php b/test/Type/DuplicateFileTest.php new file mode 100644 index 0000000..4a50f04 --- /dev/null +++ b/test/Type/DuplicateFileTest.php @@ -0,0 +1,123 @@ + '{"autoload":{"psr-4":{' + . '"Api\\\\App\\\\":"src/App/src/",' + . '"Core\\\\App\\\\":"src/Core/src/App/src/"' + . '}}}', + ]); + + $this->config = new Config($root->url()); + $this->context = new Context($root->url()); + $this->fileSystem = (new FileSystem($this->context))->setModuleName('BookStore'); + $this->module = new Module($this->fileSystem, $this->context, $this->config); + + Output::setOutputStream($this->openMemoryStream()); + Output::setErrorStream($this->openMemoryStream()); + } + + #[DataProvider('singleFileTypeProvider')] + public function testSecondCreateThrowsDuplicateFileException(TypeEnum $typeEnum): void + { + $type = $this->type($typeEnum); + $file = $type->create('BookStore'); + $this->assertTrue($file->exists()); + + $this->expectException(DuplicateFileException::class); + $this->expectExceptionMessage(sprintf('already exists at %s', $file->getPath())); + + $type->create('BookStore'); + } + + public function testConfirmDeleteInputRejectsInvalidName(): void + { + $this->expectException(BadRequestException::class); + $this->expectExceptionMessage('Input name: "1Book"'); + + $this->type(TypeEnum::InputConfirmDelete)->create('1Book'); + } + + /** + * @return array + */ + public static function singleFileTypeProvider(): array + { + $cases = [ + TypeEnum::ConfigProvider, + TypeEnum::CoreConfigProvider, + TypeEnum::RoutesDelegator, + TypeEnum::FormCreateResource, + TypeEnum::FormDeleteResource, + TypeEnum::FormEditResource, + TypeEnum::HandlerApiDeleteResource, + TypeEnum::HandlerApiGetResource, + TypeEnum::HandlerApiGetCollection, + TypeEnum::HandlerApiPatchResource, + TypeEnum::HandlerApiPostResource, + TypeEnum::HandlerApiPutResource, + TypeEnum::HandlerGetCreateResource, + TypeEnum::HandlerGetDeleteResource, + TypeEnum::HandlerGetEditResource, + TypeEnum::HandlerGetListResource, + TypeEnum::HandlerGetViewResource, + TypeEnum::HandlerPostCreateResource, + TypeEnum::HandlerPostDeleteResource, + TypeEnum::HandlerPostEditResource, + TypeEnum::InputConfirmDelete, + TypeEnum::InputFilterCreateResource, + TypeEnum::InputFilterDeleteResource, + TypeEnum::InputFilterEditResource, + TypeEnum::InputFilterReplaceResource, + ]; + + $data = []; + foreach ($cases as $case) { + $data[$case->name] = [$case]; + } + + return $data; + } + + private function type(TypeEnum $typeEnum): FileInterface + { + $type = new ($typeEnum->value)($this->fileSystem, $this->context, $this->config, $this->module); + $this->assertInstanceOf(FileInterface::class, $type); + + return $type; + } +} diff --git a/test/Type/EntityTest.php b/test/Type/EntityTest.php index da9077f..bb818ab 100644 --- a/test/Type/EntityTest.php +++ b/test/Type/EntityTest.php @@ -11,11 +11,12 @@ use Dot\Maker\IO\Output; use Dot\Maker\Type\Entity; use Dot\Maker\Type\Module; +use DotTest\Maker\StreamTrait; use org\bovigo\vfs\vfsStream; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function fwrite; use function rewind; use function sprintf; @@ -25,6 +26,8 @@ class EntityTest extends TestCase { + use StreamTrait; + private Config $config; private Context $context; private FileSystem $fileSystem; @@ -57,13 +60,13 @@ protected function setUp(): void $this->fileSystem = (new FileSystem($this->context))->setModuleName($this->moduleName); $this->module = new Module($this->fileSystem, $this->context, $this->config); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -145,9 +148,7 @@ public function testCallToInvokeWillOutputErrorAndWillNotCreateFileWhenNameIsInv $this->assertFileDoesNotExist($file->getPath()); } - /** - * @dataProvider dataProvider - */ + #[DataProvider('dataProvider')] public function testCallToInvokeWillSucceedWhenNameIsValid(string $expected): void { $file = $this->fileSystem->entity($this->resourceName); @@ -166,9 +167,7 @@ public function testCallToInvokeWillSucceedWhenNameIsValid(string $expected): vo $this->assertSame($expected, $file->read()); } - /** - * @dataProvider dataProvider - */ + #[DataProvider('dataProvider')] public function testCallToCreateWillSucceedWhenNameIsValid(string $expected): void { $file = $this->fileSystem->entity($this->resourceName); @@ -194,6 +193,9 @@ public function testCallToCreateWillSucceedWhenNameIsValid(string $expected): vo $this->assertSame($expected, $type->read()); } + /** + * @return array + */ public static function dataProvider(): array { $entity = <<import = new Import($this->context); $this->module = new Module($this->fileSystem, $this->context, $this->config); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -171,7 +173,7 @@ public function testCallToInvokeWillCreateOnlyCreateResourceForm(): void $this->assertFileExists($createResourceForm->getPath()); $this->assertTrue($createResourceForm->exists()); - $this->assertSame($this->dataProviderCreateResourceForm(), $createResourceForm->read()); + $this->assertSame($this->expectedCreateResourceForm(), $createResourceForm->read()); $createResourceInputFilter = $this->fileSystem->createResourceInputFilter($this->resourceName); $this->assertFileExists($createResourceInputFilter->getPath()); @@ -223,7 +225,7 @@ public function testCallToInvokeWillCreateOnlyDeleteResourceForm(): void $this->assertFileExists($deleteResourceForm->getPath()); $this->assertTrue($deleteResourceForm->exists()); - $this->assertSame($this->dataProviderDeleteResourceForm(), $deleteResourceForm->read()); + $this->assertSame($this->expectedDeleteResourceForm(), $deleteResourceForm->read()); $this->assertFileExists($deleteResourceInputFilter->getPath()); $this->assertTrue($deleteResourceInputFilter->exists()); @@ -273,7 +275,7 @@ public function testCallToInvokeWillCreateOnlyEditResourceForm(): void $this->assertFileExists($editResourceForm->getPath()); $this->assertTrue($editResourceForm->exists()); - $this->assertSame($this->dataProviderEditResourceForm(), $editResourceForm->read()); + $this->assertSame($this->expectedEditResourceForm(), $editResourceForm->read()); $this->assertFileExists($editResourceInputFilter->getPath()); $this->assertTrue($editResourceInputFilter->exists()); @@ -311,7 +313,7 @@ public function testCallToCreateWillCreateOnlyCreateResourceForm(): void $this->assertFileExists($createResourceForm->getPath()); $this->assertTrue($createResourceForm->exists()); - $this->assertSame($this->dataProviderCreateResourceForm(), $createResourceForm->read()); + $this->assertSame($this->expectedCreateResourceForm(), $createResourceForm->read()); $this->assertFileExists($createResourceInputFilter->getPath()); $this->assertTrue($createResourceInputFilter->exists()); @@ -362,7 +364,7 @@ public function testCallToCreateWillCreateOnlyDeleteResourceForm(): void $this->assertFileExists($deleteResourceForm->getPath()); $this->assertTrue($deleteResourceForm->exists()); - $this->assertSame($this->dataProviderDeleteResourceForm(), $deleteResourceForm->read()); + $this->assertSame($this->expectedDeleteResourceForm(), $deleteResourceForm->read()); $this->assertFileExists($deleteResourceInputFilter->getPath()); $this->assertTrue($deleteResourceInputFilter->exists()); @@ -412,7 +414,7 @@ public function testCallToCreateWillCreateOnlyEditResourceForm(): void $this->assertFileExists($editResourceForm->getPath()); $this->assertTrue($editResourceForm->exists()); - $this->assertSame($this->dataProviderEditResourceForm(), $editResourceForm->read()); + $this->assertSame($this->expectedEditResourceForm(), $editResourceForm->read()); $this->assertFileExists($editResourceInputFilter->getPath()); $this->assertTrue($editResourceInputFilter->exists()); @@ -421,7 +423,7 @@ public function testCallToCreateWillCreateOnlyEditResourceForm(): void $this->assertEmpty(stream_get_contents($this->errorStream)); } - private function dataProviderCreateResourceForm(): string + private function expectedCreateResourceForm(): string { $uses = [ sprintf('use %s;', $this->import->getAbstractFormFqcn()), @@ -493,7 +495,7 @@ public function init(): void BODY; } - private function dataProviderDeleteResourceForm(): string + private function expectedDeleteResourceForm(): string { $uses = [ sprintf('use %s;', $this->import->getAbstractFormFqcn()), @@ -575,7 +577,7 @@ public function init(): void BODY; } - private function dataProviderEditResourceForm(): string + private function expectedEditResourceForm(): string { $uses = [ sprintf('use %s;', $this->import->getAbstractFormFqcn()), diff --git a/test/Type/Handler/ApiHandlerTest.php b/test/Type/Handler/ApiHandlerTest.php index 03d280f..255051c 100644 --- a/test/Type/Handler/ApiHandlerTest.php +++ b/test/Type/Handler/ApiHandlerTest.php @@ -12,11 +12,11 @@ use Dot\Maker\IO\Output; use Dot\Maker\Type\Handler; use Dot\Maker\Type\Module; +use DotTest\Maker\StreamTrait; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function fwrite; use function implode; use function rewind; @@ -27,6 +27,8 @@ class ApiHandlerTest extends TestCase { + use StreamTrait; + private Config $config; private Context $context; private FileSystem $fileSystem; @@ -60,13 +62,13 @@ protected function setUp(): void $this->import = new Import($this->context); $this->module = new Module($this->fileSystem, $this->context, $this->config); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -153,7 +155,7 @@ public function testCallToInvokeWillCreateOnlyGetCollectionHandler(): void $this->assertFileExists($apiGetCollectionHandler->getPath()); $this->assertTrue($apiGetCollectionHandler->exists()); - $this->assertSame($this->dataProviderGetCollectionHandler(), $apiGetCollectionHandler->read()); + $this->assertSame($this->expectedGetCollectionHandler(), $apiGetCollectionHandler->read()); $collection = $this->fileSystem->collection($this->resourceName); $this->assertFileExists($collection->getPath()); @@ -221,7 +223,7 @@ public function testCallToInvokeWillCreateOnlyGetResourceHandler(): void $this->assertFileExists($apiGetResourceHandler->getPath()); $this->assertTrue($apiGetResourceHandler->exists()); - $this->assertSame($this->dataProviderGetResourceHandler(), $apiGetResourceHandler->read()); + $this->assertSame($this->expectedGetResourceHandler(), $apiGetResourceHandler->read()); $this->assertFileDoesNotExist($apiPostResourceHandler->getPath()); $this->assertFalse($apiPostResourceHandler->exists()); @@ -285,7 +287,7 @@ public function testCallToInvokeWillCreateOnlyPostResourceHandler(): void $this->assertFileExists($apiPostResourceHandler->getPath()); $this->assertTrue($apiPostResourceHandler->exists()); - $this->assertSame($this->dataProviderPostResourceHandler(), $apiPostResourceHandler->read()); + $this->assertSame($this->expectedPostResourceHandler(), $apiPostResourceHandler->read()); $createResourceInputFilter = $this->fileSystem->createResourceInputFilter($this->resourceName); $this->assertFileExists($createResourceInputFilter->getPath()); @@ -353,7 +355,7 @@ public function testCallToInvokeWillCreateOnlyDeleteResourceHandler(): void $this->assertFileExists($apiDeleteResourceHandler->getPath()); $this->assertTrue($apiDeleteResourceHandler->exists()); - $this->assertSame($this->dataProviderDeleteResourceHandler(), $apiDeleteResourceHandler->read()); + $this->assertSame($this->expectedDeleteResourceHandler(), $apiDeleteResourceHandler->read()); $this->assertFileDoesNotExist($apiPatchResourceHandler->getPath()); $this->assertFalse($apiPatchResourceHandler->exists()); @@ -417,7 +419,7 @@ public function testCallToInvokeWillCreateOnlyPatchResourceHandler(): void $this->assertFileExists($apiPatchResourceHandler->getPath()); $this->assertTrue($apiPatchResourceHandler->exists()); - $this->assertSame($this->dataProviderPatchResourceHandler(), $apiPatchResourceHandler->read()); + $this->assertSame($this->expectedPatchResourceHandler(), $apiPatchResourceHandler->read()); $editResourceInputFilter = $this->fileSystem->editResourceInputFilter($this->resourceName); $this->assertFileExists($editResourceInputFilter->getPath()); @@ -485,7 +487,7 @@ public function testCallToInvokeWillCreateOnlyPutResourceHandler(): void $this->assertFileExists($apiPutResourceHandler->getPath()); $this->assertTrue($apiPutResourceHandler->exists()); - $this->assertSame($this->dataProviderPutResourceHandler(), $apiPutResourceHandler->read()); + $this->assertSame($this->expectedPutResourceHandler(), $apiPutResourceHandler->read()); $replaceResourceInputFilter = $this->fileSystem->replaceResourceInputFilter($this->resourceName); $this->assertFileExists($replaceResourceInputFilter->getPath()); @@ -535,7 +537,7 @@ public function testCallToCreateWillCreateOnlyGetCollectionHandler(): void $this->assertFileExists($apiGetCollectionHandler->getPath()); $this->assertTrue($apiGetCollectionHandler->exists()); - $this->assertSame($this->dataProviderGetCollectionHandler(), $apiGetCollectionHandler->read()); + $this->assertSame($this->expectedGetCollectionHandler(), $apiGetCollectionHandler->read()); $collection = $this->fileSystem->collection($this->resourceName); $this->assertFileExists($collection->getPath()); @@ -603,7 +605,7 @@ public function testCallToCreateWillCreateOnlyGetResourceHandler(): void $this->assertFileExists($apiGetResourceHandler->getPath()); $this->assertTrue($apiGetResourceHandler->exists()); - $this->assertSame($this->dataProviderGetResourceHandler(), $apiGetResourceHandler->read()); + $this->assertSame($this->expectedGetResourceHandler(), $apiGetResourceHandler->read()); $this->assertFileDoesNotExist($apiPostResourceHandler->getPath()); $this->assertFalse($apiPostResourceHandler->exists()); @@ -667,7 +669,7 @@ public function testCallToCreateWillCreateOnlyPostResourceHandler(): void $this->assertFileExists($apiPostResourceHandler->getPath()); $this->assertTrue($apiPostResourceHandler->exists()); - $this->assertSame($this->dataProviderPostResourceHandler(), $apiPostResourceHandler->read()); + $this->assertSame($this->expectedPostResourceHandler(), $apiPostResourceHandler->read()); $createResourceInputFilter = $this->fileSystem->createResourceInputFilter($this->resourceName); $this->assertFileExists($createResourceInputFilter->getPath()); @@ -735,7 +737,7 @@ public function testCallToCreateWillCreateOnlyDeleteResourceHandler(): void $this->assertFileExists($apiDeleteResourceHandler->getPath()); $this->assertTrue($apiDeleteResourceHandler->exists()); - $this->assertSame($this->dataProviderDeleteResourceHandler(), $apiDeleteResourceHandler->read()); + $this->assertSame($this->expectedDeleteResourceHandler(), $apiDeleteResourceHandler->read()); $this->assertFileDoesNotExist($apiPatchResourceHandler->getPath()); $this->assertFalse($apiPatchResourceHandler->exists()); @@ -799,7 +801,7 @@ public function testCallToCreateWillCreateOnlyPatchResourceHandler(): void $this->assertFileExists($apiPatchResourceHandler->getPath()); $this->assertTrue($apiPatchResourceHandler->exists()); - $this->assertSame($this->dataProviderPatchResourceHandler(), $apiPatchResourceHandler->read()); + $this->assertSame($this->expectedPatchResourceHandler(), $apiPatchResourceHandler->read()); $editResourceInputFilter = $this->fileSystem->editResourceInputFilter($this->resourceName); $this->assertFileExists($editResourceInputFilter->getPath()); @@ -867,7 +869,7 @@ public function testCallToCreateWillCreateOnlyPutResourceHandler(): void $this->assertFileExists($apiPutResourceHandler->getPath()); $this->assertTrue($apiPutResourceHandler->exists()); - $this->assertSame($this->dataProviderPutResourceHandler(), $apiPutResourceHandler->read()); + $this->assertSame($this->expectedPutResourceHandler(), $apiPutResourceHandler->read()); $replaceResourceInputFilter = $this->fileSystem->replaceResourceInputFilter($this->resourceName); $this->assertFileExists($replaceResourceInputFilter->getPath()); @@ -877,7 +879,7 @@ public function testCallToCreateWillCreateOnlyPutResourceHandler(): void $this->assertEmpty(stream_get_contents($this->errorStream)); } - private function dataProviderGetCollectionHandler(): string + private function expectedGetCollectionHandler(): string { $collection = $this->fileSystem->collection($this->resourceName); $serviceInterface = $this->fileSystem->serviceInterface($this->resourceName); @@ -924,7 +926,7 @@ public function handle( BODY; } - private function dataProviderGetResourceHandler(): string + private function expectedGetResourceHandler(): string { $entity = $this->fileSystem->entity($this->resourceName); @@ -962,7 +964,7 @@ public function handle( BODY; } - private function dataProviderPostResourceHandler(): string + private function expectedPostResourceHandler(): string { $createResourceInputFilter = $this->fileSystem->createResourceInputFilter($this->resourceName); $serviceInterface = $this->fileSystem->serviceInterface($this->resourceName); @@ -1024,7 +1026,7 @@ public function handle( BODY; } - private function dataProviderDeleteResourceHandler(): string + private function expectedDeleteResourceHandler(): string { $serviceInterface = $this->fileSystem->serviceInterface($this->resourceName); $entity = $this->fileSystem->entity($this->resourceName); @@ -1074,7 +1076,7 @@ public function handle( BODY; } - private function dataProviderPatchResourceHandler(): string + private function expectedPatchResourceHandler(): string { $editResourceInputFilter = $this->fileSystem->editResourceInputFilter($this->resourceName); $serviceInterface = $this->fileSystem->serviceInterface($this->resourceName); @@ -1143,7 +1145,7 @@ public function handle( BODY; } - private function dataProviderPutResourceHandler(): string + private function expectedPutResourceHandler(): string { $replaceResourceInputFilter = $this->fileSystem->replaceResourceInputFilter($this->resourceName); $serviceInterface = $this->fileSystem->serviceInterface($this->resourceName); diff --git a/test/Type/HandlerTest.php b/test/Type/HandlerTest.php index 1135bac..df9609d 100644 --- a/test/Type/HandlerTest.php +++ b/test/Type/HandlerTest.php @@ -12,11 +12,11 @@ use Dot\Maker\IO\Output; use Dot\Maker\Type\Handler; use Dot\Maker\Type\Module; +use DotTest\Maker\StreamTrait; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function fwrite; use function implode; use function rewind; @@ -27,6 +27,8 @@ class HandlerTest extends TestCase { + use StreamTrait; + private Config $config; private Context $context; private FileSystem $fileSystem; @@ -60,13 +62,13 @@ protected function setUp(): void $this->import = new Import($this->context); $this->module = new Module($this->fileSystem, $this->context, $this->config); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -161,7 +163,7 @@ public function testCallToInvokeWillCreateOnlyListResourceHandler(): void $getListResourcesHandler = $this->fileSystem->getListResourcesHandler($this->resourceName); $this->assertFileExists($getListResourcesHandler->getPath()); $this->assertTrue($getListResourcesHandler->exists()); - $this->assertSame($this->dataProviderGetListResourceHandler(), $getListResourcesHandler->read()); + $this->assertSame($this->expectedGetListResourceHandler(), $getListResourcesHandler->read()); $getViewResourceHandler = $this->fileSystem->getViewResourceHandler($this->resourceName); $this->assertFileDoesNotExist($getViewResourceHandler->getPath()); @@ -257,7 +259,7 @@ public function testCallToInvokeWillCreateOnlyViewResourceHandler(): void $getViewResourceHandler = $this->fileSystem->getViewResourceHandler($this->resourceName); $this->assertFileExists($getViewResourceHandler->getPath()); $this->assertTrue($getViewResourceHandler->exists()); - $this->assertSame($this->dataProviderGetViewResourceHandler(), $getViewResourceHandler->read()); + $this->assertSame($this->expectedGetViewResourceHandler(), $getViewResourceHandler->read()); $getCreateResourceHandler = $this->fileSystem->getCreateResourceHandler($this->resourceName); $this->assertFileDoesNotExist($getCreateResourceHandler->getPath()); @@ -353,12 +355,12 @@ public function testCallToInvokeWillCreateOnlyCreateResourceHandler(): void $getCreateResourceHandler = $this->fileSystem->getCreateResourceHandler($this->resourceName); $this->assertFileExists($getCreateResourceHandler->getPath()); $this->assertTrue($getCreateResourceHandler->exists()); - $this->assertSame($this->dataProviderGetCreateResourceHandler(), $getCreateResourceHandler->read()); + $this->assertSame($this->expectedGetCreateResourceHandler(), $getCreateResourceHandler->read()); $postCreateResourceHandler = $this->fileSystem->postCreateResourceHandler($this->resourceName); $this->assertFileExists($postCreateResourceHandler->getPath()); $this->assertTrue($postCreateResourceHandler->exists()); - $this->assertSame($this->dataProviderPostCreateResourceHandler(), $postCreateResourceHandler->read()); + $this->assertSame($this->expectedPostCreateResourceHandler(), $postCreateResourceHandler->read()); $getDeleteResourceHandler = $this->fileSystem->getDeleteResourceHandler($this->resourceName); $this->assertFileDoesNotExist($getDeleteResourceHandler->getPath()); @@ -457,12 +459,12 @@ public function testCallToInvokeWillCreateOnlyDeleteResourceHandler(): void $getDeleteResourceHandler = $this->fileSystem->getDeleteResourceHandler($this->resourceName); $this->assertFileExists($getDeleteResourceHandler->getPath()); $this->assertTrue($getDeleteResourceHandler->exists()); - $this->assertSame($this->dataProviderGetDeleteResourceHandler(), $getDeleteResourceHandler->read()); + $this->assertSame($this->expectedGetDeleteResourceHandler(), $getDeleteResourceHandler->read()); $postDeleteResourceHandler = $this->fileSystem->postDeleteResourceHandler($this->resourceName); $this->assertFileExists($postDeleteResourceHandler->getPath()); $this->assertTrue($postDeleteResourceHandler->exists()); - $this->assertSame($this->dataProviderPostDeleteResourceHandler(), $postDeleteResourceHandler->read()); + $this->assertSame($this->expectedPostDeleteResourceHandler(), $postDeleteResourceHandler->read()); $getEditResourceHandler = $this->fileSystem->getEditResourceHandler($this->resourceName); $this->assertFileDoesNotExist($getEditResourceHandler->getPath()); @@ -561,12 +563,12 @@ public function testCallToInvokeWillCreateOnlyEditResourceHandler(): void $getEditResourceHandler = $this->fileSystem->getEditResourceHandler($this->resourceName); $this->assertFileExists($getEditResourceHandler->getPath()); $this->assertTrue($getEditResourceHandler->exists()); - $this->assertSame($this->dataProviderGetEditResourceHandler(), $getEditResourceHandler->read()); + $this->assertSame($this->expectedGetEditResourceHandler(), $getEditResourceHandler->read()); $postEditResourceHandler = $this->fileSystem->postEditResourceHandler($this->resourceName); $this->assertFileExists($postEditResourceHandler->getPath()); $this->assertTrue($postEditResourceHandler->exists()); - $this->assertSame($this->dataProviderPostEditResourceHandler(), $postEditResourceHandler->read()); + $this->assertSame($this->expectedPostEditResourceHandler(), $postEditResourceHandler->read()); $entity = $this->fileSystem->entity($this->resourceName); @@ -633,7 +635,7 @@ public function testCallToCreateWillCreateOnlyListResourceHandler(): void $getListResourcesHandler = $this->fileSystem->getListResourcesHandler($this->resourceName); $this->assertFileExists($getListResourcesHandler->getPath()); $this->assertTrue($getListResourcesHandler->exists()); - $this->assertSame($this->dataProviderGetListResourceHandler(), $getListResourcesHandler->read()); + $this->assertSame($this->expectedGetListResourceHandler(), $getListResourcesHandler->read()); $getViewResourceHandler = $this->fileSystem->getViewResourceHandler($this->resourceName); $this->assertFileDoesNotExist($getViewResourceHandler->getPath()); @@ -729,7 +731,7 @@ public function testCallToCreateWillCreateOnlyViewResourceHandler(): void $getViewResourceHandler = $this->fileSystem->getViewResourceHandler($this->resourceName); $this->assertFileExists($getViewResourceHandler->getPath()); $this->assertTrue($getViewResourceHandler->exists()); - $this->assertSame($this->dataProviderGetViewResourceHandler(), $getViewResourceHandler->read()); + $this->assertSame($this->expectedGetViewResourceHandler(), $getViewResourceHandler->read()); $getCreateResourceHandler = $this->fileSystem->getCreateResourceHandler($this->resourceName); $this->assertFileDoesNotExist($getCreateResourceHandler->getPath()); @@ -825,12 +827,12 @@ public function testCallToCreateWillCreateOnlyCreateResourceHandler(): void $getCreateResourceHandler = $this->fileSystem->getCreateResourceHandler($this->resourceName); $this->assertFileExists($getCreateResourceHandler->getPath()); $this->assertTrue($getCreateResourceHandler->exists()); - $this->assertSame($this->dataProviderGetCreateResourceHandler(), $getCreateResourceHandler->read()); + $this->assertSame($this->expectedGetCreateResourceHandler(), $getCreateResourceHandler->read()); $postCreateResourceHandler = $this->fileSystem->postCreateResourceHandler($this->resourceName); $this->assertFileExists($postCreateResourceHandler->getPath()); $this->assertTrue($postCreateResourceHandler->exists()); - $this->assertSame($this->dataProviderPostCreateResourceHandler(), $postCreateResourceHandler->read()); + $this->assertSame($this->expectedPostCreateResourceHandler(), $postCreateResourceHandler->read()); $getDeleteResourceHandler = $this->fileSystem->getDeleteResourceHandler($this->resourceName); $this->assertFileDoesNotExist($getDeleteResourceHandler->getPath()); @@ -929,12 +931,12 @@ public function testCallToCreateWillCreateOnlyDeleteResourceHandler(): void $getDeleteResourceHandler = $this->fileSystem->getDeleteResourceHandler($this->resourceName); $this->assertFileExists($getDeleteResourceHandler->getPath()); $this->assertTrue($getDeleteResourceHandler->exists()); - $this->assertSame($this->dataProviderGetDeleteResourceHandler(), $getDeleteResourceHandler->read()); + $this->assertSame($this->expectedGetDeleteResourceHandler(), $getDeleteResourceHandler->read()); $postDeleteResourceHandler = $this->fileSystem->postDeleteResourceHandler($this->resourceName); $this->assertFileExists($postDeleteResourceHandler->getPath()); $this->assertTrue($postDeleteResourceHandler->exists()); - $this->assertSame($this->dataProviderPostDeleteResourceHandler(), $postDeleteResourceHandler->read()); + $this->assertSame($this->expectedPostDeleteResourceHandler(), $postDeleteResourceHandler->read()); $getEditResourceHandler = $this->fileSystem->getEditResourceHandler($this->resourceName); $this->assertFileDoesNotExist($getEditResourceHandler->getPath()); @@ -1033,12 +1035,12 @@ public function testCallToCreateWillCreateOnlyEditResourceHandler(): void $getEditResourceHandler = $this->fileSystem->getEditResourceHandler($this->resourceName); $this->assertFileExists($getEditResourceHandler->getPath()); $this->assertTrue($getEditResourceHandler->exists()); - $this->assertSame($this->dataProviderGetEditResourceHandler(), $getEditResourceHandler->read()); + $this->assertSame($this->expectedGetEditResourceHandler(), $getEditResourceHandler->read()); $postEditResourceHandler = $this->fileSystem->postEditResourceHandler($this->resourceName); $this->assertFileExists($postEditResourceHandler->getPath()); $this->assertTrue($postEditResourceHandler->exists()); - $this->assertSame($this->dataProviderPostEditResourceHandler(), $postEditResourceHandler->read()); + $this->assertSame($this->expectedPostEditResourceHandler(), $postEditResourceHandler->read()); $entity = $this->fileSystem->entity($this->resourceName); @@ -1057,7 +1059,7 @@ public function testCallToCreateWillCreateOnlyEditResourceHandler(): void $this->assertEmpty(stream_get_contents($this->errorStream)); } - private function dataProviderGetListResourceHandler(): string + private function expectedGetListResourceHandler(): string { $serviceInterface = $this->fileSystem->serviceInterface($this->resourceName); @@ -1107,7 +1109,7 @@ public function handle( BODY; } - private function dataProviderGetViewResourceHandler(): string + private function expectedGetViewResourceHandler(): string { $serviceInterface = $this->fileSystem->serviceInterface($this->resourceName); @@ -1171,7 +1173,7 @@ public function handle( BODY; } - private function dataProviderGetCreateResourceHandler(): string + private function expectedGetCreateResourceHandler(): string { $createResourceForm = $this->fileSystem->createResourceForm($this->resourceName); @@ -1227,7 +1229,7 @@ public function handle( BODY; } - private function dataProviderPostCreateResourceHandler(): string + private function expectedPostCreateResourceHandler(): string { $createResourceForm = $this->fileSystem->createResourceForm($this->resourceName); $serviceInterface = $this->fileSystem->serviceInterface($this->resourceName); @@ -1338,7 +1340,7 @@ public function handle( BODY; } - private function dataProviderGetDeleteResourceHandler(): string + private function expectedGetDeleteResourceHandler(): string { $deleteResourceForm = $this->fileSystem->deleteResourceForm($this->resourceName); $serviceInterface = $this->fileSystem->serviceInterface($this->resourceName); @@ -1405,8 +1407,8 @@ public function handle( return new HtmlResponse( \$this->template->render('book-store::delete-book-store-form', [ - 'form' => \$this->deleteBookStoreForm->prepare(), - 'book-store' => \$bookStore, + 'form' => \$this->deleteBookStoreForm->prepare(), + 'bookStore' => \$bookStore, ]) ); } @@ -1415,7 +1417,7 @@ public function handle( BODY; } - private function dataProviderPostDeleteResourceHandler(): string + private function expectedPostDeleteResourceHandler(): string { $deleteResourceForm = $this->fileSystem->deleteResourceForm($this->resourceName); $serviceInterface = $this->fileSystem->serviceInterface($this->resourceName); @@ -1497,7 +1499,7 @@ public function handle( return new HtmlResponse( \$this->template->render('book-store::delete-book-store-form', [ - 'form' => \$this->deleteBookStoreForm->prepare(), + 'form' => \$this->deleteBookStoreForm->prepare(), 'bookStore' => \$bookStore, ]), StatusCodeInterface::STATUS_UNPROCESSABLE_ENTITY @@ -1519,7 +1521,7 @@ public function handle( BODY; } - private function dataProviderGetEditResourceHandler(): string + private function expectedGetEditResourceHandler(): string { $editResourceForm = $this->fileSystem->editResourceForm($this->resourceName); $serviceInterface = $this->fileSystem->serviceInterface($this->resourceName); @@ -1589,8 +1591,8 @@ public function handle( return new HtmlResponse( \$this->template->render('book-store::edit-book-store-form', [ - 'form' => \$this->editBookStoreForm->prepare(), - 'book-store' => \$bookStore, + 'form' => \$this->editBookStoreForm->prepare(), + 'bookStore' => \$bookStore, ]) ); } @@ -1600,7 +1602,7 @@ public function handle( // phpcs:enable Generic.Files.LineLength.TooLong } - private function dataProviderPostEditResourceHandler(): string + private function expectedPostEditResourceHandler(): string { $editResourceForm = $this->fileSystem->editResourceForm($this->resourceName); $serviceInterface = $this->fileSystem->serviceInterface($this->resourceName); @@ -1687,7 +1689,7 @@ public function handle( return new HtmlResponse( \$this->template->render('book-store::edit-book-store-form', [ - 'form' => \$this->editBookStoreForm->prepare(), + 'form' => \$this->editBookStoreForm->prepare(), 'bookStore' => \$bookStore, ]), StatusCodeInterface::STATUS_UNPROCESSABLE_ENTITY @@ -1695,9 +1697,9 @@ public function handle( } catch (BadRequestException | ConflictException | NotFoundException \$exception) { return new HtmlResponse( \$this->template->render('book-store::edit-book-store-form', [ - 'form' => \$this->editBookStoreForm->prepare(), + 'form' => \$this->editBookStoreForm->prepare(), 'bookStore' => \$bookStore, - 'messages' => [ + 'messages' => [ 'error' => \$exception->getMessage(), ], ]), diff --git a/test/Type/HelpTest.php b/test/Type/HelpTest.php index 2c92cf5..08ac705 100644 --- a/test/Type/HelpTest.php +++ b/test/Type/HelpTest.php @@ -10,16 +10,18 @@ use Dot\Maker\IO\Output; use Dot\Maker\Type\Help; use DotTest\Maker\Helper; +use DotTest\Maker\StreamTrait; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function rewind; use function stream_get_contents; class HelpTest extends TestCase { + use StreamTrait; + private Config $config; private Context $context; private FileSystem $fileSystem; @@ -43,7 +45,7 @@ protected function setUp(): void public function testWillDisplayHelpMessage(): void { - $stream = fopen('php://memory', 'w+'); + $stream = $this->openMemoryStream(); Output::setOutputStream($stream); $help = new Help($this->fileSystem, $this->context, $this->config); diff --git a/test/Type/InputFilter/ApiInputFilterTest.php b/test/Type/InputFilter/ApiInputFilterTest.php index 2abdd41..3eda96b 100644 --- a/test/Type/InputFilter/ApiInputFilterTest.php +++ b/test/Type/InputFilter/ApiInputFilterTest.php @@ -12,11 +12,11 @@ use Dot\Maker\IO\Output; use Dot\Maker\Type\InputFilter; use Dot\Maker\Type\Module; +use DotTest\Maker\StreamTrait; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function fwrite; use function rewind; use function stream_get_contents; @@ -25,6 +25,8 @@ class ApiInputFilterTest extends TestCase { + use StreamTrait; + private Config $config; private Context $context; private FileSystem $fileSystem; @@ -59,13 +61,13 @@ protected function setUp(): void $this->import = new Import($this->context); $this->module = new Module($this->fileSystem, $this->context, $this->config); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -141,7 +143,7 @@ public function testCallToInvokeWillCreateOnlyCreateResourceInputFilter(): void $this->assertFileExists($createResourceInputFilter->getPath()); $this->assertTrue($createResourceInputFilter->exists()); - $this->assertSame($this->dataProviderApiCreateResourceInputFilter(), $createResourceInputFilter->read()); + $this->assertSame($this->expectedApiCreateResourceInputFilter(), $createResourceInputFilter->read()); $this->assertFileDoesNotExist($deleteResourceInputFilter->getPath()); $this->assertFalse($deleteResourceInputFilter->exists()); @@ -234,7 +236,7 @@ public function testCallToInvokeWillCreateOnlyEditResourceInputFilter(): void $this->assertFileExists($editResourceInputFilter->getPath()); $this->assertTrue($editResourceInputFilter->exists()); - $this->assertSame($this->dataProviderApiEditResourceInputFilter(), $editResourceInputFilter->read()); + $this->assertSame($this->expectedApiEditResourceInputFilter(), $editResourceInputFilter->read()); $this->assertFileDoesNotExist($replaceResourceInputFilter->getPath()); $this->assertFalse($replaceResourceInputFilter->exists()); @@ -281,7 +283,7 @@ public function testCallToInvokeWillCreateOnlyReplaceResourceInputFilter(): void $this->assertFileExists($replaceResourceInputFilter->getPath()); $this->assertTrue($replaceResourceInputFilter->exists()); - $this->assertSame($this->dataProviderApiReplaceResourceInputFilter(), $replaceResourceInputFilter->read()); + $this->assertSame($this->expectedApiReplaceResourceInputFilter(), $replaceResourceInputFilter->read()); rewind($this->errorStream); $this->assertEmpty(stream_get_contents($this->errorStream)); @@ -315,7 +317,7 @@ public function testCallToCreateWillCreateOnlyCreateResourceInputFilter(): void $this->assertFileExists($createResourceInputFilter->getPath()); $this->assertTrue($createResourceInputFilter->exists()); - $this->assertSame($this->dataProviderApiCreateResourceInputFilter(), $createResourceInputFilter->read()); + $this->assertSame($this->expectedApiCreateResourceInputFilter(), $createResourceInputFilter->read()); $this->assertFileDoesNotExist($deleteResourceInputFilter->getPath()); $this->assertFalse($deleteResourceInputFilter->exists()); @@ -406,7 +408,7 @@ public function testCallToCreateWillCreateOnlyEditResourceInputFilter(): void $this->assertFileExists($editResourceInputFilter->getPath()); $this->assertTrue($editResourceInputFilter->exists()); - $this->assertSame($this->dataProviderApiEditResourceInputFilter(), $editResourceInputFilter->read()); + $this->assertSame($this->expectedApiEditResourceInputFilter(), $editResourceInputFilter->read()); $this->assertFileDoesNotExist($replaceResourceInputFilter->getPath()); $this->assertFalse($replaceResourceInputFilter->exists()); @@ -452,13 +454,13 @@ public function testCallToCreateWillCreateOnlyReplaceResourceInputFilter(): void $this->assertFileExists($replaceResourceInputFilter->getPath()); $this->assertTrue($replaceResourceInputFilter->exists()); - $this->assertSame($this->dataProviderApiReplaceResourceInputFilter(), $replaceResourceInputFilter->read()); + $this->assertSame($this->expectedApiReplaceResourceInputFilter(), $replaceResourceInputFilter->read()); rewind($this->errorStream); $this->assertEmpty(stream_get_contents($this->errorStream)); } - private function dataProviderApiCreateResourceInputFilter(): string + private function expectedApiCreateResourceInputFilter(): string { return <<import = new Import($this->context); $this->module = new Module($this->fileSystem, $this->context, $this->config); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -141,7 +143,7 @@ public function testCallToInvokeWillCreateOnlyCreateResourceInputFilter(): void $this->assertFileExists($createResourceInputFilter->getPath()); $this->assertTrue($createResourceInputFilter->exists()); - $this->assertSame($this->dataProviderCreateResourceInputFilter(), $createResourceInputFilter->read()); + $this->assertSame($this->expectedCreateResourceInputFilter(), $createResourceInputFilter->read()); $this->assertFileDoesNotExist($deleteResourceInputFilter->getPath()); $this->assertFalse($deleteResourceInputFilter->exists()); @@ -188,7 +190,7 @@ public function testCallToInvokeWillCreateOnlyDeleteResourceInputFilter(): void $this->assertFileExists($deleteResourceInputFilter->getPath()); $this->assertTrue($deleteResourceInputFilter->exists()); - $this->assertSame($this->dataProviderDeleteResourceInputFilter(), $deleteResourceInputFilter->read()); + $this->assertSame($this->expectedDeleteResourceInputFilter(), $deleteResourceInputFilter->read()); $this->assertFileDoesNotExist($editResourceInputFilter->getPath()); $this->assertFalse($editResourceInputFilter->exists()); @@ -235,7 +237,7 @@ public function testCallToInvokeWillCreateOnlyEditResourceInputFilter(): void $this->assertFileExists($editResourceInputFilter->getPath()); $this->assertTrue($editResourceInputFilter->exists()); - $this->assertSame($this->dataProviderEditResourceInputFilter(), $editResourceInputFilter->read()); + $this->assertSame($this->expectedEditResourceInputFilter(), $editResourceInputFilter->read()); $this->assertFileDoesNotExist($replaceResourceInputFilter->getPath()); $this->assertFalse($replaceResourceInputFilter->exists()); @@ -315,7 +317,7 @@ public function testCallToCreateWillCreateOnlyCreateResourceInputFilter(): void $this->assertFileExists($createResourceInputFilter->getPath()); $this->assertTrue($createResourceInputFilter->exists()); - $this->assertSame($this->dataProviderCreateResourceInputFilter(), $createResourceInputFilter->read()); + $this->assertSame($this->expectedCreateResourceInputFilter(), $createResourceInputFilter->read()); $this->assertFileDoesNotExist($deleteResourceInputFilter->getPath()); $this->assertFalse($deleteResourceInputFilter->exists()); @@ -362,7 +364,7 @@ public function testCallToCreateWillCreateOnlyDeleteResourceInputFilter(): void $this->assertFileExists($deleteResourceInputFilter->getPath()); $this->assertTrue($deleteResourceInputFilter->exists()); - $this->assertSame($this->dataProviderDeleteResourceInputFilter(), $deleteResourceInputFilter->read()); + $this->assertSame($this->expectedDeleteResourceInputFilter(), $deleteResourceInputFilter->read()); $this->assertFileDoesNotExist($editResourceInputFilter->getPath()); $this->assertFalse($editResourceInputFilter->exists()); @@ -408,7 +410,7 @@ public function testCallToCreateWillCreateOnlyEditResourceInputFilter(): void $this->assertFileExists($editResourceInputFilter->getPath()); $this->assertTrue($editResourceInputFilter->exists()); - $this->assertSame($this->dataProviderEditResourceInputFilter(), $editResourceInputFilter->read()); + $this->assertSame($this->expectedEditResourceInputFilter(), $editResourceInputFilter->read()); $this->assertFileDoesNotExist($replaceResourceInputFilter->getPath()); $this->assertFalse($replaceResourceInputFilter->exists()); @@ -459,7 +461,7 @@ public function testCallToCreateWillNotCreateReplaceResourceInputFilter(): void $this->assertEmpty(stream_get_contents($this->errorStream)); } - private function dataProviderCreateResourceInputFilter(): string + private function expectedCreateResourceInputFilter(): string { return <<fileSystem->input('ConfirmDeleteBookStoreInput'); @@ -523,7 +525,7 @@ public function init(): self BODY; } - private function dataProviderEditResourceInputFilter(): string + private function expectedEditResourceInputFilter(): string { return <<import = new Import($this->context); $this->module = new Module($this->fileSystem, $this->context, $this->config); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -163,7 +165,7 @@ public function testCallToInvokeWillSucceedWhenNameIsValid(): void $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProvider(), $file->read()); + $this->assertSame($this->expectedContent(), $file->read()); } public function testCallToCreateWillSucceedWhenNameIsValid(): void @@ -188,10 +190,10 @@ public function testCallToCreateWillSucceedWhenNameIsValid(): void stream_get_contents($this->outputStream) ); - $this->assertSame($this->dataProvider(), $type->read()); + $this->assertSame($this->expectedContent(), $type->read()); } - private function dataProvider(): string + private function expectedContent(): string { $uses = [ sprintf('use %s;', $this->import->getAppMessageFqcn()), diff --git a/test/Type/MiddlewareTest.php b/test/Type/MiddlewareTest.php index ec4dc9f..3664248 100644 --- a/test/Type/MiddlewareTest.php +++ b/test/Type/MiddlewareTest.php @@ -13,11 +13,11 @@ use Dot\Maker\IO\Output; use Dot\Maker\Type\Middleware; use Dot\Maker\Type\Module; +use DotTest\Maker\StreamTrait; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function fwrite; use function implode; use function rewind; @@ -28,6 +28,8 @@ class MiddlewareTest extends TestCase { + use StreamTrait; + private Config $config; private Context $context; private FileSystem $fileSystem; @@ -59,13 +61,13 @@ protected function setUp(): void $this->fileSystem = (new FileSystem($this->context))->setModuleName($this->moduleName); $this->module = new Module($this->fileSystem, $this->context, $this->config); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -162,7 +164,7 @@ public function testCallToInvokeWillSucceedWhenNameIsValidAndServiceDoesNotExist $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProviderWithoutService(), $file->read()); + $this->assertSame($this->expectedWithoutService(), $file->read()); } public function testCallToCreateWillSucceedWhenNameIsValidAndServiceDoesNotExist(): void @@ -187,7 +189,7 @@ public function testCallToCreateWillSucceedWhenNameIsValidAndServiceDoesNotExist stream_get_contents($this->outputStream) ); - $this->assertSame($this->dataProviderWithoutService(), $file->read()); + $this->assertSame($this->expectedWithoutService(), $file->read()); } public function testCallToInvokeWillSucceedWhenNameIsValidAndServiceDoesExist(): void @@ -210,7 +212,7 @@ public function testCallToInvokeWillSucceedWhenNameIsValidAndServiceDoesExist(): $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProviderWithService($serviceInterface), $file->read()); + $this->assertSame($this->expectedWithService($serviceInterface), $file->read()); } public function testCallToCreateWillSucceedWhenNameIsValidAndServiceDoesExist(): void @@ -240,10 +242,10 @@ public function testCallToCreateWillSucceedWhenNameIsValidAndServiceDoesExist(): stream_get_contents($this->outputStream) ); - $this->assertSame($this->dataProviderWithService($serviceInterface), $file->read()); + $this->assertSame($this->expectedWithService($serviceInterface), $file->read()); } - private function dataProviderWithService(File $serviceInterface): string + private function expectedWithService(File $serviceInterface): string { $uses = [ sprintf('use %s;', $serviceInterface->getComponent()->getFqcn()), @@ -287,7 +289,7 @@ public function process( BODY; } - private function dataProviderWithoutService(): string + private function expectedWithoutService(): string { $uses = [ sprintf('use %s;', Import::PSR_HTTP_MESSAGE_RESPONSEINTERFACE), diff --git a/test/Type/ModuleTest.php b/test/Type/ModuleTest.php index 8886614..3ac34d4 100644 --- a/test/Type/ModuleTest.php +++ b/test/Type/ModuleTest.php @@ -12,11 +12,11 @@ use Dot\Maker\IO\Output; use Dot\Maker\Message; use Dot\Maker\Type\Module; +use DotTest\Maker\StreamTrait; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function fwrite; use function rewind; use function stream_get_contents; @@ -25,6 +25,8 @@ class ModuleTest extends TestCase { + use StreamTrait; + private Config $config; private Context $context; private FileSystem $fileSystem; @@ -40,13 +42,13 @@ class ModuleTest extends TestCase protected function setUp(): void { - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -244,7 +246,11 @@ public function testWillAddMessage(): void $this->assertEmpty($module->getMessages()); $module->addMessage(new Message('test')); $this->assertCount(1, $module->getMessages()); - $this->assertSame('test', $module->getMessages()[0]); + $this->assertSame(['test' => 'test'], $module->getMessages()[0]); + + $module->addMessage(new Message('other')); + $module->addMessage(new Message('test')); + $this->assertSame(['test' => 'test', 'other' => 'other'], $module->getMessages()[0]); } public function testInitExistingWillNotInitWhenInvalidModuleName(): void @@ -554,7 +560,7 @@ public function testWillCreateFilesWhenProjectTypeIsApiAndUsesCore(): void rewind($this->outputStream); $this->assertEmpty(stream_get_contents($this->errorStream)); $this->assertSame( - $this->dataProviderWhenProjectTypeIsApiAndUsesCore(), + $this->expectedWhenProjectTypeIsApiAndUsesCore(), stream_get_contents($this->outputStream) ); } @@ -720,7 +726,7 @@ public function testWillCreateFilesWhenProjectTypeIsApiAndDoesNotUseCore(): void rewind($this->outputStream); $this->assertEmpty(stream_get_contents($this->errorStream)); $this->assertSame( - $this->dataProviderWhenProjectTypeIsApiAndDoesNotUseCore(), + $this->expectedWhenProjectTypeIsApiAndDoesNotUseCore(), stream_get_contents($this->outputStream) ); } @@ -886,7 +892,7 @@ public function testWillCreateFilesWhenProjectTypeIsNotApiAndUsesCore(): void rewind($this->outputStream); $this->assertEmpty(stream_get_contents($this->errorStream)); $this->assertSame( - $this->dataProviderWhenProjectTypeIsNotApiAndUsesCore(), + $this->expectedWhenProjectTypeIsNotApiAndUsesCore(), stream_get_contents($this->outputStream) ); } @@ -1051,12 +1057,12 @@ public function testWillCreateFilesWhenProjectTypeIsNootApiAndDoesNotUseCore(): rewind($this->outputStream); $this->assertEmpty(stream_get_contents($this->errorStream)); $this->assertSame( - $this->dataProviderWhenProjectTypeIsNotApiAndDoesNotUseCore(), + $this->expectedWhenProjectTypeIsNotApiAndDoesNotUseCore(), stream_get_contents($this->outputStream) ); } - private function dataProviderWhenProjectTypeIsApiAndUsesCore(): string + private function expectedWhenProjectTypeIsApiAndUsesCore(): string { // phpcs:disable Generic.Files.LineLength.TooLong return <<outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); } @@ -133,7 +135,7 @@ public function testWillCreateFile(): void rewind($this->outputStream); $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProviderRenderedOpenApi(), $file->read()); + $this->assertSame($this->expectedRenderedOpenApi(), $file->read()); $this->assertSame( ColorEnum::colorize( 'Created OpenAPI: vfs://root/src/ModuleName/src/OpenAPI.php', @@ -143,7 +145,7 @@ public function testWillCreateFile(): void ); } - private function dataProviderRenderedOpenApi(): string + private function expectedRenderedOpenApi(): string { return <<project('Admin'); + $existing = $this->fileSystem->createResourceForm('Book'); + $existing->create('existing'); + + $this->answer('Book'); + (new Form($this->fileSystem, $this->context, $this->config, $this->module))(); + + $this->assertStringContainsString( + sprintf('Class "CreateBookForm" already exists at %s', $existing->getPath()), + $this->errors() + ); + } + + public function testFormCreateInApiReturnsTheFileWithoutCreatingIt(): void + { + $this->project('Api'); + + $form = (new Form($this->fileSystem, $this->context, $this->config, $this->module))->create('Book'); + + $this->assertSame('BookForm', $form->getComponent()->getClassName()); + $this->assertFalse($form->exists()); + } + + public function testHandlerReportsErrorAndKeepsPrompting(): void + { + $this->project('Admin'); + $existing = $this->fileSystem->getListResourcesHandler('Book'); + $existing->create('existing'); + + $this->answer('Book'); + (new Handler($this->fileSystem, $this->context, $this->config, $this->module))(); + + $this->assertStringContainsString( + sprintf('Class "GetListBookHandler" already exists at %s', $existing->getPath()), + $this->errors() + ); + } + + public function testInputFilterReportsErrorAndKeepsPrompting(): void + { + $this->project('Admin'); + $existing = $this->fileSystem->createResourceInputFilter('Book'); + $existing->create('existing'); + + $this->answer('Book'); + (new InputFilter($this->fileSystem, $this->context, $this->config, $this->module))(); + + $this->assertStringContainsString( + sprintf('Class "CreateBookInputFilter" already exists at %s', $existing->getPath()), + $this->errors() + ); + } + + public function testModuleReportsErrorFromAComponent(): void + { + $this->project('Api'); + $this->fileSystem->setModuleName('Shelf'); + $existing = $this->fileSystem->coreConfigProvider(); + $existing->create('existing'); + + $this->answer('Shelf'); + $module = new Module($this->fileSystem, $this->context, $this->config); + $module->setModule($module); + $module(); + + $this->assertStringContainsString( + sprintf('Class "ConfigProvider" already exists at %s', $existing->getPath()), + $this->errors() + ); + } + + /** + * A project with Core architecture and the module "Book". + */ + private function project(string $projectType): void + { + $root = vfsStream::setup('root', 0755, [ + 'composer.json' => sprintf( + '{"autoload":{"psr-4":{"%s\\\\App\\\\":"src/App/src/","Core\\\\App\\\\":"src/Core/src/App/src/"}}}', + $projectType + ), + 'src' => [ + 'Book' => [ + 'src' => [], + ], + 'Core' => [ + 'src' => [], + ], + ], + ]); + + $this->config = new Config($root->url()); + $this->context = new Context($root->url()); + $this->fileSystem = (new FileSystem($this->context))->setModuleName('Book'); + $this->module = new Module($this->fileSystem, $this->context, $this->config); + + $this->errorStream = $this->openMemoryStream(); + Output::setErrorStream($this->errorStream); + Output::setOutputStream($this->openMemoryStream()); + } + + /** + * Answers followed by the end of input: every confirmation then takes its default ("yes"), + * and the name prompt receives a blank answer, which ends the loop. + */ + private function answer(string ...$lines): void + { + $stream = $this->openMemoryStream(); + foreach ($lines as $line) { + fwrite($stream, $line . PHP_EOL); + } + rewind($stream); + Input::setStream($stream); + } + + private function errors(): string + { + rewind($this->errorStream); + + return (string) preg_replace('/\e\[\d+(;\d+)?m/', '', (string) stream_get_contents($this->errorStream)); + } +} diff --git a/test/Type/RepositoryTest.php b/test/Type/RepositoryTest.php index c841c49..71f0615 100644 --- a/test/Type/RepositoryTest.php +++ b/test/Type/RepositoryTest.php @@ -11,11 +11,12 @@ use Dot\Maker\IO\Output; use Dot\Maker\Type\Module; use Dot\Maker\Type\Repository; +use DotTest\Maker\StreamTrait; use org\bovigo\vfs\vfsStream; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function fwrite; use function rewind; use function sprintf; @@ -25,6 +26,8 @@ class RepositoryTest extends TestCase { + use StreamTrait; + private Config $config; private Context $context; private FileSystem $fileSystem; @@ -57,13 +60,13 @@ protected function setUp(): void $this->fileSystem = (new FileSystem($this->context))->setModuleName($this->moduleName); $this->module = new Module($this->fileSystem, $this->context, $this->config); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -145,9 +148,7 @@ public function testCallToInvokeWillOutputErrorAndWillNotCreateFileWhenNameIsInv $this->assertFileDoesNotExist($file->getPath()); } - /** - * @dataProvider dataProvider - */ + #[DataProvider('dataProvider')] public function testCallToInvokeWillSucceedWhenNameIsValid(string $expected): void { $file = $this->fileSystem->repository($this->resourceName); @@ -166,9 +167,7 @@ public function testCallToInvokeWillSucceedWhenNameIsValid(string $expected): vo $this->assertSame($expected, $file->read()); } - /** - * @dataProvider dataProvider - */ + #[DataProvider('dataProvider')] public function testCallToCreateWillSucceedWhenNameIsValid(string $expected): void { $file = $this->fileSystem->repository($this->resourceName); @@ -194,6 +193,9 @@ public function testCallToCreateWillSucceedWhenNameIsValid(string $expected): vo $this->assertSame($expected, $type->read()); } + /** + * @return array + */ public static function dataProvider(): array { $repository = <<openMemoryStream(); Output::setOutputStream($stream); $root = vfsStream::setup('root', 0644, [ @@ -73,12 +74,10 @@ public function testCallToCreateWhenProjectTypeIsNotApiWillCreateFile(string $ex fclose($stream); } - /** - * @dataProvider dataProviderApi - */ + #[DataProvider('dataProviderApi')] public function testCallToCreateWhenProjectTypeIsApiWillCreateFile(string $expected): void { - $stream = fopen('php://memory', 'w+'); + $stream = $this->openMemoryStream(); Output::setOutputStream($stream); $root = vfsStream::setup('root', 0644, [ @@ -119,6 +118,9 @@ public function testCallToCreateWhenProjectTypeIsApiWillCreateFile(string $expec fclose($stream); } + /** + * @return array + */ public static function dataProvider(): array { // phpcs:disable Generic.Files.LineLength.TooLong @@ -182,6 +184,9 @@ public function __invoke( ]; } + /** + * @return array + */ public static function dataProviderApi(): array { // phpcs:disable Generic.Files.LineLength.TooLong diff --git a/test/Type/ServiceInterfaceTest.php b/test/Type/ServiceInterfaceTest.php index f2b474f..e4e7638 100644 --- a/test/Type/ServiceInterfaceTest.php +++ b/test/Type/ServiceInterfaceTest.php @@ -13,11 +13,11 @@ use Dot\Maker\IO\Output; use Dot\Maker\Type\Module; use Dot\Maker\Type\ServiceInterface; +use DotTest\Maker\StreamTrait; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function fwrite; use function implode; use function rewind; @@ -28,6 +28,8 @@ class ServiceInterfaceTest extends TestCase { + use StreamTrait; + private Config $config; private Context $context; private FileSystem $fileSystem; @@ -62,13 +64,13 @@ protected function setUp(): void $this->import = new Import($this->context); $this->module = new Module($this->fileSystem, $this->context, $this->config); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -178,7 +180,7 @@ public function testCallToInvokeWillSucceedWhenNameIsValidAndProjectTypeIsNotApi $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProviderNotApi($entity, $repository), $file->read()); + $this->assertSame($this->expectedNotApi($entity, $repository), $file->read()); } public function testCallToCreateWillSucceedWhenNameIsValidAndProjectTypeIsNotApi(): void @@ -206,7 +208,7 @@ public function testCallToCreateWillSucceedWhenNameIsValidAndProjectTypeIsNotApi $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProviderNotApi($entity, $repository), $file->read()); + $this->assertSame($this->expectedNotApi($entity, $repository), $file->read()); } public function testCallToInvokeWillSucceedWhenNameIsValidAndProjectTypeIsApi(): void @@ -250,7 +252,7 @@ public function testCallToInvokeWillSucceedWhenNameIsValidAndProjectTypeIsApi(): $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProviderApi($entity, $repository), $file->read()); + $this->assertSame($this->expectedApi($entity, $repository), $file->read()); } public function testCallToCreateWillSucceedWhenNameIsValidAndProjectTypeIsApi(): void @@ -294,10 +296,10 @@ public function testCallToCreateWillSucceedWhenNameIsValidAndProjectTypeIsApi(): $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProviderApi($entity, $repository), $file->read()); + $this->assertSame($this->expectedApi($entity, $repository), $file->read()); } - private function dataProviderNotApi(File $entity, File $repository): string + private function expectedNotApi(File $entity, File $repository): string { $uses = [ sprintf('use %s;', $this->import->getNotFoundExceptionFqcn()), @@ -349,7 +351,7 @@ public function findBookStore( BODY; } - private function dataProviderApi(File $entity, File $repository): string + private function expectedApi(File $entity, File $repository): string { $uses = [ sprintf('use %s;', $entity->getComponent()->getFqcn()), diff --git a/test/Type/ServiceTest.php b/test/Type/ServiceTest.php index 36cb93b..d3a18fd 100644 --- a/test/Type/ServiceTest.php +++ b/test/Type/ServiceTest.php @@ -13,11 +13,11 @@ use Dot\Maker\IO\Output; use Dot\Maker\Type\Module; use Dot\Maker\Type\Service; +use DotTest\Maker\StreamTrait; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use function fclose; -use function fopen; use function fwrite; use function implode; use function rewind; @@ -28,6 +28,8 @@ class ServiceTest extends TestCase { + use StreamTrait; + private Config $config; private Context $context; private FileSystem $fileSystem; @@ -62,13 +64,13 @@ protected function setUp(): void $this->import = new Import($this->context); $this->module = new Module($this->fileSystem, $this->context, $this->config); - $this->outputStream = fopen('php://memory', 'w+'); + $this->outputStream = $this->openMemoryStream(); Output::setOutputStream($this->outputStream); - $this->errorStream = fopen('php://memory', 'w+'); + $this->errorStream = $this->openMemoryStream(); Output::setErrorStream($this->errorStream); - $this->inputStream = fopen('php://memory', 'w+'); + $this->inputStream = $this->openMemoryStream(); Input::setStream($this->inputStream); } @@ -175,7 +177,7 @@ public function testCallToInvokeWillSucceedWhenNameIsValidAndProjectTypeIsNotApi $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProviderNotApi($entity, $repository), $file->read()); + $this->assertSame($this->expectedNotApi($entity, $repository), $file->read()); } public function testCallToCreateWillSucceedWhenNameIsValidAndProjectTypeIsNotApi(): void @@ -203,7 +205,7 @@ public function testCallToCreateWillSucceedWhenNameIsValidAndProjectTypeIsNotApi $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProviderNotApi($entity, $repository), $file->read()); + $this->assertSame($this->expectedNotApi($entity, $repository), $file->read()); } public function testCallToInvokeWillSucceedWhenNameIsValidAndProjectTypeIsApi(): void @@ -247,7 +249,7 @@ public function testCallToInvokeWillSucceedWhenNameIsValidAndProjectTypeIsApi(): $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProviderApi($entity, $repository), $file->read()); + $this->assertSame($this->expectedApi($entity, $repository), $file->read()); } public function testCallToCreateWillSucceedWhenNameIsValidAndProjectTypeIsApi(): void @@ -291,10 +293,10 @@ public function testCallToCreateWillSucceedWhenNameIsValidAndProjectTypeIsApi(): $this->assertFileExists($file->getPath()); $this->assertTrue($file->exists()); - $this->assertSame($this->dataProviderApi($entity, $repository), $file->read()); + $this->assertSame($this->expectedApi($entity, $repository), $file->read()); } - private function dataProviderNotApi(File $entity, File $repository): string + private function expectedNotApi(File $entity, File $repository): string { $uses = [ sprintf('use %s;', $this->import->getNotFoundExceptionFqcn()), @@ -397,7 +399,7 @@ public function findBookStore( // phpcs:enable Generic.Files.LineLength.TooLong } - private function dataProviderApi(File $entity, File $repository): string + private function expectedApi(File $entity, File $repository): string { $uses = [ sprintf('use %s;', $this->import->getAppHelperPaginatorFqcn()),