Skip to content

Commit

Permalink
Merge eebb428 into d9a9b3a
Browse files Browse the repository at this point in the history
  • Loading branch information
byjg committed Oct 19, 2022
2 parents d9a9b3a + eebb428 commit 883bf5d
Show file tree
Hide file tree
Showing 32 changed files with 1,330 additions and 1,325 deletions.
39 changes: 39 additions & 0 deletions .github/workflows/phpunit.yml
@@ -0,0 +1,39 @@
name: PHPUnit
on:
push:
branches:
- master
tags:
- "*.*.*"
pull_request:
branches:
- master
schedule:
- cron: "0 8 * * 1"

jobs:
Build:
runs-on: 'ubuntu-latest'
container: 'byjg/php:${{ matrix.php-version }}-cli'
strategy:
matrix:
php-version:
- "8.1"
- "8.0"
- "7.4"
- "7.3"

steps:
- uses: actions/checkout@v3
- run: composer install
- run: ./vendor/bin/phpunit

Documentation:
runs-on: 'ubuntu-latest'
needs: Build
if: github.ref == 'refs/heads/master'
env:
DOC_GITHUB_TOKEN: '${{ secrets.DOC_TOKEN }}'
steps:
- uses: actions/checkout@v3
- run: curl https://opensource.byjg.com/add-doc.sh | bash /dev/stdin php restserver
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -4,3 +4,4 @@ composer.lock
vendor

.idea
.phpunit.result.cache
14 changes: 0 additions & 14 deletions .travis.yml

This file was deleted.

