1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yeelight\Http\Controllers\Api\Middleware; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
use Dingo\Api\Exception\ResourceException; |
7
|
|
|
use Illuminate\Auth\AuthenticationException; |
8
|
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException; |
9
|
|
|
use Illuminate\Http\Exceptions\HttpResponseException; |
10
|
|
|
use League\OAuth2\Server\Exception\OAuthServerException; |
11
|
|
|
use Prettus\Validator\Exceptions\ValidatorException; |
12
|
|
|
use Symfony\Component\HttpKernel\Exception\HttpException; |
13
|
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; |
14
|
|
|
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Class ApiAccessMiddleware |
18
|
|
|
* |
19
|
|
|
* @category Yeelight |
20
|
|
|
* |
21
|
|
|
* @package Yeelight\Http\Controllers\Api\Middleware |
22
|
|
|
* |
23
|
|
|
* @author Sheldon Lee <[email protected]> |
24
|
|
|
* |
25
|
|
|
* @license https://opensource.org/licenses/MIT MIT |
26
|
|
|
* |
27
|
|
|
* @link https://www.yeelight.com |
28
|
|
|
*/ |
29
|
|
|
class ApiAccessMiddleware |
30
|
|
|
{ |
31
|
|
|
/** |
32
|
|
|
* Handle an incoming request. |
33
|
|
|
* |
34
|
|
|
* @param \Illuminate\Http\Request $request Request |
35
|
|
|
* @param \Closure $next Closure |
36
|
|
|
* |
37
|
|
|
* @throws HttpException |
38
|
|
|
* |
39
|
|
|
* @return mixed |
40
|
|
|
*/ |
41
|
|
|
public function handle($request, Closure $next) |
42
|
|
|
{ |
43
|
|
|
try { |
44
|
|
|
$response = $next($request); |
45
|
|
|
|
46
|
|
|
// Was an exception thrown? If so and available catch in our middleware |
47
|
|
|
if (isset($response->exception) && $response->exception) { |
48
|
|
|
throw $response->exception; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $response; |
52
|
|
|
} catch (OAuthServerException $e) { |
53
|
|
|
$message = env('API_DEBUG') ? $e->getMessage() : null; |
54
|
|
|
|
55
|
|
|
throw new HttpException($e->getHttpStatusCode(), $message, $e, $e->getHttpHeaders()); |
56
|
|
|
} catch (HttpResponseException $e) { |
57
|
|
|
$message = env('API_DEBUG') ? $e->getMessage() : null; |
58
|
|
|
|
59
|
|
|
throw new HttpException($e->getResponse()->getStatusCode(), $message, $e); |
60
|
|
|
} catch (AuthenticationException $e) { |
61
|
|
|
throw new UnauthorizedHttpException(null, $e->getMessage(), $e); |
62
|
|
|
} catch (ValidatorException $e) { |
63
|
|
|
$messageBag = $e->getMessageBag(); |
64
|
|
|
|
65
|
|
|
throw new ResourceException($messageBag->first(), $messageBag->all()); |
66
|
|
|
} catch (ModelNotFoundException $e) { |
67
|
|
|
throw new NotFoundHttpException('No results found.'); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|