Yuriy Belenko 8e78b14e28 New PHP Slim4 Server Generator (#3658)
* [Slim4] Copy Slim3 generator as starting point

* [Slim4] Add psr7Implementation generator option

Slim supports PSR-7 interfaces for its Request and Response objects.
Slim provides its own PSR-7 implementation so that it works out of the
box.
However, you are free to replace Slim’s default PSR-7 objects with
a third-party implementation.
[Ref] https://www.slimframework.com/docs/v4/concepts/value-objects.html

* [Slim4] Handle psr7Implementation generator option

It somehow ended up with composerPackages and composerDevPackages
codegen variables and two additional functions. Hope, it's not too much.

* [Slim4] Extend from Slim3 generator

* [Slim4] Bump PHP Slim Framework version to 4.0.0

* [Slim4] Bump required PHP version to 7.1

[Upgrade Guide](https://www.slimframework.com/docs/v4/start/upgrade.html)

* [Slim4] Remove app settings

Slim’s App settings used to be a part of the container and  they have
now been decoupled from it.

[Upgrade Guide](https://www.slimframework.com/docs/v4/start/upgrade.html)

* [Slim4] Set container argument optional

Slim uses an optional dependency container to prepare, manage,
and inject application dependencies.
Slim supports containers that implement PSR-11
like [PHP-DI](http://php-di.org/doc/frameworks/slim.html).

[Upgrade Guide](https://www.slimframework.com/docs/v4/start/upgrade.html)

* [Slim4] Change response body write

You can't write to response instance directly anymore,
need to retrieve body object first.

[Doc](https://www.slimframework.com/docs/v4/objects/response.html#the-response-body)

* [Slim4] Change Slim\App constructor

[Upgrade Guide](https://www.slimframework.com/docs/v4/start/upgrade.html)

* [Slim4] Refactor token authentication options

User can provide array or Container as constructor argument from now.
Small refactoring required to retrieve authentication options from
that argument.

* [Slim4] Add PSR-7 implementation codegen flags

This approach seems more flexible to me.
User can customize templates in favor of chosen PSR7 implementation.
It's easier to change Composer packages and their versions.

* [Slim4] Add JsonBodyParserMiddleware

Slim4 doesn't parse JSON body, need to add suggested middleware.
Ref: https://www.slimframework.com/docs/v4/objects/request.html#the-request-body

* [Slim4] Remove request's deprecated methods usage

Since Slim 4.0.0 ServerRequest implementation doesn't have
getQueryParam and getParsedBodyParam methods anymore.

* [Slim4] Use getUploadedFiles for multipart request

isMultipart codegen property is always false so far.
Hope that bug will be fixed soon.

* [Slim4] Add samples
2019-10-21 22:20:12 +08:00

11 KiB

php-base - PHP Slim 4 Server library for OpenAPI Petstore

This server has been generated with Slim PSR-7 implementation.

Requirements

  • Web server with URL rewriting
  • PHP 7.1 or newer

This package contains .htaccess for Apache configuration. If you use another server(Nginx, HHVM, IIS, lighttpd) check out Web Servers doc.

Installation via Composer

Navigate into your project's root directory and execute the bash command shown below. This command downloads the Slim Framework and its third-party dependencies into your project's vendor/ directory.

$ composer install

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:

$ php -S localhost:8888 -t php-slim-server

Warning

This web server was designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network.

Tests

PHPUnit

This package uses PHPUnit 6 or 7(depends from your PHP version) for unit testing. Test folder contains templates which you can fill with real test assertions. How to write tests read at PHPUnit Manual - Chapter 2. Writing Tests for PHPUnit.

Run

Command Target
$ composer test All tests
$ composer test-apis Apis tests
$ composer test-models Models tests

Config

Package contains fully functional config ./phpunit.xml.dist file. Create ./phpunit.xml in root folder to override it.

Quote from 3. The Command-Line Test Runner — PHPUnit 7.4 Manual:

If phpunit.xml or phpunit.xml.dist (in that order) exist in the current working directory and --configuration is not used, the configuration will be automatically read from that file.

PHP CodeSniffer

PHP CodeSniffer Documentation. This tool helps to follow coding style and avoid common PHP coding mistakes.

Run

$ composer phpcs

Config

Package contains fully functional config ./phpcs.xml.dist file. It checks source code against PSR-1 and PSR-2 coding standards. Create ./phpcs.xml in root folder to override it. More info at Using a Default Configuration File

PHPLint

PHPLint Documentation. Checks PHP syntax only.

Run

$ composer phplint

Show errors

Switch on option in ./index.php:

/**
 * 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);

API Endpoints

All URIs are relative to http://petstore.swagger.io:80/v2

Important! Do not modify abstract API controllers directly! Instead extend them by implementation classes like:

// src/Api/PetApi.php

namespace OpenAPIServer\Api;

use OpenAPIServer\Api\AbstractPetApi;

class PetApi extends AbstractPetApi
{

    public function addPet($request, $response, $args)
    {
        // your implementation of addPet method here
    }
}

Place all your implementation classes in ./src folder accordingly. For instance, when abstract class located at ./lib/Api/AbstractPetApi.php you need to create implementation class at ./src/Api/PetApi.php.

Class Method HTTP request Description
AbstractAnotherFakeApi call123TestSpecialTags PATCH /another-fake/dummy To test special tags
AbstractFakeApi createXmlItem POST /fake/create_xml_item creates an XmlItem
AbstractFakeApi fakeOuterBooleanSerialize POST /fake/outer/boolean
AbstractFakeApi fakeOuterCompositeSerialize POST /fake/outer/composite
AbstractFakeApi fakeOuterNumberSerialize POST /fake/outer/number
AbstractFakeApi fakeOuterStringSerialize POST /fake/outer/string
AbstractFakeApi testBodyWithFileSchema PUT /fake/body-with-file-schema
AbstractFakeApi testBodyWithQueryParams PUT /fake/body-with-query-params
AbstractFakeApi testClientModel PATCH /fake To test "client" model
AbstractFakeApi testEndpointParameters POST /fake Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
AbstractFakeApi testEnumParameters GET /fake To test enum parameters
AbstractFakeApi testGroupParameters DELETE /fake Fake endpoint to test group parameters (optional)
AbstractFakeApi testInlineAdditionalProperties POST /fake/inline-additionalProperties test inline additionalProperties
AbstractFakeApi testJsonFormData GET /fake/jsonFormData test json serialization of form data
AbstractFakeApi testQueryParameterCollectionFormat PUT /fake/test-query-paramters
AbstractFakeClassnameTags123Api testClassname PATCH /fake_classname_test To test class name in snake case
AbstractPetApi addPet POST /pet Add a new pet to the store
AbstractPetApi findPetsByStatus GET /pet/findByStatus Finds Pets by status
AbstractPetApi findPetsByTags GET /pet/findByTags Finds Pets by tags
AbstractPetApi updatePet PUT /pet Update an existing pet
AbstractPetApi deletePet DELETE /pet/{petId} Deletes a pet
AbstractPetApi getPetById GET /pet/{petId} Find pet by ID
AbstractPetApi updatePetWithForm POST /pet/{petId} Updates a pet in the store with form data
AbstractPetApi uploadFile POST /pet/{petId}/uploadImage uploads an image
AbstractPetApi uploadFileWithRequiredFile POST /fake/{petId}/uploadImageWithRequiredFile uploads an image (required)
AbstractStoreApi getInventory GET /store/inventory Returns pet inventories by status
AbstractStoreApi placeOrder POST /store/order Place an order for a pet
AbstractStoreApi deleteOrder DELETE /store/order/{order_id} Delete purchase order by ID
AbstractStoreApi getOrderById GET /store/order/{order_id} Find purchase order by ID
AbstractUserApi createUser POST /user Create user
AbstractUserApi createUsersWithArrayInput POST /user/createWithArray Creates list of users with given input array
AbstractUserApi createUsersWithListInput POST /user/createWithList Creates list of users with given input array
AbstractUserApi loginUser GET /user/login Logs user into the system
AbstractUserApi logoutUser GET /user/logout Logs out current logged in user session
AbstractUserApi deleteUser DELETE /user/{username} Delete user
AbstractUserApi getUserByName GET /user/{username} Get user by user name
AbstractUserApi updateUser PUT /user/{username} Updated user

Models

  • OpenAPIServer\Model\AdditionalPropertiesAnyType
  • OpenAPIServer\Model\AdditionalPropertiesArray
  • OpenAPIServer\Model\AdditionalPropertiesBoolean
  • OpenAPIServer\Model\AdditionalPropertiesClass
  • OpenAPIServer\Model\AdditionalPropertiesInteger
  • OpenAPIServer\Model\AdditionalPropertiesNumber
  • OpenAPIServer\Model\AdditionalPropertiesObject
  • OpenAPIServer\Model\AdditionalPropertiesString
  • OpenAPIServer\Model\Animal
  • OpenAPIServer\Model\ApiResponse
  • OpenAPIServer\Model\ArrayOfArrayOfNumberOnly
  • OpenAPIServer\Model\ArrayOfNumberOnly
  • OpenAPIServer\Model\ArrayTest
  • OpenAPIServer\Model\Capitalization
  • OpenAPIServer\Model\Cat
  • OpenAPIServer\Model\CatAllOf
  • OpenAPIServer\Model\Category
  • OpenAPIServer\Model\ClassModel
  • OpenAPIServer\Model\Client
  • OpenAPIServer\Model\Dog
  • OpenAPIServer\Model\DogAllOf
  • OpenAPIServer\Model\EnumArrays
  • OpenAPIServer\Model\EnumClass
  • OpenAPIServer\Model\EnumTest
  • OpenAPIServer\Model\File
  • OpenAPIServer\Model\FileSchemaTestClass
  • OpenAPIServer\Model\FormatTest
  • OpenAPIServer\Model\HasOnlyReadOnly
  • OpenAPIServer\Model\MapTest
  • OpenAPIServer\Model\MixedPropertiesAndAdditionalPropertiesClass
  • OpenAPIServer\Model\Model200Response
  • OpenAPIServer\Model\ModelList
  • OpenAPIServer\Model\ModelReturn
  • OpenAPIServer\Model\Name
  • OpenAPIServer\Model\NumberOnly
  • OpenAPIServer\Model\Order
  • OpenAPIServer\Model\OuterComposite
  • OpenAPIServer\Model\OuterEnum
  • OpenAPIServer\Model\Pet
  • OpenAPIServer\Model\ReadOnlyFirst
  • OpenAPIServer\Model\SpecialModelName
  • OpenAPIServer\Model\Tag
  • OpenAPIServer\Model\TypeHolderDefault
  • OpenAPIServer\Model\TypeHolderExample
  • OpenAPIServer\Model\User
  • OpenAPIServer\Model\XmlItem

Authentication

Security schema api_key

Important! To make ApiKey authentication work you need to extend \OpenAPIServer\Auth\AbstractAuthenticator class by \OpenAPIServer\Auth\ApiKeyAuthenticator class.

Security schema api_key_query

Important! To make ApiKey authentication work you need to extend \OpenAPIServer\Auth\AbstractAuthenticator class by \OpenAPIServer\Auth\ApiKeyAuthenticator class.

Security schema http_basic_test

Important! To make Basic authentication work you need to extend \OpenAPIServer\Auth\AbstractAuthenticator class by \OpenAPIServer\Auth\BasicAuthenticator class.

Security schema petstore_auth

Important! To make OAuth authentication work you need to extend \OpenAPIServer\Auth\AbstractAuthenticator class by \OpenAPIServer\Auth\OAuthAuthenticator class.

Scope list:

  • write:pets - modify pets in your account
  • read:pets - read your pets

Advanced middleware configuration

Ref to used Slim Token Middleware dyorg/slim-token-authentication