* expressive version uplift

* loslog added
This commit is contained in:
Danyi Dávid 2018-07-09 01:01:22 +02:00
parent efad8765c8
commit 12c98c0519
18 changed files with 885 additions and 597 deletions

View File

@ -11,18 +11,18 @@
"prefer-stable": true,
"require": {
"php": "^7.1",
"dasprid/container-interop-doctrine": "^1.0",
"dasprid/container-interop-doctrine": "^1.1",
"guzzlehttp/guzzle": "^6.3",
"http-interop/http-middleware": "^0.4.1",
"los/loslog": "^3.1",
"roave/security-advisories": "dev-master",
"zendframework/zend-component-installer": "^1.0",
"zendframework/zend-component-installer": "^2.1.1",
"zendframework/zend-config-aggregator": "^1.0",
"zendframework/zend-eventmanager": "^3.2",
"zendframework/zend-expressive": "^2.0.2",
"zendframework/zend-expressive-fastroute": "^2.0",
"zendframework/zend-expressive-helpers": "^4.0",
"zendframework/zend-http": "^2.6",
"zendframework/zend-json": "^3.0",
"zendframework/zend-expressive": "^3.0.1",
"zendframework/zend-expressive-fastroute": "^3.0",
"zendframework/zend-expressive-helpers": "^5.0",
"zendframework/zend-http": "^2.7",
"zendframework/zend-json": "^3.1",
"zendframework/zend-servicemanager": "^3.3",
"zendframework/zend-stdlib": "^3.1"
},

