From 64ca52e8aabb103a40f2d8ef3151bd61f43da782 Mon Sep 17 00:00:00 2001 From: ytake Date: Mon, 22 Jan 2018 02:39:12 +0900 Subject: [PATCH] for cs --- LICENSE | 29 ++++--- README.md | 5 +- composer.json | 2 +- src/Exceptions/NotFoundHttpException.php | 3 +- src/Foundation/Application.php | 75 +++++++++---------- .../Bootstrap/BootstrapRegister.php | 17 ++--- src/Foundation/Dependency/Dependency.php | 21 +++--- .../Dependency/DependencyInterface.php | 2 +- src/Foundation/Exception/ExceptionHandler.php | 34 +++++---- .../Exception/ExceptionRegister.php | 4 +- .../Exception/ExceptionServiceModule.php | 14 ++-- src/Foundation/Middleware/Dispatcher.php | 19 ++--- src/Foundation/Service.php | 4 +- .../Validation/ValidationException.php | 6 +- src/Foundation/Validation/Validator.php | 20 ++--- .../Validation/ValidatorFactory.php | 4 +- src/Log/LogServiceModule.php | 7 +- src/Middleware/LogExceptionMiddleware.php | 15 ++-- src/Middleware/SimpleCorsMiddleware.php | 40 ++++++---- src/Response/Emitter.php | 4 +- src/Routing/RouteServiceModule.php | 15 ++-- src/Routing/Router.php | 13 ++-- src/http_enum.php | 6 +- 23 files changed, 188 insertions(+), 171 deletions(-) diff --git a/LICENSE b/LICENSE index 4de261e..2469d07 100644 --- a/LICENSE +++ b/LICENSE @@ -1,16 +1,21 @@ -Copyright 2018 Yuuki Takezawa +The MIT License (MIT) -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: +Copyright (c) 2017-2018 Yuuki Takezawa -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md index fadbdad..402f8e2 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,13 @@ -# Nazg Micro Fremawork Core Repository +# Nazg Micro Framework Core Repository [![Build Status](https://travis-ci.org/nazg-hack/framework.svg?branch=master)](https://travis-ci.org/nazg-hack/framework) Http Application / Microframework for HHVM/Hack -## Usage +## Usage [Skeleton](https://github.com/ytake/nazg-skeleton) ```bash $ hhvm -d xdebug.enable=0 -d hhvm.jit=0 -d hhvm.php7.all=1 -d hhvm.hack.lang.auto_typecheck=0 $(which composer) update ``` - diff --git a/composer.json b/composer.json index b0a8cc0..9d65bf4 100644 --- a/composer.json +++ b/composer.json @@ -9,7 +9,7 @@ "psr-11", "psr-15" ], - "license": "BSD-3-Clause", + "license": "MIT", "authors": [ { "name": "Yuuki Takezawa", diff --git a/src/Exceptions/NotFoundHttpException.php b/src/Exceptions/NotFoundHttpException.php index cf05e47..5e92c1e 100644 --- a/src/Exceptions/NotFoundHttpException.php +++ b/src/Exceptions/NotFoundHttpException.php @@ -17,4 +17,5 @@ */ namespace Nazg\Exceptions; -final class NotFoundHttpException extends \Facebook\HackRouter\NotFoundException {} +final class NotFoundHttpException + extends \Facebook\HackRouter\NotFoundException {} diff --git a/src/Foundation/Application.php b/src/Foundation/Application.php index 432da57..914c85a 100644 --- a/src/Foundation/Application.php +++ b/src/Foundation/Application.php @@ -19,7 +19,7 @@ use Facebook\HackRouter\BaseRouter; use Nazg\Http\HttpMethod; -use Nazg\Heredity\{ MiddlewareStack, PsrContainerResolver }; +use Nazg\Heredity\{MiddlewareStack, PsrContainerResolver}; use Nazg\Response\Emitter; use Nazg\RequestHandler\FallbackHandler; use Nazg\Foundation\Middleware\Dispatcher; @@ -32,63 +32,61 @@ use Psr\Container\ContainerInterface; class Application { - - protected ImmVector<\Nazg\Types\TMiddlewareClass> $im = ImmVector{}; + + protected ImmVector<\Nazg\Types\TMiddlewareClass> $im = ImmVector {}; protected ?RequestHandlerInterface $requestHandler; protected ?BootstrapRegister $bootstrapRegister; - public function __construct( - protected DependencyInterface $dependency - ) {} + public function __construct(protected DependencyInterface $dependency) {} - public function run( - ServerRequestInterface $serverRequest - ): void { + public function run(ServerRequestInterface $serverRequest): void { $container = $this->getContainer(); - // register bootstrap for framework application + // register bootstrap for framework application $this->bootstrap($container); $router = $container->get(BaseRouter::class); invariant( - $router instanceof BaseRouter, - "%s class must extend %s", - get_class($router), - BaseRouter::class + $router instanceof BaseRouter, + "%s class must extend %s", + get_class($router), + BaseRouter::class, ); - list($middleware, $attributes) = $router->routePsr7Request($serverRequest); + list($middleware, $attributes) = + $router->routePsr7Request($serverRequest); if ($attributes->count()) { - foreach($attributes as $key => $attribute) { + foreach ($attributes as $key => $attribute) { $serverRequest = $serverRequest->withAttribute($key, $attribute); } } $heredity = $this->middlewareProcessor($middleware, $container); $this->send( $heredity->handle( - $this->marshalAttributes($serverRequest, $attributes) - ) + $this->marshalAttributes($serverRequest, $attributes), + ), ); } protected function marshalAttributes( - ServerRequestInterface $request, - ImmMap $attributes + ServerRequestInterface $request, + ImmMap $attributes, ): ServerRequestInterface { if ($attributes->count()) { - foreach($attributes as $key => $attribute) { + foreach ($attributes as $key => $attribute) { $request = $request->withAttribute($key, $attribute); } } return $request; } - + private function bootstrap(ContainerInterface $container): void { - $bootstrap = $this->bootstrapRegister ?: new BootstrapRegister($container); + $bootstrap = + $this->bootstrapRegister ?: new BootstrapRegister($container); $bootstrap->register(); } public function setBootstrap(BootstrapRegister $br): void { - $this->bootstrapRegister = $br; + $this->bootstrapRegister = $br; } public function setRequestHandler(RequestHandlerInterface $handler): void { @@ -106,26 +104,26 @@ public function setApplicationConfig(array $config): void { public function getContainer(): ContainerInterface { return $this->dependency->getContainer(); } - + /** * Middleware always executed by the application * must override application class * * - * <<__Override>> + * <<__Override>> * protected function middleware(): ImmVector<\Nazg\Types\TMiddlewareClass> { * return ImmVector{}; * } * */ protected function middleware(): ImmVector<\Nazg\Types\TMiddlewareClass> { - return ImmVector{}; + return ImmVector {}; } private function registerDependencies(mixed $config): void { - if(is_array($config)) { - if(array_key_exists(Service::MODULES, $config)) { - if($this->dependency instanceof \Nazg\Foundation\Dependency\Dependency) { + if (is_array($config)) { + if (array_key_exists(Service::MODULES, $config)) { + if ($this->dependency instanceof \Nazg\Foundation\Dependency\Dependency) { $vModule = $config[Service::MODULES]; if ($vModule instanceof ImmVector) { $this->dependency->appendModules($vModule->toVector()); @@ -136,8 +134,8 @@ private function registerDependencies(mixed $config): void { } private function registerMiddlewares(mixed $config): void { - if(is_array($config)) { - if(array_key_exists(Service::MIDDLEWARES, $config)) { + if (is_array($config)) { + if (array_key_exists(Service::MIDDLEWARES, $config)) { if ($config[Service::MIDDLEWARES] instanceof ImmVector) { $this->im = $config[Service::MIDDLEWARES]; } @@ -147,21 +145,22 @@ private function registerMiddlewares(mixed $config): void { protected function middlewareProcessor( ImmVector<\Nazg\Types\TMiddlewareClass> $middleware, - ContainerInterface $container + ContainerInterface $container, ): RequestHandlerInterface { - $appMiddleware = $this->im->concat($this->middleware()) - |>$$->concat($middleware)->toArray(); + $appMiddleware = + $this->im->concat($this->middleware()) + |> $$->concat($middleware)->toArray(); $dispatcher = new Dispatcher( new MiddlewareStack( $appMiddleware, - new PsrContainerResolver($container) + new PsrContainerResolver($container), ), - $this->requestHandler ?: new FallbackHandler() + $this->requestHandler ?: new FallbackHandler(), ); $dispatcher->setContainer($container); return $dispatcher; } - + protected function send(ResponseInterface $response): void { (new Emitter())->emit($response); } diff --git a/src/Foundation/Bootstrap/BootstrapRegister.php b/src/Foundation/Bootstrap/BootstrapRegister.php index 059ba0f..2216995 100644 --- a/src/Foundation/Bootstrap/BootstrapRegister.php +++ b/src/Foundation/Bootstrap/BootstrapRegister.php @@ -22,18 +22,15 @@ type Bootstrap = classname; class BootstrapRegister implements BootstrapRegisterInterface { - - protected ImmVector $ibr = ImmVector{ - \Nazg\Foundation\Exception\ExceptionRegister::class, - }; - - public function __construct( - protected ContainerInterface $container - ) {} + + protected ImmVector + $ibr = ImmVector {\Nazg\Foundation\Exception\ExceptionRegister::class}; + + public function __construct(protected ContainerInterface $container) {} public function register(): void { - foreach($this->ibr->getIterator() as $i) { - if($this->container->has($i)) { + foreach ($this->ibr->getIterator() as $i) { + if ($this->container->has($i)) { $instance = $this->container->get($i); if ($instance instanceof BootstrapRegisterInterface) { $instance->register(); diff --git a/src/Foundation/Dependency/Dependency.php b/src/Foundation/Dependency/Dependency.php index 1305a71..5973ddd 100644 --- a/src/Foundation/Dependency/Dependency.php +++ b/src/Foundation/Dependency/Dependency.php @@ -9,12 +9,11 @@ use Nazg\Routing\RouteServiceModule; class Dependency implements DependencyInterface { - + protected FactoryContainer $container; - - protected Vector<\Nazg\Types\TServiceModule> $modules = Vector{ - RouteServiceModule::class, - }; + + protected Vector<\Nazg\Types\TServiceModule> + $modules = Vector {RouteServiceModule::class}; public function __construct() { $this->container = new \Ytake\HHContainer\FactoryContainer(); @@ -22,24 +21,26 @@ public function __construct() { public function registerConfig(array $config): void { $this->container->set( - Service::CONFIG, + Service::CONFIG, $container ==> $config, - \Ytake\HHContainer\Scope::SINGLETON + \Ytake\HHContainer\Scope::SINGLETON, ); } protected function registerServiceModule(): void { - foreach($this->modules->getIterator() as $i) { + foreach ($this->modules->getIterator() as $i) { $this->container->register($i); } $this->container->lockModule(); } - + public function register(): void { $this->registerServiceModule(); } - public function appendModules(Vector<\Nazg\Types\TServiceModule> $modules): void { + public function appendModules( + Vector<\Nazg\Types\TServiceModule> $modules, + ): void { $this->modules->addAll($modules); } diff --git a/src/Foundation/Dependency/DependencyInterface.php b/src/Foundation/Dependency/DependencyInterface.php index dd9e48b..3a5c5e4 100644 --- a/src/Foundation/Dependency/DependencyInterface.php +++ b/src/Foundation/Dependency/DependencyInterface.php @@ -19,7 +19,7 @@ use Psr\Container\ContainerInterface; -interface DependencyInterface { +interface DependencyInterface { public function registerConfig(array $config): void; diff --git a/src/Foundation/Exception/ExceptionHandler.php b/src/Foundation/Exception/ExceptionHandler.php index 34ce9dd..f6e823f 100644 --- a/src/Foundation/Exception/ExceptionHandler.php +++ b/src/Foundation/Exception/ExceptionHandler.php @@ -1,4 +1,4 @@ -; class ExceptionHandler implements ExceptionHandleInterface { - + public function __construct(protected Emitter $emitter) {} - + /** * @see https://github.com/zendframework/zend-diactoros/blob/master/doc/book/custom-responses.md */ public function render(ExceptionMap $em, \Exception $e): void { $this->emitter->emit( new JsonResponse( - $em->toArray(), - StatusCode::StatusInternalServerError - ) + $em->toArray(), + StatusCode::StatusInternalServerError, + ), ); } @@ -46,15 +46,17 @@ public function handleException(\Exception $e): void { } protected function toImmMap(\Exception $e): ExceptionMap { - return new ImmMap([ - 'message' => $e->getMessage(), - 'exception' => get_class($e), - 'file' => $e->getFile(), - 'line' => $e->getLine(), - 'trace' => map( - $e->getTrace(), - $v ==> (new Map($v))|>$$->removeKey('args')|>$$->toArray() - ), - ]); + return new ImmMap( + [ + 'message' => $e->getMessage(), + 'exception' => get_class($e), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + 'trace' => map( + $e->getTrace(), + $v ==> (new Map($v)) |> $$->removeKey('args') |> $$->toArray(), + ), + ], + ); } } diff --git a/src/Foundation/Exception/ExceptionRegister.php b/src/Foundation/Exception/ExceptionRegister.php index a8a4f15..ca061f7 100644 --- a/src/Foundation/Exception/ExceptionRegister.php +++ b/src/Foundation/Exception/ExceptionRegister.php @@ -22,9 +22,7 @@ class ExceptionRegister implements BootstrapRegisterInterface { - public function __construct( - protected ExceptionHandleInterface $handler - ) {} + public function __construct(protected ExceptionHandleInterface $handler) {} public function register(): void { set_exception_handler([$this->handler, 'handleException']); diff --git a/src/Foundation/Exception/ExceptionServiceModule.php b/src/Foundation/Exception/ExceptionServiceModule.php index 69a0705..26be214 100644 --- a/src/Foundation/Exception/ExceptionServiceModule.php +++ b/src/Foundation/Exception/ExceptionServiceModule.php @@ -24,26 +24,24 @@ class ExceptionServiceModule extends ServiceModule { <<__Override>> - public function provide( - FactoryContainer $container - ): void { + public function provide(FactoryContainer $container): void { $container->set( - ExceptionHandleInterface::class, + ExceptionHandleInterface::class, $container ==> new ExceptionHandler(new Emitter()), ); $container->set( - ExceptionRegister::class, + ExceptionRegister::class, $container ==> new ExceptionRegister( - $this->invariantExceptionHandler($container) + $this->invariantExceptionHandler($container), ), ); } private function invariantExceptionHandler( - FactoryContainer $container + FactoryContainer $container, ): ExceptionHandleInterface { $instance = $container->get(ExceptionHandleInterface::class); - if($instance instanceof ExceptionHandleInterface) { + if ($instance instanceof ExceptionHandleInterface) { return $instance; } throw new \LogicException(); diff --git a/src/Foundation/Middleware/Dispatcher.php b/src/Foundation/Middleware/Dispatcher.php index 1e027fc..927ed02 100644 --- a/src/Foundation/Middleware/Dispatcher.php +++ b/src/Foundation/Middleware/Dispatcher.php @@ -13,34 +13,35 @@ use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; -enum InterceptorMethod: string { +enum InterceptorMethod : string { Process = 'process'; } class Dispatcher extends Heredity { - + protected int $validatorIndex = 0; protected ?ContainerInterface $container; - <<__Override>> + <<__Override>> protected function processor( MiddlewareInterface $middleware, - ServerRequestInterface $request + ServerRequestInterface $request, ): ResponseInterface { $this->validateInterceptor($middleware, $request); return $middleware->process($request, $this); } protected function validateInterceptor( - MiddlewareInterface $middleware, - ServerRequestInterface $request + MiddlewareInterface $middleware, + ServerRequestInterface $request, ): void { $rm = new ReflectionMethod($middleware, InterceptorMethod::Process); $attribute = $rm->getAttribute(Attribute::Named); if (is_array($attribute)) { - if(array_key_exists($this->validatorIndex, $attribute)) { - $validator = $this->container?->get((string)$attribute[$this->validatorIndex]); - if($validator instanceof Validator) { + if (array_key_exists($this->validatorIndex, $attribute)) { + $validator = + $this->container?->get((string) $attribute[$this->validatorIndex]); + if ($validator instanceof Validator) { $factory = new ValidatorFactory($validator, $request); $factory->validator()->validate(); } diff --git a/src/Foundation/Service.php b/src/Foundation/Service.php index adc9711..55d6cf0 100644 --- a/src/Foundation/Service.php +++ b/src/Foundation/Service.php @@ -1,4 +1,4 @@ -validator = $validator; + parent::__construct('The given data was invalid.'); + $this->validator = $validator; } public function errors(): array { - return $this->validator->errors()->toArray(); + return $this->validator->errors()->toArray(); } } diff --git a/src/Foundation/Validation/Validator.php b/src/Foundation/Validation/Validator.php index 9c22e71..f51aa44 100644 --- a/src/Foundation/Validation/Validator.php +++ b/src/Foundation/Validation/Validator.php @@ -20,7 +20,7 @@ use Psr\Http\Message\ServerRequestInterface; use Facebook\TypeAssert; -enum Attribute: string as string { +enum Attribute : string as string { Named = 'RequestValidation'; } @@ -28,15 +28,15 @@ enum Attribute: string as string { abstract class Validator { protected ?ServerRequestInterface $request; - - protected Vector $messages = Vector{}; - protected Vector $validateMethods = Vector{}; + protected Vector $messages = Vector {}; + + protected Vector $validateMethods = Vector {}; protected bool $shouldThrowException = false; - // disabled type assert for request parameters - protected bool $skipValidateStructure = true; + // disabled type assert for request parameters + protected bool $skipValidateStructure = true; public function validateRequest(ServerRequestInterface $request): void { $this->request = $request; @@ -44,9 +44,9 @@ public function validateRequest(ServerRequestInterface $request): void { public function validate(): bool { if (!is_null($this->request)) { - $this->assertStructure(); + $this->assertStructure(); } - if($this->errors()->count()) { + if ($this->errors()->count()) { if ($this->shouldThrowException) { throw new ValidationException($this); } @@ -54,14 +54,14 @@ public function validate(): bool { } return true; } - + <<__Memoize>> public function errors(): ImmVector { return $this->assertValidateResult()->immutable(); } protected function assertStructure(): void { - if(!$this->skipValidateStructure) { + if (!$this->skipValidateStructure) { // here } } diff --git a/src/Foundation/Validation/ValidatorFactory.php b/src/Foundation/Validation/ValidatorFactory.php index e5cf52d..af75ff3 100644 --- a/src/Foundation/Validation/ValidatorFactory.php +++ b/src/Foundation/Validation/ValidatorFactory.php @@ -20,10 +20,10 @@ use Psr\Http\Message\ServerRequestInterface; class ValidatorFactory { - + public function __construct( protected Validator $validatorName, - protected ServerRequestInterface $request + protected ServerRequestInterface $request, ) {} public function validator(): Validator { diff --git a/src/Log/LogServiceModule.php b/src/Log/LogServiceModule.php index 7943ce7..b3a324a 100644 --- a/src/Log/LogServiceModule.php +++ b/src/Log/LogServiceModule.php @@ -1,4 +1,4 @@ -> - public function provide(FactoryContainer $container): void - { + public function provide(FactoryContainer $container): void { $container->set( LoggerInterface::class, $container ==> $this->defaultLogger(), - \Ytake\HHContainer\Scope::SINGLETON + \Ytake\HHContainer\Scope::SINGLETON, ); } diff --git a/src/Middleware/LogExceptionMiddleware.php b/src/Middleware/LogExceptionMiddleware.php index 5af4d81..7462579 100644 --- a/src/Middleware/LogExceptionMiddleware.php +++ b/src/Middleware/LogExceptionMiddleware.php @@ -33,12 +33,15 @@ public function process( ): ResponseInterface { try { return $handler->handle($request); - } catch(\Exception $e) { - $this->log->warning($e->getMessage(), [ - 'file' => $e->getFile(), - 'line' => $e->getLine(), - 'trace' => $e->getTraceAsString() - ]); + } catch (\Exception $e) { + $this->log->warning( + $e->getMessage(), + [ + 'file' => $e->getFile(), + 'line' => $e->getLine(), + 'trace' => $e->getTraceAsString(), + ], + ); throw $e; } } diff --git a/src/Middleware/SimpleCorsMiddleware.php b/src/Middleware/SimpleCorsMiddleware.php index 8eb4ec8..1f07b1f 100644 --- a/src/Middleware/SimpleCorsMiddleware.php +++ b/src/Middleware/SimpleCorsMiddleware.php @@ -24,23 +24,29 @@ use Interop\Http\Server\MiddlewareInterface; use Interop\Http\Server\RequestHandlerInterface; -type CorsSetting = shape('origin' => string, 'header' => string, 'methods' => Vector); +type CorsSetting = shape( + 'origin' => string, + 'header' => string, + 'methods' => Vector, +); -enum AccessControl: string as string { +enum AccessControl : string as string { AllowOrigin = 'Access-Control-Allow-Origin'; AllowHeaders = 'Access-Control-Allow-Headers'; AllowMethods = 'Access-Control-Allow-Methods'; } class SimpleCorsMiddleware implements MiddlewareInterface { - + protected string $allowOrigin = '*'; - protected string $allowHeaders = 'X-Requested-With, Content-Type, Accept, Origin, Authorization'; - protected Vector $allowMethods = Vector{ - HttpMethod::GET, - HttpMethod::HEAD, - HttpMethod::POST, - }; + protected string + $allowHeaders = 'X-Requested-With, Content-Type, Accept, Origin, Authorization'; + protected Vector + $allowMethods = Vector { + HttpMethod::GET, + HttpMethod::HEAD, + HttpMethod::POST, + }; public function __construct(protected CorsSetting $cors) {} @@ -51,11 +57,17 @@ public function process( $response = $handler->handle($request); $origin = ($this->cors['origin']) ?? $this->allowOrigin; $header = ($this->cors['header']) ?? $this->allowHeaders; - $methods = ($this->cors['methods']->isEmpty()) ? $this->allowMethods : $this->cors['methods']; - return $response - ->withHeader(AccessControl::AllowOrigin, $origin) - ->withHeader(AccessControl::AllowHeaders, $header) - ->withHeader(AccessControl::AllowMethods, $this->implodeMethods($methods)); + $methods = + ($this->cors['methods']->isEmpty()) + ? $this->allowMethods + : $this->cors['methods']; + return + $response->withHeader(AccessControl::AllowOrigin, $origin) + ->withHeader(AccessControl::AllowHeaders, $header) + ->withHeader( + AccessControl::AllowMethods, + $this->implodeMethods($methods), + ); } protected function implodeMethods(Vector $methods): string { diff --git a/src/Response/Emitter.php b/src/Response/Emitter.php index 0a97a49..aa44b2a 100644 --- a/src/Response/Emitter.php +++ b/src/Response/Emitter.php @@ -1,4 +1,4 @@ -> - public function provide(FactoryContainer $container): void - { + public function provide(FactoryContainer $container): void { $container->set( - \Facebook\HackRouter\BaseRouter::class, + \Facebook\HackRouter\BaseRouter::class, $container ==> new \Nazg\Routing\Router( - $this->resolveRoutes($container) + $this->resolveRoutes($container), ), - \Ytake\HHContainer\Scope::SINGLETON + \Ytake\HHContainer\Scope::SINGLETON, ); } - + protected function resolveRoutes(FactoryContainer $container): ImmRouteMap { $config = $container->get(Service::CONFIG); - if(is_array($config)) { - if(array_key_exists(Service::ROUTES, $config)) { + if (is_array($config)) { + if (array_key_exists(Service::ROUTES, $config)) { return $config[Service::ROUTES]; } } diff --git a/src/Routing/Router.php b/src/Routing/Router.php index d841697..5776209 100644 --- a/src/Routing/Router.php +++ b/src/Routing/Router.php @@ -26,27 +26,30 @@ type ImmRouteMap = ImmMap>; final class Router extends BaseRouter { - + public function __construct(private ImmRouteMap $routeMap) {} - protected function getRoutes(): ImmMap> { + protected function getRoutes( + ): ImmMap> { $i = $this->routeMap->getIterator(); $map = []; - while($i->valid()) { + while ($i->valid()) { $map[$this->convertHttpMethod($i->key())] = $i->current(); $i->next(); } return new ImmMap($map); } - private function convertHttpMethod(HttpMethod $method): HackRouterHttpMethod { + private function convertHttpMethod( + HttpMethod $method, + ): HackRouterHttpMethod { switch (HttpMethod::assert($method)) { case HttpMethod::GET: return HackRouterHttpMethod::GET; case HttpMethod::HEAD: return HackRouterHttpMethod::HEAD; default: - return HackRouterHttpMethod::POST; + return HackRouterHttpMethod::POST; } } } diff --git a/src/http_enum.php b/src/http_enum.php index 35b8094..b1cb2e2 100644 --- a/src/http_enum.php +++ b/src/http_enum.php @@ -17,15 +17,15 @@ */ namespace Nazg\Http; -enum HttpMethod: string { +enum HttpMethod : string { HEAD = 'HEAD'; GET = 'GET'; - POST = 'POST'; + POST = 'POST'; PATCH = 'PATCH'; PUT = 'PUT'; DELETE = 'DELETE'; } -enum StatusCode: int { +enum StatusCode : int { StatusInternalServerError = 500; }