Skip to content

Commit da9f2f7

Browse files
authored
[php-slim4] Move config to a separate file (#6971)
* Move config into separated file * Restrict access from web to config folder * Exclude config folder from code base * Update documentation * Refresh samples * Fix misplaced pathes
1 parent 2c65605 commit da9f2f7

13 files changed

Lines changed: 349 additions & 172 deletions

File tree

modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,9 @@ public void processOpts() {
123123

124124
// Slim 4 doesn't parse JSON body anymore we need to add suggested middleware
125125
// ref: https://www.slimframework.com/docs/v4/objects/request.html#the-request-body
126+
supportingFiles.add(new SupportingFile("htaccess_deny_all", "config", ".htaccess"));
127+
supportingFiles.add(new SupportingFile("config_example.mustache", "config" + File.separator + "dev", "example.inc.php"));
128+
supportingFiles.add(new SupportingFile("config_example.mustache", "config" + File.separator + "prod", "example.inc.php"));
126129
supportingFiles.add(new SupportingFile("json_body_parser_middleware.mustache", toSrcPath(invokerPackage + "\\Middleware", srcBasePath), "JsonBodyParserMiddleware.php"));
127130
supportingFiles.add(new SupportingFile("base_model.mustache", toSrcPath(invokerPackage, srcBasePath), "BaseModel.php"));
128131
supportingFiles.add(new SupportingFile("base_model_test.mustache", toSrcPath(invokerPackage, testBasePath), "BaseModelTest.php"));

modules/openapi-generator/src/main/resources/php-slim4-server/README.mustache

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ This command downloads the Slim Framework and its third-party dependencies into
3232
$ composer install
3333
```
3434

35+
## Add configs
36+
37+
Application requires at least one config file(`config/dev/config.inc.php` or `config/prod/config.inc.php`). You can use [config/dev/example.inc.php](config/dev/example.inc.php) as starting point.
38+
3539
## Start devserver
3640

3741
Run the following command in terminal to start localhost web server, assuming `./php-slim-server/` is public-accessible directory with `index.php` file:
@@ -93,25 +97,19 @@ $ composer phplint
9397

9498
## Show errors
9599

96-
Switch on option in `./index.php`:
100+
Switch on option in your application config file like:
97101
```diff
98-
/**
99-
* Add Error Handling Middleware
100-
*
101-
* @param bool $displayErrorDetails -> Should be set to false in production
102-
* @param bool $logErrors -> Parameter is passed to the default ErrorHandler
103-
* @param bool $logErrorDetails -> Display error details in error log
104-
* which can be replaced by a callable of your choice.
105-
106-
* Note: This middleware should be added last. It will not handle any exceptions/errors
107-
* for middleware added after it.
108-
*/
109-
--- $app->addErrorMiddleware(false, true, true);
110-
+++ $app->addErrorMiddleware(true, true, true);
102+
return [
103+
'slimSettings' => [
104+
- 'displayErrorDetails' => false,
105+
+ 'displayErrorDetails' => true,
106+
'logErrors' => true,
107+
'logErrorDetails' => true,
108+
],
111109
```
112110

113111
## Mock Server
114-
For a quick start uncomment [mocker middleware config](index.php#L62-L89).
112+
For a quick start uncomment [mocker middleware options](config/dev/example.inc.php#L67-L94) in your application config file.
115113

116114
Used packages:
117115
* [Openapi Data Mocker](https://github.com/ybelenko/openapi-data-mocker) - first implementation of OAS3 fake data generator.
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
<?php
2+
3+
{{>licenseInfo}}
4+
5+
/**
6+
* App configuration file example.
7+
*
8+
* Copy file to config/dev/config.inc.php and config/prod/config.inc.php
9+
* App loads dev config only when prod doesn't exist
10+
* in other words if both configs presented - prod config applies
11+
*/
12+
13+
use Psr\Http\Message\ServerRequestInterface;
14+
use Psr\Http\Message\ResponseInterface;
15+
use OpenAPIServer\Mock\OpenApiDataMocker;
16+
17+
$mocker = new OpenApiDataMocker();
18+
$mocker->setModelsNamespace('{{modelPackage}}\\');
19+
20+
return [
21+
'slimSettings' => [
22+
'displayErrorDetails' => false,
23+
'logErrors' => true,
24+
'logErrorDetails' => true,
25+
],
26+
27+
'tokenAuthenticationOptions' => [
28+
/**
29+
* Tokens are essentially passwords. You should treat them as such and you should always
30+
* use HTTPS. If the middleware detects insecure usage over HTTP it will return unauthorized
31+
* with a message Required HTTPS for token authentication. This rule is relaxed for requests
32+
* on localhost. To allow insecure usage you must enable it manually by setting secure to
33+
* false.
34+
* Default: true
35+
*/
36+
// 'secure' => true,
37+
38+
/**
39+
* Alternatively you can list your development host to have relaxed security.
40+
* Default: ['localhost', '127.0.0.1']
41+
*/
42+
// 'relaxed' => ['localhost', '127.0.0.1'],
43+
44+
/**
45+
* By default on ocurred a fail on authentication, is sent a response on json format with a
46+
* message (`Invalid Token` or `Not found Token`) and with the token (if found), with status
47+
* `401 Unauthorized`. You can customize it by setting a callable function on error option.
48+
* Default: null
49+
*/
50+
// 'error' => null,
51+
],
52+
53+
'mockerOptions' => [
54+
// 'dataMocker' => $mocker,
55+
56+
// 'getMockStatusCodeCallback' => function (ServerRequestInterface $request, array $responses) {
57+
// // check if client clearly asks for mocked response
58+
// $pingHeader = 'X-{{invokerPackage}}-Mock';
59+
// $pingHeaderCode = 'X-{{invokerPackage}}-Mock-Code';
60+
// if (
61+
// $request->hasHeader($pingHeader)
62+
// && $request->getHeader($pingHeader)[0] === 'ping'
63+
// ) {
64+
// $responses = (array) $responses;
65+
// $requestedResponseCode = ($request->hasHeader($pingHeaderCode)) ? $request->getHeader($pingHeaderCode)[0] : 'default';
66+
// if (array_key_exists($requestedResponseCode, $responses)) {
67+
// return $requestedResponseCode;
68+
// }
69+
70+
// // return first response key
71+
// reset($responses);
72+
// return key($responses);
73+
// }
74+
75+
// return false;
76+
// },
77+
78+
// 'afterCallback' => function (ServerRequestInterface $request, ResponseInterface $response) {
79+
// // mark mocked response to distinguish real and fake responses
80+
// return $response->withHeader('X-{{invokerPackage}}-Mock', 'pong');
81+
// },
82+
],
83+
];

modules/openapi-generator/src/main/resources/php-slim4-server/gitignore

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,10 @@ composer.phar
1515
/.phpunit.result.cache
1616

1717
# Do not commit local PHP_CodeSniffer config
18-
/phpcs.xml
18+
/phpcs.xml
19+
20+
# Application config may contain sensitive data
21+
/config/**/*.*
22+
!/config/.htaccess
23+
!/config/dev/example.inc.php
24+
!/config/prod/example.inc.php
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Deny from all

modules/openapi-generator/src/main/resources/php-slim4-server/index.mustache

Lines changed: 13 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -15,76 +15,15 @@ use Psr\Http\Message\ResponseInterface;
1515
use OpenAPIServer\Mock\OpenApiDataMocker;
1616
{{/apiInfo}}
1717

18+
// load config file
1819
$config = [];
19-
20-
/**
21-
* Token Middleware 1.x Options
22-
* Options `header`, `regex`, `parameter`, `cookie`, `attribute`, `path`, `except`, `authenticator`
23-
* are handled by SlimRouter class. These options are ignored by app and they omitted from current
24-
* example.
25-
* Ref: https://github.com/dyorg/slim-token-authentication/tree/1.x
26-
*/
27-
$config['tokenAuthenticationOptions'] = [
28-
/**
29-
* Tokens are essentially passwords. You should treat them as such and you should always
30-
* use HTTPS. If the middleware detects insecure usage over HTTP it will return unathorized
31-
* with a message Required HTTPS for token authentication. This rule is relaxed for requests
32-
* on localhost. To allow insecure usage you must enable it manually by setting secure to
33-
* false.
34-
* Default: true
35-
*/
36-
// 'secure' => true,
37-
38-
/**
39-
* Alternatively you can list your development host to have relaxed security.
40-
* Default: ['localhost', '127.0.0.1']
41-
*/
42-
// 'relaxed' => ['localhost', '127.0.0.1'],
43-
44-
/**
45-
* By default on ocurred a fail on authentication, is sent a response on json format with a
46-
* message (`Invalid Token` or `Not found Token`) and with the token (if found), with status
47-
* `401 Unauthorized`. You can customize it by setting a callable function on error option.
48-
* Default: null
49-
*/
50-
// 'error' => null,
51-
];
52-
53-
/**
54-
* Mocker Middleware options.
55-
*/
56-
$mocker = new OpenApiDataMocker();
57-
$mocker->setModelsNamespace('{{modelPackage}}\\');
58-
$config['mockerOptions'] = [
59-
// 'dataMocker' => $mocker,
60-
61-
// 'getMockStatusCodeCallback' => function (ServerRequestInterface $request, $responses) {
62-
// // check if client clearly asks for mocked response
63-
// $pingHeader = 'X-{{invokerPackage}}-Mock';
64-
// $pingHeaderCode = 'X-{{invokerPackage}}-Mock-Code';
65-
// if (
66-
// $request->hasHeader($pingHeader)
67-
// && $request->getHeader($pingHeader)[0] === 'ping'
68-
// ) {
69-
// $responses = (array) $responses;
70-
// $requestedResponseCode = ($request->hasHeader($pingHeaderCode)) ? $request->getHeader($pingHeaderCode)[0] : 'default';
71-
// if (array_key_exists($requestedResponseCode, $responses)) {
72-
// return $requestedResponseCode;
73-
// }
74-
75-
// // return first response key
76-
// reset($responses);
77-
// return key($responses);
78-
// }
79-
80-
// return false;
81-
// },
82-
83-
// 'afterCallback' => function ($request, $response) {
84-
// // mark mocked response to distinguish real and fake responses
85-
// return $response->withHeader('X-{{invokerPackage}}-Mock', 'pong');
86-
// },
87-
];
20+
if (is_array($prodConfig = @include(__DIR__ . '/config/prod/config.inc.php'))) {
21+
$config = $prodConfig;
22+
} elseif (is_array($devConfig = @include(__DIR__ . '/config/dev/config.inc.php'))) {
23+
$config = $devConfig;
24+
} else {
25+
throw new InvalidArgumentException('Config file missed or broken.');
26+
}
8827

8928
$router = new SlimRouter($config);
9029
$app = $router->getSlimApp();
@@ -106,6 +45,10 @@ $app->addRoutingMiddleware();
10645
* Note: This middleware should be added last. It will not handle any exceptions/errors
10746
* for middleware added after it.
10847
*/
109-
$app->addErrorMiddleware(false, true, true);
48+
$app->addErrorMiddleware(
49+
$config['slimSettings']['displayErrorDetails'] ?? false,
50+
$config['slimSettings']['logErrors'] ?? true,
51+
$config['slimSettings']['logErrorDetails'] ?? true
52+
);
11053

11154
$app->run();

samples/server/petstore/php-slim4/.gitignore

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,10 @@ composer.phar
1515
/.phpunit.result.cache
1616

1717
# Do not commit local PHP_CodeSniffer config
18-
/phpcs.xml
18+
/phpcs.xml
19+
20+
# Application config may contain sensitive data
21+
/config/**/*.*
22+
!/config/.htaccess
23+
!/config/dev/example.inc.php
24+
!/config/prod/example.inc.php

samples/server/petstore/php-slim4/.openapi-generator/FILES

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
.htaccess
33
README.md
44
composer.json
5+
config/.htaccess
6+
config/dev/example.inc.php
7+
config/prod/example.inc.php
58
index.php
69
lib/Api/AbstractPetApi.php
710
lib/Api/AbstractStoreApi.php

samples/server/petstore/php-slim4/README.md

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ This command downloads the Slim Framework and its third-party dependencies into
2121
$ composer install
2222
```
2323

24+
## Add configs
25+
26+
Application requires at least one config file(`config/dev/config.inc.php` or `config/prod/config.inc.php`). You can use [config/dev/example.inc.php](config/dev/example.inc.php) as starting point.
27+
2428
## Start devserver
2529

2630
Run the following command in terminal to start localhost web server, assuming `./php-slim-server/` is public-accessible directory with `index.php` file:
@@ -82,25 +86,19 @@ $ composer phplint
8286

8387
## Show errors
8488

85-
Switch on option in `./index.php`:
89+
Switch on option in your application config file like:
8690
```diff
87-
/**
88-
* Add Error Handling Middleware
89-
*
90-
* @param bool $displayErrorDetails -> Should be set to false in production
91-
* @param bool $logErrors -> Parameter is passed to the default ErrorHandler
92-
* @param bool $logErrorDetails -> Display error details in error log
93-
* which can be replaced by a callable of your choice.
94-
95-
* Note: This middleware should be added last. It will not handle any exceptions/errors
96-
* for middleware added after it.
97-
*/
98-
--- $app->addErrorMiddleware(false, true, true);
99-
+++ $app->addErrorMiddleware(true, true, true);
91+
return [
92+
'slimSettings' => [
93+
- 'displayErrorDetails' => false,
94+
+ 'displayErrorDetails' => true,
95+
'logErrors' => true,
96+
'logErrorDetails' => true,
97+
],
10098
```
10199

102100
## Mock Server
103-
For a quick start uncomment [mocker middleware config](index.php#L62-L89).
101+
For a quick start uncomment [mocker middleware options](config/dev/example.inc.php#L67-L94) in your application config file.
104102

105103
Used packages:
106104
* [Openapi Data Mocker](https://github.com/ybelenko/openapi-data-mocker) - first implementation of OAS3 fake data generator.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Deny from all

0 commit comments

Comments
 (0)