1107
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,28 @@
<?php
use Zend\Stratigility\Middleware\ErrorHandler;
return [
'dependencies' => [
'factories' => [
LosMiddleware\LosLog\LosLog::class => LosMiddleware\LosLog\LosLogFactory::class,
LosMiddleware\LosLog\HttpLog::class => LosMiddleware\LosLog\HttpLogFactory::class,
Psr\Log\LoggerInterface::class => LosMiddleware\LosLog\LoggerFactory::class,
],
'delegators' => [
ErrorHandler::class => [
LosMiddleware\LosLog\ErrorHandlerListenerDelegatorFactory::class,
],
],
],
'loslog' => [
'log_dir' => 'data/logs',
'error_logger_file' => 'error.log',
'exception_logger_file' => 'exception.log',
'static_logger_file' => 'static.log',
'http_logger_file' => 'http.log',
'log_request' => false,
'log_response' => false,
'full' => false,
],
];

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
use Zend\ConfigAggregator\ArrayProvider;
use Zend\ConfigAggregator\ConfigAggregator;
use Zend\ConfigAggregator\PhpFileProvider;
@ -11,10 +13,16 @@ $cacheConfig = [
];
$aggregator = new ConfigAggregator([
\Zend\Log\ConfigProvider::class,
\Zend\HttpHandlerRunner\ConfigProvider::class,
\Zend\Validator\ConfigProvider::class,
// Include cache configuration
new ArrayProvider($cacheConfig),
\Zend\Expressive\Helper\ConfigProvider::class,
\Zend\Expressive\ConfigProvider::class,
\Zend\Expressive\Router\ConfigProvider::class,
// Default App module config
App\ConfigProvider::class,

View File

@ -1,16 +1,14 @@
<?php
use Zend\ServiceManager\Config;
declare(strict_types=1);
use Zend\ServiceManager\ServiceManager;
// Load configuration
$config = require __DIR__ . '/config.php';
$dependencies = $config['dependencies'];
$dependencies['services']['config'] = $config;
// Build container
$container = new ServiceManager();
(new Config($config['dependencies']))->configureServiceManager($container);
// Inject config
$container->setService('config', $config);
return $container;
return new ServiceManager($dependencies);

View File

@ -1,5 +1,4 @@
<?php
/**
* File required to allow enablement of development mode.
*
@ -21,6 +20,8 @@
* - Configuration caching is _disabled_.
*/
declare(strict_types=1);
use Zend\ConfigAggregator\ConfigAggregator;
return [

View File

@ -1,58 +1,78 @@
<?php
declare(strict_types=1);
use Psr\Container\ContainerInterface;
use Zend\Expressive\Application;
use Zend\Expressive\Handler\NotFoundHandler;
use Zend\Expressive\Helper\ServerUrlMiddleware;
use Zend\Expressive\Helper\UrlHelperMiddleware;
use Zend\Expressive\Middleware\ImplicitHeadMiddleware;
use Zend\Expressive\Middleware\ImplicitOptionsMiddleware;
use Zend\Expressive\Middleware\NotFoundHandler;
use Zend\Expressive\MiddlewareFactory;
use Zend\Expressive\Router\Middleware\DispatchMiddleware;
use Zend\Expressive\Router\Middleware\ImplicitHeadMiddleware;
use Zend\Expressive\Router\Middleware\ImplicitOptionsMiddleware;
use Zend\Expressive\Router\Middleware\MethodNotAllowedMiddleware;
use Zend\Expressive\Router\Middleware\RouteMiddleware;
use Zend\Stratigility\Middleware\ErrorHandler;
/**
* Setup middleware pipeline:
*/
return function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void {
// The error handler should be the first (most outer) middleware to catch
// all Exceptions.
$app->pipe(ErrorHandler::class);
$app->pipe(App\Middleware\PreFlightMiddleware::class);
$app->pipe(App\Middleware\EventSubscriberMiddleware::class);
$app->pipe(ServerUrlMiddleware::class);
// The error handler should be the first (most outer) middleware to catch
// all Exceptions.
$app->pipe(ErrorHandler::class);
$app->pipe(App\Middleware\PreFlightMiddleware::class);
$app->pipe(App\Middleware\EventSubscriberMiddleware::class);
//$app->pipe(LosMiddleware\BasePath\BasePath::class);
$app->pipe(ServerUrlMiddleware::class);
// Pipe more middleware here that you want to execute on every request:
// - bootstrapping
// - pre-conditions
// - modifications to outgoing responses
//
// Piped Middleware may be either callables or service names. Middleware may
// also be passed as an array; each item in the array must resolve to
// middleware eventually (i.e., callable or service name).
//
// Middleware can be attached to specific paths, allowing you to mix and match
// applications under a common domain. The handlers in each middleware
// attached this way will see a URI with the matched path segment removed.
//
// i.e., path of "/api/member/profile" only passes "/member/profile" to $apiMiddleware
// - $app->pipe('/api', $apiMiddleware);
// - $app->pipe('/docs', $apiDocMiddleware);
// - $app->pipe('/files', $filesMiddleware);
// Pipe more middleware here that you want to execute on every request:
// - bootstrapping
// - pre-conditions
// - modifications to outgoing responses
//
// Piped Middleware may be either callables or service names. Middleware may
// also be passed as an array; each item in the array must resolve to
// middleware eventually (i.e., callable or service name).
//
// Middleware can be attached to specific paths, allowing you to mix and match
// applications under a common domain. The handlers in each middleware
// attached this way will see a URI with the MATCHED PATH SEGMENT REMOVED!!!
//
// - $app->pipe('/api', $apiMiddleware);
// - $app->pipe('/docs', $apiDocMiddleware);
// - $app->pipe('/files', $filesMiddleware);
// Register the routing middleware in the middleware pipeline.
// This middleware registers the Zend\Expressive\Router\RouteResult request attribute.
$app->pipe(RouteMiddleware::class);
// Register the routing middleware in the middleware pipeline
$app->pipeRoutingMiddleware();
$app->pipe(ImplicitHeadMiddleware::class);
$app->pipe(ImplicitOptionsMiddleware::class);
$app->pipe(UrlHelperMiddleware::class);
// The following handle routing failures for common conditions:
// - HEAD request but no routes answer that method
// - OPTIONS request but no routes answer that method
// - method not allowed
// Order here matters; the MethodNotAllowedMiddleware should be placed
// after the Implicit*Middleware.
$app->pipe(ImplicitHeadMiddleware::class);
$app->pipe(ImplicitOptionsMiddleware::class);
$app->pipe(MethodNotAllowedMiddleware::class);
// Add more middleware here that needs to introspect the routing results; this
// might include:
//
// - route-based authentication
// - route-based validation
// - etc.
// Seed the UrlHelper with the routing results:
$app->pipe(UrlHelperMiddleware::class);
// Register the dispatch middleware in the middleware pipeline
$app->pipeDispatchMiddleware();
// Add more middleware here that needs to introspect the routing results; this
// might include:
//
// - route-based authentication
// - route-based validation
// - etc.
// At this point, if no Response is return by any middleware, the
// NotFoundHandler kicks in; alternately, you can provide other fallback
// middleware to execute.
$app->pipe(NotFoundHandler::class);
// Register the dispatch middleware in the middleware pipeline
$app->pipe(DispatchMiddleware::class);
// At this point, if no Response is returned by any middleware, the
// NotFoundHandler kicks in; alternately, you can provide other fallback
// middleware to execute.
$app->pipe(NotFoundHandler::class);
};

View File

@ -1,31 +1,39 @@
<?php
declare(strict_types=1);
use Psr\Container\ContainerInterface;
use Zend\Expressive\Application;
use Zend\Expressive\MiddlewareFactory;
/**
* Setup routes with a single request method:
*
* $app->get('/', App\Action\HomePageAction::class, 'home');
* $app->post('/album', App\Action\AlbumCreateAction::class, 'album.create');
* $app->put('/album/:id', App\Action\AlbumUpdateAction::class, 'album.put');
* $app->patch('/album/:id', App\Action\AlbumUpdateAction::class, 'album.patch');
* $app->delete('/album/:id', App\Action\AlbumDeleteAction::class, 'album.delete');
* $app->get('/', App\Handler\HomePageHandler::class, 'home');
* $app->post('/album', App\Handler\AlbumCreateHandler::class, 'album.create');
* $app->put('/album/:id', App\Handler\AlbumUpdateHandler::class, 'album.put');
* $app->patch('/album/:id', App\Handler\AlbumUpdateHandler::class, 'album.patch');
* $app->delete('/album/:id', App\Handler\AlbumDeleteHandler::class, 'album.delete');
*
* Or with multiple request methods:
*
* $app->route('/contact', App\Action\ContactAction::class, ['GET', 'POST', ...], 'contact');
* $app->route('/contact', App\Handler\ContactHandler::class, ['GET', 'POST', ...], 'contact');
*
* Or handling all request methods:
*
* $app->route('/contact', App\Action\ContactAction::class)->setName('contact');
* $app->route('/contact', App\Handler\ContactHandler::class)->setName('contact');
*
* or:
*
* $app->route(
* '/contact',
* App\Action\ContactAction::class,
* App\Handler\ContactHandler::class,
* Zend\Expressive\Router\Route::HTTP_METHOD_ANY,
* 'contact'
* );
*/
$app->get('/', App\Action\HomePageAction::class, 'home');
$app->get('/list', App\Action\PingAction::class, 'api.list');
$app->post('/store/{direction:sent|received}/{hashKey}', App\Action\StoreAction::class, 'api.store');
return function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void {
$app->get('/', App\Action\HomePageAction::class, 'home');
$app->get('/list', App\Action\PingAction::class, 'api.list');
$app->post('/store/{direction:sent|received}/{hashKey}', App\Action\StoreAction::class, 'api.store');
};

1
data/.gitignore vendored
View File

@ -1,2 +1,3 @@
*.db
config-cache.php
logs

View File

@ -8,7 +8,7 @@ set('ssh_multiplexing', true);
set('repository', 'ssh://gogs@gogs.ragnarok.yvan.hu:2206/yvan/sms-store.git');
set('shared_dirs', [
// 'data/tmp',
'data/logs',
]);
set('shared_files', [
'config/autoload/local.php',

View File

@ -1,9 +1,9 @@
<?php
declare(strict_types=1);
// Delegate static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server'
&& is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))
) {
if (PHP_SAPI === 'cli-server' && $_SERVER['SCRIPT_FILENAME'] !== __FILE__) {
return false;
}
@ -13,17 +13,18 @@ require 'vendor/autoload.php';
/**
* Self-called anonymous function that creates its own scope and keep the global namespace clean.
*/
call_user_func(function () {
/** @var \Interop\Container\ContainerInterface $container */
(function () {
/** @var \Psr\Container\ContainerInterface $container */
$container = require 'config/container.php';
/** @var \Zend\Expressive\Application $app */
$app = $container->get(\Zend\Expressive\Application::class);
$factory = $container->get(\Zend\Expressive\MiddlewareFactory::class);
// Import programmatic/declarative middleware pipeline and routing
// Execute programmatic/declarative middleware pipeline and routing
// configuration statements
require 'config/pipeline.php';
require 'config/routes.php';
(require 'config/pipeline.php')($app, $factory, $container);
(require 'config/routes.php')($app, $factory, $container);
$app->run();
});
})();

View File

@ -2,17 +2,17 @@
namespace App\Action;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface as ServerMiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Json\Json;
abstract class AbstractAction implements ServerMiddlewareInterface
abstract class AbstractAction implements RequestHandlerInterface
{
const IDENTIFIER_NAME = 'id';
public function process(ServerRequestInterface $request, DelegateInterface $delegate)
public function handle(ServerRequestInterface $request): ResponseInterface
{
$requestMethod = strtoupper($request->getMethod());
$id = $request->getAttribute(static::IDENTIFIER_NAME);
@ -20,73 +20,71 @@ abstract class AbstractAction implements ServerMiddlewareInterface
switch ($requestMethod) {
case 'GET':
return isset($id)
? $this->get($request, $delegate)
: $this->getList($request, $delegate);
? $this->get($request)
: $this->getList($request);
case 'POST':
return $this->create($request, $delegate);
return $this->create($request);
case 'PUT':
return $this->update($request, $delegate);
return $this->update($request);
case 'DELETE':
return isset($id)
? $this->delete($request, $delegate)
: $this->deleteList($request, $delegate);
? $this->delete($request)
: $this->deleteList($request);
case 'HEAD':
return $this->head($request, $delegate);
return $this->head($request);
case 'OPTIONS':
return $this->options($request, $delegate);
return $this->options($request);
case 'PATCH':
return $this->patch($request, $delegate);
default:
return $delegate->process($request);
return $this->patch($request);
}
}
public function get(ServerRequestInterface $request, DelegateInterface $delegate)
public function get(ServerRequestInterface $request): ResponseInterface
{
return $this->createResponse(['content' => 'Method not allowed'], 405);
}
public function getList(ServerRequestInterface $request, DelegateInterface $delegate)
public function getList(ServerRequestInterface $request): ResponseInterface
{
return $this->createResponse(['content' => 'Method not allowed'], 405);
}
public function create(ServerRequestInterface $request, DelegateInterface $delegate)
public function create(ServerRequestInterface $request): ResponseInterface
{
return $this->createResponse(['content' => 'Method not allowed'], 405);
}
public function update(ServerRequestInterface $request, DelegateInterface $delegate)
public function update(ServerRequestInterface $request): ResponseInterface
{
return $this->createResponse(['content' => 'Method not allowed'], 405);
}
public function delete(ServerRequestInterface $request, DelegateInterface $delegate)
public function delete(ServerRequestInterface $request): ResponseInterface
{
return $this->createResponse(['content' => 'Method not allowed'], 405);
}
public function deleteList(ServerRequestInterface $request, DelegateInterface $delegate)
public function deleteList(ServerRequestInterface $request): ResponseInterface
{
return $this->createResponse(['content' => 'Method not allowed'], 405);
}
public function head(ServerRequestInterface $request, DelegateInterface $delegate)
public function head(ServerRequestInterface $request): ResponseInterface
{
return $this->createResponse(['content' => 'Method not allowed'], 405);
}
public function options(ServerRequestInterface $request, DelegateInterface $delegate)
public function options(ServerRequestInterface $request): ResponseInterface
{
return $this->createResponse(['content' => 'Method not allowed'], 405);
}
public function patch(ServerRequestInterface $request, DelegateInterface $delegate)
public function patch(ServerRequestInterface $request): ResponseInterface
{
return $this->createResponse(['content' => 'Method not allowed'], 405);
}
final protected function createResponse($data, $status = 200)
final protected function createResponse($data, $status = 200): ResponseInterface
{
return new JsonResponse($data, $status);
}

View File

@ -3,12 +3,12 @@
namespace App\Action;
use App\Service\KoinService;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface as ServerMiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\TextResponse;
class HomePageAction implements ServerMiddlewareInterface
class HomePageAction implements RequestHandlerInterface
{
private $tmp;
@ -17,7 +17,12 @@ class HomePageAction implements ServerMiddlewareInterface
$this->tmp = $tmp;
}
public function process(ServerRequestInterface $request, DelegateInterface $delegate)
/**
* Handle the request and return a response.
* @param ServerRequestInterface $request
* @return ResponseInterface
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
return new TextResponse("Nuff");
}

View File

@ -2,14 +2,14 @@
namespace App\Action;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface as ServerMiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\JsonResponse;
use Psr\Http\Message\ServerRequestInterface;
class PingAction implements ServerMiddlewareInterface
class PingAction implements RequestHandlerInterface
{
public function process(ServerRequestInterface $request, DelegateInterface $delegate)
public function handle(ServerRequestInterface $request): ResponseInterface
{
return new JsonResponse(['ack' => time()]);
}

View File

@ -5,7 +5,7 @@ namespace App\Action;
use App\Entity\Sms;
use App\Response\JsonCorsResponse;
use App\Service\SmsStoreService;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class StoreAction extends AbstractAction
@ -17,7 +17,7 @@ class StoreAction extends AbstractAction
$this->smsStore = $smsStore;
}
public function create(ServerRequestInterface $request, DelegateInterface $delegate)
public function create(ServerRequestInterface $request): ResponseInterface
{
$hashKey = $request->getAttribute('hashKey');
$direction = $request->getAttribute('direction');

View File

@ -2,23 +2,22 @@
namespace App\Middleware;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface as ServerMiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface as ServerMiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class EventSubscriberMiddleware implements ServerMiddlewareInterface
{
/**
* This actually does nothing, just wraps the next middleware in the pipe.
*
* @param ServerRequestInterface $request
* @param DelegateInterface $delegate
*
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, DelegateInterface $delegate)
{
return $delegate->process($request);
}
/**
* This actually does nothing, just wraps the next middleware in the pipe.
*
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
return $handler->handle($request);
}
}

View File

@ -9,19 +9,19 @@ use Zend\EventManager\LazyListener;
class EventSubscriberMiddlewareFactory
{
public function __invoke(ContainerInterface $container)
{
$eventManager = $container->get(EventManager::class);
$eventManager->setIdentifiers([
EventSubscriberMiddleware::class,
]);
public function __invoke(ContainerInterface $container)
{
$eventManager = $container->get(EventManager::class);
$eventManager->setIdentifiers([
EventSubscriberMiddleware::class,
]);
$lazyListener = new LazyListener([
'listener' => KoinService::class,
'method' => 'onReceiveSmsListener',
], $container);
$eventManager->attach('store.sms.persisted', $lazyListener);
$lazyListener = new LazyListener([
'listener' => KoinService::class,
'method' => 'onReceiveSmsListener',
], $container);
$eventManager->attach('store.sms.persisted', $lazyListener);
return new EventSubscriberMiddleware();
}
return new EventSubscriberMiddleware();
}
}

View File

@ -2,10 +2,12 @@
namespace App\Middleware;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface as ServerMiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class PreFlightMiddleware
class PreFlightMiddleware implements ServerMiddlewareInterface
{
const ALLOW_HEADERS = [
'DNT',
@ -19,16 +21,24 @@ class PreFlightMiddleware
'Authorization',
];
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
/**
* Set CORS headers the ugly way.
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
* @todo replace with cors middleware tuupola?
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$requestMethod = strtoupper($request->getMethod());
if ($requestMethod == 'OPTIONS') {
return $response
$response = $request
->withHeader('Accept', 'OPTIONS,GET,POST,PUT,PATCH,DELETE')
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,PATCH,DELETE')
->withHeader('Access-Control-Allow-Headers', implode(",", self::ALLOW_HEADERS));
return $handler->handle($response);
}
return $next($request, $response);
return $handler->handle($request);
}
}