Skip to content

Commit

Permalink
Refresh samples
Browse files Browse the repository at this point in the history
  • Loading branch information
ybelenko committed Aug 18, 2020
1 parent 6f6ee6b commit 806896a
Show file tree
Hide file tree
Showing 7 changed files with 229 additions and 86 deletions.
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
96 changes: 96 additions & 0 deletions samples/server/petstore/php-slim4/config/dev/example.inc.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

/**
* OpenAPI Petstore
* PHP version 7.2
*
* @package OpenAPIServer
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/

/**
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/

/**
* 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('OpenAPIServer\Model\\');

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-OpenAPIServer-Mock';
// $pingHeaderCode = 'X-OpenAPIServer-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-OpenAPIServer-Mock', 'pong');
// },
],
];
96 changes: 96 additions & 0 deletions samples/server/petstore/php-slim4/config/prod/example.inc.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

/**
* OpenAPI Petstore
* PHP version 7.2
*
* @package OpenAPIServer
* @author OpenAPI Generator team
* @link https://github.com/openapitools/openapi-generator
*/

/**
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/

/**
* 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('OpenAPIServer\Model\\');

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-OpenAPIServer-Mock';
// $pingHeaderCode = 'X-OpenAPIServer-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-OpenAPIServer-Mock', 'pong');
// },
],
];
83 changes: 13 additions & 70 deletions samples/server/petstore/php-slim4/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,76 +27,15 @@
use Psr\Http\Message\ResponseInterface;
use OpenAPIServer\Mock\OpenApiDataMocker;

// 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('OpenAPIServer\Model\\');
$config['mockerOptions'] = [
// 'dataMocker' => $mocker,

// 'getMockStatusCodeCallback' => function (ServerRequestInterface $request, $responses) {
// // check if client clearly asks for mocked response
// $pingHeader = 'X-OpenAPIServer-Mock';
// $pingHeaderCode = 'X-OpenAPIServer-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-OpenAPIServer-Mock', 'pong');
// },
];
if (is_array($prodConfig = @include(__DIR__ . '/config/dev/config.inc.php'))) {
$config = $prodConfig;
} elseif (is_array($devConfig = @include(__DIR__ . '/config/prod/config.inc.php'))) {
$config = $devConfig;
} else {
throw new InvalidArgumentException('Config file missed or broken.');
}

$router = new SlimRouter($config);
$app = $router->getSlimApp();
Expand All @@ -118,6 +57,10 @@
* 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();

0 comments on commit 806896a

Please sign in to comment.