Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented cors handling with cors headers on exceptions, refactored… #24

Merged
9 commits merged into from
Dec 30, 2015
23 changes: 14 additions & 9 deletions Contract/Exception/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
namespace Spira\Core\Contract\Exception;

use Exception;
use Illuminate\Http\JsonResponse;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Spira\Core\Responder\Contract\TransformableInterface;
use Spira\Core\Responder\Transformers\EloquentModelTransformer;
Expand Down Expand Up @@ -66,28 +67,32 @@ public function render($request, Exception $e)
'trace' => explode("\n", $e->getTraceAsString()),
];

$response = [
$responseData = [
'message' => $message,
];

$statusCode = Response::HTTP_INTERNAL_SERVER_ERROR; //default

if ($e instanceof HttpExceptionInterface) {
$statusCode = $e->getStatusCode();

if (method_exists($e, 'getResponse')) {
if ($e instanceof TransformableInterface) {
$response = $e->transform(\App::make(EloquentModelTransformer::class));
$responseData = $e->transform(\App::make(EloquentModelTransformer::class));
} else {
$response = $e->getResponse();
$responseData = $e->getResponse();
}
}
}

if ($debug) {
$response['debug'] = $debugData;
$responseData['debug'] = $debugData;
}

return response()->json($response, $statusCode, [], JSON_PRETTY_PRINT);
$response = parent::render($request, $e);

$response = new JsonResponse($responseData, $response->getStatusCode(), $response->headers->all(), JSON_PRETTY_PRINT);

$response->exception = $e;

app('Asm89\Stack\CorsService')->addActualRequestHeaders($response, $request);

return $response;
}
}
8 changes: 2 additions & 6 deletions Controllers/RequestValidationTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ protected function notFoundException($keyName = '')
// @codeCoverageIgnoreEnd
}

throw new ValidationException($validation->getMessageBag());
return new ValidationException($validation->getMessageBag());
}

/**
Expand All @@ -72,11 +72,7 @@ protected function notFoundManyException($ids, $models, $keyName = '')
if ($models->get($id)) {
$errors[] = null;
} else {
try {
throw $this->notFoundException($keyName);
} catch (ValidationException $e) {
$errors[] = $e;
}
$errors[] = $this->notFoundException($keyName);
}
}

Expand Down
28 changes: 7 additions & 21 deletions Validation/ValidationException.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,16 @@ class ValidationException extends HttpException implements TransformableInterfa
/**
* Create a new validation exception instance.
* @param MessageBag $errors
* @param string $message
* @param \Exception $previous
* @param array $headers
* @param int $code
*/
public function __construct(MessageBag $errors)
public function __construct(MessageBag $errors, $message = 'There was an issue with the validation of provided entity', \Exception $previous = null, array $headers = [], $code = 0)
{
$this->errors = $errors->toArray();
}

/**
* Returns the status code.
*
* @return int An HTTP response status code
*/
public function getStatusCode()
{
return Response::HTTP_UNPROCESSABLE_ENTITY;
parent::__construct(Response::HTTP_UNPROCESSABLE_ENTITY, $message, $previous, $headers, $code);
}

/**
Expand All @@ -52,21 +48,11 @@ public function getStatusCode()
public function getResponse()
{
return [
'message' => 'There was an issue with the validation of provided entity',
'message' => $this->getMessage(),
'invalid' => $this->errors,
];
}

/**
* Returns response headers.
*
* @return array Response headers
*/
public function getHeaders()
{
return [];
}

/**
* @param TransformerInterface $transformer
* @return mixed
Expand Down
22 changes: 11 additions & 11 deletions Validation/ValidationExceptionCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,19 @@ class ValidationExceptionCollection extends HttpException implements Transformab
*/
private $exceptions;

public function __construct(array $exceptions)
{
$this->exceptions = $exceptions;
}

/**
* Returns the status code.
*
* @return int An HTTP response status code
* Create a new validation collection exception instance.
* @param array $exceptions
* @param string $message
* @param \Exception $previous
* @param array $headers
* @param int $code
*/
public function getStatusCode()
public function __construct(array $exceptions, $message = 'There was an issue with the validation of provided entities', \Exception $previous = null, array $headers = [], $code = 0)
{
return Response::HTTP_UNPROCESSABLE_ENTITY;
$this->exceptions = $exceptions;

parent::__construct(Response::HTTP_UNPROCESSABLE_ENTITY, $message, $previous, $headers, $code);
}

/**
Expand Down Expand Up @@ -63,7 +63,7 @@ public function getResponse()
public function transform(TransformerInterface $transformer)
{
return [
'message' => 'There was an issue with the validation of provided entity',
'message' => $this->getMessage(),
'invalid' => $transformer->transformCollection($this->getResponse()),
];
}
Expand Down
6 changes: 4 additions & 2 deletions bootstrap/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
$app->withEloquent();

$app->configure('regions');
$app->configure('cors');

/*
|--------------------------------------------------------------------------
Expand Down Expand Up @@ -67,7 +68,7 @@

$app->middleware([
Spira\Core\Middleware\TransformInputDataMiddleware::class,

Barryvdh\Cors\HandleCors::class,
]);

$app->routeMiddleware([
Expand All @@ -86,9 +87,10 @@
| totally optional, so you are not required to uncomment this line.
|
*/
$app->register(Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
$app->register(Barryvdh\Cors\LumenServiceProvider::class);
$app->register(Spira\Core\Providers\AppServiceProvider::class);
$app->register(Bosnadev\Database\DatabaseServiceProvider::class);
$app->register(Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);

/*
|--------------------------------------------------------------------------
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
"bosnadev/database": "^0.11.0",
"league/fractal": "0.12.*",
"illuminate/mail": "^5.0",
"elasticquent/elasticquent": "1.1.*"
"elasticquent/elasticquent": "1.1.*",
"barryvdh/laravel-cors": "0.7.x"
},
"require-dev": {
"satooshi/php-coveralls": "dev-master",
Expand Down
103 changes: 97 additions & 6 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions config/cors.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value, the allowed methods however have to be explicitly listed.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
'exposedHeaders' => [],
'maxAge' => 0,
'hosts' => [],
];