38 changes: 38 additions & 0 deletions .vscode/launch.json
@@ -0,0 +1,38 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Debug current Script in Console",
"type": "php",
"request": "launch",
"program": "${file}",
"cwd": "${fileDirname}",
"port": 0,
"runtimeArgs": [
"-dxdebug.start_with_request=yes"
],
"env": {
"XDEBUG_MODE": "debug,develop",
"XDEBUG_CONFIG": "client_port=${port}"
}
},
{
"name": "PHPUnit Debug",
"type": "php",
"request": "launch",
"program": "${workspaceFolder}/vendor/bin/phpunit",
"cwd": "${workspaceFolder}",
"port": 0,
"runtimeArgs": [
"-dxdebug.start_with_request=yes"
],
"env": {
"XDEBUG_MODE": "debug,develop",
"XDEBUG_CONFIG": "client_port=${port}"
}
}
]
}
120 changes: 93 additions & 27 deletions README.md
@@ -1,18 +1,22 @@
# PHP Rest Server
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/byjg/restserver/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/byjg/restserver/?branch=master)
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/40968662-27b2-4a31-9872-a29bdd68da2b/mini.png)](https://insight.sensiolabs.com/projects/40968662-27b2-4a31-9872-a29bdd68da2b)
[![Build Status](https://travis-ci.com/byjg/restserver.svg?branch=master)](https://travis-ci.com/byjg/restserver)

[![Build Status](https://github.com/byjg/restserver/actions/workflows/phpunit.yml/badge.svg?branch=master)](https://github.com/byjg/restserver/actions/workflows/phpunit.yml)
[![Opensource ByJG](https://img.shields.io/badge/opensource-byjg-success.svg)](http://opensource.byjg.com)
[![GitHub source](https://img.shields.io/badge/Github-source-informational?logo=github)](https://github.com/byjg/restserver/)
[![GitHub license](https://img.shields.io/github/license/byjg/restserver.svg)](https://opensource.byjg.com/opensource/licensing.html)
[![GitHub release](https://img.shields.io/github/release/byjg/restserver.svg)](https://github.com/byjg/restserver/releases/)


Create RESTFull services with different and customizable output handlers (JSON, XML, Html, etc.).
Auto-Generate routes from swagger.json definition.

# Installation
## Installation

```bash
composer require "byjg/restserver=4.0.*"
```
# Understanding the RestServer library

## Understanding the RestServer library

Basically the RestServer library enables you to create a full feature RESTFul
application on top of the well-known [FastRoute](https://github.com/nikic/FastRoute) library.
Expand All @@ -23,15 +27,15 @@ You can get this working in a few minutes. Just follow this steps:
- Using Clousures (Easiest)
- Using Classes
- Using the OpenApi 2 (former Swagger) and OpenApi 3 documentation (the most reliable and for long-term and maintable applications)

2. Process the Request and output the Response

Each "Path" or "Route" can have your own handle for output the response.
The are several handlers implemented and you can implement your own.

# 1. Creating the Routes
## 1. Creating the Routes

## Using Closures
### Using Closures

```php
<?php
Expand All @@ -52,7 +56,7 @@ $restServer = new \ByJG\RestServer\HttpRequestHandler();
$restServer->handle($routeDefinition);
```

## Using Classes
### Using Classes

```php
<?php
Expand Down Expand Up @@ -94,7 +98,7 @@ class ClassName
}
```

## Auto-Generate from an OpenApi definition
### Auto-Generate from an OpenApi definition

[OpenApi](https://www.openapis.org/) is the world's largest framework of API developer tools for the
OpenAPI Specification(OAS), enabling development across the entire API lifecycle, from design and documentation,
Expand Down Expand Up @@ -148,7 +152,7 @@ $restServer = new \ByJG\RestServer\HttpRequestHandler();
$restServer->handle($routeDefinition);
```

## Caching the Routes
### Caching the Routes

It is possible to cache the route by adding any PSR-16 instance on the second parameter of the constructor:

Expand All @@ -158,7 +162,7 @@ $routeDefinition = new \ByJG\RestServer\Route\OpenApiRouteDefinition(__DIR__ . '
$routeDefinition->withCache(new \ByJG\Cache\Psr16\FileSystemCacheEngine());
```

## Customizing the Handlers
### Customizing the Handlers

As the Swagger process is fully automated, you can define the handler by Mime Type or Route:

Expand All @@ -185,7 +189,7 @@ $routeDefinition->withOutputProcessorForRoute(
);
```

# 2. Processing the Request and Response
## 2. Processing the Request and Response

You need to implement a method, function or clousure with two parameters - Response and Request - in that order.

Expand Down Expand Up @@ -222,7 +226,7 @@ informations to the requester.
- addHeader($header, $value): Add an header entry;
- setResponseCode($value): Set the HTTP response code (eg. 200, 401, etc)

## Output your data
### Output your data

To output your data you *have to* use the `$response->write($object)`.
The write method supports you output a object, stdclass, array or string. The Handler object will
Expand Down Expand Up @@ -279,7 +283,7 @@ The result will be something like:
}
```

# The OutputProcessors
## The OutputProcessors

An OutputProcessor will parse the `$response->write($obj)` and output in the proper format.
The available handlers are:
Expand All @@ -289,7 +293,7 @@ The available handlers are:
- HtmlHandler
- JsonCleanOutputProcessor

## Using Custom Response Handler
### Using Custom Response Handler

The Default Response Handler will process all "$response->write" into a JSON.
You can choose another Handlers. See below for a list of Available Response Handlers.
Expand All @@ -312,13 +316,10 @@ $restServer = new \ByJG\RestServer\HttpRequestHandler();
$restServer->handle($routeDefinition);
```


# Defining a Route

## Defining a Route

You can define route with constant and/or variable. For example:


| Pattern | Description |
|------------------------|---------------------------------|
| /myroute | Matches exactly "/myroute" |
Expand All @@ -340,28 +341,93 @@ all matches values can be obtained by
$this->getRequest()->param('variable');
```

# Running the rest server
## Error Handler

You need to set up your restserver to handle ALL requests to a single PHP file. Normally is "app.php"
This project uses the project `flip/whoops` to handle the errors. The default behavior is return the error with the minimum information necessary.

```php
[
"type" => Exception Type,
"message" => Error Message.
]
```

To disable completely any error handler you can:

```php
<?php

$http = (new HttpErrorHandler())
->withDoNotUseErrorHandler();

try {
$http->handle(.....);
} catch (Exception $ex) {
// You have to handle by yourself the errors
}
```

or you can get the detailed error handler with all information necessary to debug your application:

```php
<?php

$http = (new HttpErrorHandler())
->withDetailedErrorHandler();

$http->handle(.....);
```

The error handler return the data based on the format defined by first accept content type header.

## PHP Built-in server
The currently implementation are:

- HTML
- JSON
- XML

## CORS support

Restserver can handle CORS and send the proper headers to the browser:

```php
<?php
$httpHandler = new \ByJG\RestServer\HttpRequestHandler();
$httpHandler
->withCorsOrigins([/* list of accepted origing */]) // Required to enable CORS
->withAcceptCorsMethods([/* list of methods */]) // Optional. Default all methods. Don't need to pass 'OPTIONS'
->withAcceptCorsHeaders([/* list of headers */]) // Optional. Default all headers
->handle(/* definition */)
```

Note that the method `withCorsOrigins` accept a list of hosts regular expressions. e.g.

- `example\.com` - Accept only example.com
- `example\.(com|org)` - Accept both example.com and example.org
- `example\.com(\.br)?` -Accept both example.com and example.com.br

## Running the rest server

You need to set up your restserver to handle ALL requests to a single PHP file. Normally is "app.php"

### PHP Built-in server

```bash
cd web
php -S localhost:8080 app.php
```

## Nginx
### Nginx

```
```nginx
location / {
try_files $uri $uri/ /app.php$is_args$args;
}
```

## Apache .htaccess
### Apache .htaccess

```
```apache
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
Expand Down

0 comments on commit 883bf5d

Please sign in to comment.