Skip to content

[php-slim4] Move config to a separate file #6971

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

Merged
merged 6 commits into from
Aug 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@ public void processOpts() {

// Slim 4 doesn't parse JSON body anymore we need to add suggested middleware
// ref: https://www.slimframework.com/docs/v4/objects/request.html#the-request-body
supportingFiles.add(new SupportingFile("htaccess_deny_all", "config", ".htaccess"));
supportingFiles.add(new SupportingFile("config_example.mustache", "config" + File.separator + "dev", "example.inc.php"));
supportingFiles.add(new SupportingFile("config_example.mustache", "config" + File.separator + "prod", "example.inc.php"));
supportingFiles.add(new SupportingFile("json_body_parser_middleware.mustache", toSrcPath(invokerPackage + "\\Middleware", srcBasePath), "JsonBodyParserMiddleware.php"));
supportingFiles.add(new SupportingFile("base_model.mustache", toSrcPath(invokerPackage, srcBasePath), "BaseModel.php"));
supportingFiles.add(new SupportingFile("base_model_test.mustache", toSrcPath(invokerPackage, testBasePath), "BaseModelTest.php"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ This command downloads the Slim Framework and its third-party dependencies into
$ composer install
```

## Add configs

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.

## Start devserver

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

## Show errors

Switch on option in `./index.php`:
Switch on option in your application config file like:
```diff
/**
* Add Error Handling Middleware
*
* @param bool $displayErrorDetails -> Should be set to false in production
* @param bool $logErrors -> Parameter is passed to the default ErrorHandler
* @param bool $logErrorDetails -> Display error details in error log
* which can be replaced by a callable of your choice.

* Note: This middleware should be added last. It will not handle any exceptions/errors
* for middleware added after it.
*/
--- $app->addErrorMiddleware(false, true, true);
+++ $app->addErrorMiddleware(true, true, true);
return [
'slimSettings' => [
- 'displayErrorDetails' => false,
+ 'displayErrorDetails' => true,
'logErrors' => true,
'logErrorDetails' => true,
],
```

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

Used packages:
* [Openapi Data Mocker](https://github.com/ybelenko/openapi-data-mocker) - first implementation of OAS3 fake data generator.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

{{>licenseInfo}}

/**
* App configuration file example.
*
* Copy file to config/dev/config.inc.php and config/prod/config.inc.php
* App loads dev config only when prod doesn't exist
* in other words if both configs presented - prod config applies
*/

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use OpenAPIServer\Mock\OpenApiDataMocker;

$mocker = new OpenApiDataMocker();
$mocker->setModelsNamespace('{{modelPackage}}\\');

return [
'slimSettings' => [
'displayErrorDetails' => false,
'logErrors' => true,
'logErrorDetails' => true,
],

'tokenAuthenticationOptions' => [
/**
* Tokens are essentially passwords. You should treat them as such and you should always
* use HTTPS. If the middleware detects insecure usage over HTTP it will return unauthorized
* with a message Required HTTPS for token authentication. This rule is relaxed for requests
* on localhost. To allow insecure usage you must enable it manually by setting secure to
* false.
* Default: true
*/
// 'secure' => true,

/**
* Alternatively you can list your development host to have relaxed security.
* Default: ['localhost', '127.0.0.1']
*/
// 'relaxed' => ['localhost', '127.0.0.1'],

/**
* By default on ocurred a fail on authentication, is sent a response on json format with a
* message (`Invalid Token` or `Not found Token`) and with the token (if found), with status
* `401 Unauthorized`. You can customize it by setting a callable function on error option.
* Default: null
*/
// 'error' => null,
],

'mockerOptions' => [
// 'dataMocker' => $mocker,

// 'getMockStatusCodeCallback' => function (ServerRequestInterface $request, array $responses) {
// // check if client clearly asks for mocked response
// $pingHeader = 'X-{{invokerPackage}}-Mock';
// $pingHeaderCode = 'X-{{invokerPackage}}-Mock-Code';
// if (
// $request->hasHeader($pingHeader)
// && $request->getHeader($pingHeader)[0] === 'ping'
// ) {
// $responses = (array) $responses;
// $requestedResponseCode = ($request->hasHeader($pingHeaderCode)) ? $request->getHeader($pingHeaderCode)[0] : 'default';
// if (array_key_exists($requestedResponseCode, $responses)) {
// return $requestedResponseCode;
// }

// // return first response key
// reset($responses);
// return key($responses);
// }

// return false;
// },

// 'afterCallback' => function (ServerRequestInterface $request, ResponseInterface $response) {
// // mark mocked response to distinguish real and fake responses
// return $response->withHeader('X-{{invokerPackage}}-Mock', 'pong');
// },
],
];
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,10 @@ composer.phar
/.phpunit.result.cache

# Do not commit local PHP_CodeSniffer config
/phpcs.xml
/phpcs.xml

# Application config may contain sensitive data
/config/**/*.*
!/config/.htaccess
!/config/dev/example.inc.php
!/config/prod/example.inc.php
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Deny from all
Original file line number Diff line number Diff line change
Expand Up @@ -15,76 +15,15 @@ use Psr\Http\Message\ResponseInterface;
use OpenAPIServer\Mock\OpenApiDataMocker;
{{/apiInfo}}

// load config file
$config = [];

/**
* Token Middleware 1.x Options
* Options `header`, `regex`, `parameter`, `cookie`, `attribute`, `path`, `except`, `authenticator`
* are handled by SlimRouter class. These options are ignored by app and they omitted from current
* example.
* Ref: https://github.com/dyorg/slim-token-authentication/tree/1.x
*/
$config['tokenAuthenticationOptions'] = [
/**
* Tokens are essentially passwords. You should treat them as such and you should always
* use HTTPS. If the middleware detects insecure usage over HTTP it will return unathorized
* with a message Required HTTPS for token authentication. This rule is relaxed for requests
* on localhost. To allow insecure usage you must enable it manually by setting secure to
* false.
* Default: true
*/
// 'secure' => true,

/**
* Alternatively you can list your development host to have relaxed security.
* Default: ['localhost', '127.0.0.1']
*/
// 'relaxed' => ['localhost', '127.0.0.1'],

/**
* By default on ocurred a fail on authentication, is sent a response on json format with a
* message (`Invalid Token` or `Not found Token`) and with the token (if found), with status
* `401 Unauthorized`. You can customize it by setting a callable function on error option.
* Default: null
*/
// 'error' => null,
];

/**
* Mocker Middleware options.
*/
$mocker = new OpenApiDataMocker();
$mocker->setModelsNamespace('{{modelPackage}}\\');
$config['mockerOptions'] = [
// 'dataMocker' => $mocker,

// 'getMockStatusCodeCallback' => function (ServerRequestInterface $request, $responses) {
// // check if client clearly asks for mocked response
// $pingHeader = 'X-{{invokerPackage}}-Mock';
// $pingHeaderCode = 'X-{{invokerPackage}}-Mock-Code';
// if (
// $request->hasHeader($pingHeader)
// && $request->getHeader($pingHeader)[0] === 'ping'
// ) {
// $responses = (array) $responses;
// $requestedResponseCode = ($request->hasHeader($pingHeaderCode)) ? $request->getHeader($pingHeaderCode)[0] : 'default';
// if (array_key_exists($requestedResponseCode, $responses)) {
// return $requestedResponseCode;
// }

// // return first response key
// reset($responses);
// return key($responses);
// }

// return false;
// },

// 'afterCallback' => function ($request, $response) {
// // mark mocked response to distinguish real and fake responses
// return $response->withHeader('X-{{invokerPackage}}-Mock', 'pong');
// },
];
if (is_array($prodConfig = @include(__DIR__ . '/config/prod/config.inc.php'))) {
$config = $prodConfig;
} elseif (is_array($devConfig = @include(__DIR__ . '/config/dev/config.inc.php'))) {
$config = $devConfig;
} else {
throw new InvalidArgumentException('Config file missed or broken.');
}

$router = new SlimRouter($config);
$app = $router->getSlimApp();
Expand All @@ -106,6 +45,10 @@ $app->addRoutingMiddleware();
* Note: This middleware should be added last. It will not handle any exceptions/errors
* for middleware added after it.
*/
$app->addErrorMiddleware(false, true, true);
$app->addErrorMiddleware(
$config['slimSettings']['displayErrorDetails'] ?? false,
$config['slimSettings']['logErrors'] ?? true,
$config['slimSettings']['logErrorDetails'] ?? true
);

$app->run();
8 changes: 7 additions & 1 deletion samples/server/petstore/php-slim4/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,10 @@ composer.phar
/.phpunit.result.cache

# Do not commit local PHP_CodeSniffer config
/phpcs.xml
/phpcs.xml

# Application config may contain sensitive data
/config/**/*.*
!/config/.htaccess
!/config/dev/example.inc.php
!/config/prod/example.inc.php
3 changes: 3 additions & 0 deletions samples/server/petstore/php-slim4/.openapi-generator/FILES
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
.htaccess
README.md
composer.json
config/.htaccess
config/dev/example.inc.php
config/prod/example.inc.php
index.php
lib/Api/AbstractPetApi.php
lib/Api/AbstractStoreApi.php
Expand Down
28 changes: 13 additions & 15 deletions samples/server/petstore/php-slim4/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ This command downloads the Slim Framework and its third-party dependencies into
$ composer install
```

## Add configs

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.

## Start devserver

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

## Show errors

Switch on option in `./index.php`:
Switch on option in your application config file like:
```diff
/**
* Add Error Handling Middleware
*
* @param bool $displayErrorDetails -> Should be set to false in production
* @param bool $logErrors -> Parameter is passed to the default ErrorHandler
* @param bool $logErrorDetails -> Display error details in error log
* which can be replaced by a callable of your choice.

* Note: This middleware should be added last. It will not handle any exceptions/errors
* for middleware added after it.
*/
--- $app->addErrorMiddleware(false, true, true);
+++ $app->addErrorMiddleware(true, true, true);
return [
'slimSettings' => [
- 'displayErrorDetails' => false,
+ 'displayErrorDetails' => true,
'logErrors' => true,
'logErrorDetails' => true,
],
```

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

Used packages:
* [Openapi Data Mocker](https://github.com/ybelenko/openapi-data-mocker) - first implementation of OAS3 fake data generator.
Expand Down
1 change: 1 addition & 0 deletions samples/server/petstore/php-slim4/config/.htaccess
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Deny from all
Loading