Skip to content

[PHP] Add declareStrictTypes option to AbstractPhpCodegen to generate declare(strict_types=1); #21179

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: master
Choose a base branch
from

Conversation

Gosling-dude
Copy link

Summary

This PR introduces support for a new generator option: declareStrictTypes for PHP code generation.

When enabled via --additional-properties=declareStrictTypes=true, the generated PHP files will start with:

<?php
declare(strict_types=1);

This enforces strict typing in the generated PHP client code, promoting best practices for modern PHP development.

Affected Files

Codegen Core:

  • AbstractPhpCodegen.java

    → Added support for the declareStrictTypes property and updated the help message.

  • PHP Template Files:

Located in modules/openapi-generator/src/main/resources/php/

- model.mustache
- api.mustache
- api_test.mustache
- model_test.mustache
  • Other templates starting with <?php

All updated to conditionally include:

{{#declareStrictTypes}}declare(strict_types=1);{{/declareStrictTypes}}

Usage Example

To generate PHP code with declare(strict_types=1); included at the top of the files, run:


java -jar openapi-generator-cli.jar generate \
  -g php \
  --additional-properties=declareStrictTypes=true \
  -i https://raw.githubusercontent.com/OpenAPITools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml \
  -o /tmp/test-php

Then check any generated file (e.g., ApiClient.php) for:


<?php
declare(strict_types=1);

Fixes: #12771

Thank you for reviewing this contribution! 🙏

@@ -1,4 +1,6 @@
<?php
{{#declareStrictTypes}}declare(strict_types=1);{{/declareStrictTypes}}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

better do in the following way

{{#declareStrictTypes}}
declare(strict_types=1);
{{/declareStrictTypes}}

to avoid blank lines

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I'll do it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants