diff --git a/phpunit.xml b/phpunit.xml index b0c0bbf04..86a91ad12 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -9,7 +9,7 @@ processIsolation="false" stopOnFailure="false" syntaxCheck="false" -> + > ./tests/ diff --git a/src/ApiServiceProvider.php b/src/ApiServiceProvider.php index 1e89deecf..b08d0aa34 100644 --- a/src/ApiServiceProvider.php +++ b/src/ApiServiceProvider.php @@ -1,5 +1,6 @@ package('dingo/api', 'api', __DIR__); - $this->app['Dingo\Api\Dispatcher'] = function($app) { return $app['dingo.api.dispatcher']; }; - $this->app['Dingo\Api\Auth\Shield'] = function($app) { return $app['dingo.api.auth']; }; + $this->app['Dingo\Api\Dispatcher'] = function ($app) { + return $app['dingo.api.dispatcher']; + }; + $this->app['Dingo\Api\Auth\Shield'] = function ($app) { + return $app['dingo.api.auth']; + }; $formats = $this->prepareResponseFormats(); @@ -32,25 +38,22 @@ public function boot() /** * Prepare the response formats. - * + * * @return array */ protected function prepareResponseFormats() { $formats = []; - foreach ($this->app['config']['api::formats'] as $key => $format) - { - if (is_callable($format)) - { + foreach ($this->app['config']['api::formats'] as $key => $format) { + if (is_callable($format)) { $format = call_user_func($format, $this->app); } $formats[$key] = $format; } - if (empty($formats)) - { + if (empty($formats)) { throw new RuntimeException('No registered response formats.'); } @@ -59,7 +62,7 @@ protected function prepareResponseFormats() /** * Register bindings for the service provider. - * + * * @return void */ public function register() @@ -68,11 +71,25 @@ public function register() $this->registerRouter(); $this->registerTransformer(); $this->registerExceptionHandler(); - $this->registerAuthentication(); $this->registerMiddlewares(); - $this->app->booting(function($app) - { + $this->app->booting(function ($app) { + // grab the setting for the auth driver your using. + $shield_type = $app['config']->get('api::auth_provider'); + $shield_class = $app['config']->get("api::auth_drivers.$shield_type"); + + $app['dingo.api.auth'] = $app->share(function ($app) use ($shield_type, $shield_class) { + $providers = []; + foreach ($app['config']['api::auth'] as $key => $provider) { + if (is_callable($provider)) { + $provider = call_user_func($provider, $app); + } + $providers[$key] = $provider; + } + + return new $shield_class($app[$shield_type], $app, $providers); + }); + $router = $app['router']; $router->setExceptionHandler($app['dingo.api.exception']); @@ -86,17 +103,15 @@ public function register() /** * Register and replace the bound router. - * + * * @return void */ protected function registerRouter() { - $this->app['router'] = $this->app->share(function($app) - { + $this->app['router'] = $this->app->share(function ($app) { $router = new Router($app['events'], $app); - if ($app['env'] == 'testing') - { + if ($app['env'] == 'testing') { $router->disableFilters(); } @@ -106,30 +121,27 @@ protected function registerRouter() /** * Register the API dispatcher. - * + * * @return void */ protected function registerDispatcher() { - $this->app['dingo.api.dispatcher'] = $this->app->share(function($app) - { + $this->app['dingo.api.dispatcher'] = $this->app->share(function ($app) { return new Dispatcher($app['request'], $app['url'], $app['router'], $app['dingo.api.auth']); }); } /** * Register the API transformer. - * + * * @return void */ protected function registerTransformer() { - $this->app['dingo.api.transformer'] = $this->app->share(function($app) - { + $this->app['dingo.api.transformer'] = $this->app->share(function ($app) { $factory = new Factory($app); - if ($app['config']->has('api::transformer')) - { + if ($app['config']->has('api::transformer')) { $transformer = call_user_func($app['config']['api::transformer'], $app); $factory->setTransformer($transformer); @@ -141,45 +153,19 @@ protected function registerTransformer() /** * Register the exception handler. - * + * * @return void */ protected function registerExceptionHandler() { - $this->app['dingo.api.exception'] = $this->app->share(function($app) - { + $this->app['dingo.api.exception'] = $this->app->share(function ($app) { return new ExceptionHandler; }); } - /** - * Register the API authentication. - * - * @return void - */ - protected function registerAuthentication() - { - $this->app['dingo.api.auth'] = $this->app->share(function($app) - { - $providers = []; - - foreach ($app['config']['api::auth'] as $key => $provider) - { - if (is_callable($provider)) - { - $provider = call_user_func($provider, $app); - } - - $providers[$key] = $provider; - } - - return new Shield($app['auth'], $app, $providers); - }); - } - /** * Register the middlewares. - * + * * @return void */ protected function registerMiddlewares() diff --git a/src/Auth/AuthorizationProvider.php b/src/Auth/AuthorizationProvider.php index 8c82ab0d6..fa26ffcce 100644 --- a/src/Auth/AuthorizationProvider.php +++ b/src/Auth/AuthorizationProvider.php @@ -3,33 +3,33 @@ use Illuminate\Http\Request; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; -abstract class AuthorizationProvider extends Provider { +abstract class AuthorizationProvider extends Provider +{ /** * Array of provider specific options. - * + * * @var array */ protected $options = []; /** * Validate the requests authorization header for the provider. - * - * @param \Illuminate\Http\Request $request + * + * @param \Illuminate\Http\Request $request * @return bool * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException */ public function validateAuthorizationHeader(Request $request) { - if ( ! starts_with(strtolower($request->headers->get('authorization')), $this->getAuthorizationMethod())) - { + if (!starts_with(strtolower($request->headers->get('authorization')), $this->getAuthorizationMethod())) { throw new BadRequestHttpException; } } /** * Get the providers authorization method. - * + * * @return string */ abstract public function getAuthorizationMethod(); diff --git a/src/Auth/BasicProvider.php b/src/Auth/BasicProvider.php index af727b136..6c5c83509 100644 --- a/src/Auth/BasicProvider.php +++ b/src/Auth/BasicProvider.php @@ -5,26 +5,27 @@ use Illuminate\Auth\AuthManager; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; -class BasicProvider extends AuthorizationProvider { +class BasicProvider extends AuthorizationProvider +{ /** * Illuminate authentication manager. - * + * * @var \Illuminate\Auth\AuthManager */ protected $auth; /** * Basic auth identifier. - * + * * @var string */ protected $identifier; /** * Create a new Dingo\Api\Auth\BasicProvider instance. - * - * @param \Illuminate\Auth\AuthManager $auth + * + * @param \Illuminate\Auth\AuthManager $auth * @return void */ public function __construct(AuthManager $auth, $identifier = 'email') @@ -35,17 +36,16 @@ public function __construct(AuthManager $auth, $identifier = 'email') /** * Authenticate request with Basic. - * + * * @param \Illuminate\Http\Request $request - * @param \Illuminate\Routing\Route $route + * @param \Illuminate\Routing\Route $route * @return int */ public function authenticate(Request $request, Route $route) { $this->validateAuthorizationHeader($request); - if ($response = $this->auth->onceBasic($this->identifier) and $response->getStatusCode() === 401) - { + if ($response = $this->auth->onceBasic($this->identifier) and $response->getStatusCode() === 401) { throw new UnauthorizedHttpException('Basic', 'Invalid authentication credentials.'); } @@ -54,12 +54,11 @@ public function authenticate(Request $request, Route $route) /** * Get the providers authorization method. - * + * * @return string */ public function getAuthorizationMethod() { return 'basic'; } - } diff --git a/src/Auth/DingoOAuth2Provider.php b/src/Auth/DingoOAuth2Provider.php index b1324043c..5746ddeba 100644 --- a/src/Auth/DingoOAuth2Provider.php +++ b/src/Auth/DingoOAuth2Provider.php @@ -7,19 +7,20 @@ use Dingo\OAuth2\Exception\InvalidTokenException; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; -class DingoOAuth2Provider extends AuthorizationProvider { +class DingoOAuth2Provider extends AuthorizationProvider +{ /** * OAuth 2.0 resource server instance. - * + * * @var \Dingo\OAuth2\Server\Resource */ protected $resource; /** * Create a new Dingo\Api\Auth\OAuth2Provider instance. - * - * @param \Dingo\OAuth2\Server\Resource $resource + * + * @param \Dingo\OAuth2\Server\Resource $resource * @return void */ public function __construct(Resource $resource) @@ -29,58 +30,51 @@ public function __construct(Resource $resource) /** * Authenticate request with the OAuth 2.0 resource server. - * + * * @param \Illuminate\Http\Request $request - * @param \Illuminate\Routing\Route $route + * @param \Illuminate\Routing\Route $route * @return int */ public function authenticate(Request $request, Route $route) { - try - { + try { $this->validateAuthorizationHeader($request); - } - catch (Exception $exception) - { + } catch (Exception $exception) { // If we catch an exception here it means the header was missing so we'll // now look for the access token in the query string. If we don't have // the query string either then we'll re-throw the exception. - if ( ! $request->query('access_token', false)) - { + if (!$request->query('access_token', false)) { throw $exception; } } $scopes = $this->getRouteScopes($route); - try - { + try { $token = $this->resource->validateRequest($scopes); return $token->getUserId(); - } - catch (InvalidTokenException $exception) - { + } catch (InvalidTokenException $exception) { throw new UnauthorizedHttpException('Bearer', $exception->getMessage(), $exception); } } /** * Get the routes scopes. - * - * @param \Illuminate\Routing\Route $route + * + * @param \Illuminate\Routing\Route $route * @return array */ protected function getRouteScopes(Route $route) { $action = $route->getAction(); - return isset($action['scopes']) ? (array) $action['scopes'] : []; + return isset($action['scopes']) ? (array)$action['scopes'] : []; } /** * Get the providers authorization method. - * + * * @return string */ public function getAuthorizationMethod() diff --git a/src/Auth/LeagueOAuth2Provider.php b/src/Auth/LeagueOAuth2Provider.php index ed6783d3b..61c1cf46b 100644 --- a/src/Auth/LeagueOAuth2Provider.php +++ b/src/Auth/LeagueOAuth2Provider.php @@ -7,27 +7,28 @@ use League\OAuth2\Server\Exception\InvalidAccessTokenException; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; -class LeagueOAuth2Provider extends AuthorizationProvider { +class LeagueOAuth2Provider extends AuthorizationProvider +{ /** * OAuth 2.0 resource server instance. - * + * * @var \Dingo\OAuth2\Server\Resource */ protected $resource; /** * Indicates whether access token is limited to headers only. - * + * * @var bool */ protected $httpHeadersOnly = false; /** * Create a new Dingo\Api\Auth\OAuth2Provider instance. - * - * @param \Dingo\OAuth2\Server\Resource $resource - * @param bool $httpHeadersOnly + * + * @param \Dingo\OAuth2\Server\Resource $resource + * @param bool $httpHeadersOnly * @return void */ public function __construct(Resource $resource, $httpHeadersOnly = false) @@ -38,64 +39,56 @@ public function __construct(Resource $resource, $httpHeadersOnly = false) /** * Authenticate request with the OAuth 2.0 resource server. - * + * * @param \Illuminate\Http\Request $request - * @param \Illuminate\Routing\Route $route + * @param \Illuminate\Routing\Route $route * @return int */ public function authenticate(Request $request, Route $route) { - try - { + try { $this->validateAuthorizationHeader($request); - } - catch (Exception $exception) - { + } catch (Exception $exception) { + dd($exception->getMessage().' in '.$exception->getFile().' on'. $exception->getLine()); // If we catch an exception here it means the header was missing so we'll // now look for the access token in the query string. If we don't have // the query string either then we'll re-throw the exception. - if ( ! $request->query('access_token', false)) - { + if (!$request->query('access_token', false)) { throw $exception; } } - try - { + try { $this->resource->isValid($this->httpHeadersOnly); - foreach ($this->getRouteScopes($route) as $scope) - { - if ( ! $this->resource->hasScope($scope)) - { - throw new InvalidAccessTokenException('Requested scope "'.$scope.'" is not associated with this access token.'); + foreach ($this->getRouteScopes($route) as $scope) { + if (!$this->resource->hasScope($scope)) { + throw new InvalidAccessTokenException('Requested scope "' . $scope . '" is not associated with this access token.'); } } return $this->resource->getOwnerId(); - } - catch (InvalidAccessTokenException $exception) - { + } catch (InvalidAccessTokenException $exception) { throw new UnauthorizedHttpException('Bearer', $exception->getMessage(), $exception); } } /** * Get the routes scopes. - * - * @param \Illuminate\Routing\Route $route + * + * @param \Illuminate\Routing\Route $route * @return array */ protected function getRouteScopes(Route $route) { $action = $route->getAction(); - return isset($action['scopes']) ? (array) $action['scopes'] : []; + return isset($action['scopes']) ? (array)$action['scopes'] : []; } /** * Get the providers authorization method. - * + * * @return string */ public function getAuthorizationMethod() diff --git a/src/Auth/Provider.php b/src/Auth/Provider.php index 806445b25..5ff206a9a 100644 --- a/src/Auth/Provider.php +++ b/src/Auth/Provider.php @@ -3,13 +3,14 @@ use Illuminate\Http\Request; use Illuminate\Routing\Route; -abstract class Provider { +abstract class Provider +{ /** * Authenticate the request and return the authenticated users ID. - * + * * @param \Illuminate\Http\Request $request - * @param \Illuminate\Routing\Route $route + * @param \Illuminate\Routing\Route $route * @return int */ abstract public function authenticate(Request $request, Route $route); diff --git a/src/Auth/SentryOAuthProvider.php b/src/Auth/SentryOAuthProvider.php new file mode 100644 index 000000000..e63fc1446 --- /dev/null +++ b/src/Auth/SentryOAuthProvider.php @@ -0,0 +1,55 @@ +resource = $resource; + $this->httpHeadersOnly = $httpHeadersOnly; + $this->sentry = $sentry; + } + + /** + * Authenticate request with the OAuth 2.0 resource server. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Routing\Route $route + * @return int + */ + public function authenticate(Request $request, Route $route) + { + $id = parent::authenticate($request, $route); + $user = $this->sentry->getUserRepository()->findById($id); + $this->sentry->stateless($user); + return $id; + } + + /** + * Get the providers authorization method. + * + * @return string + */ + public function getAuthorizationMethod() + { + return 'bearer'; + } +} diff --git a/src/Auth/SentryProvider.php b/src/Auth/SentryProvider.php new file mode 100644 index 000000000..62fc8f0bb --- /dev/null +++ b/src/Auth/SentryProvider.php @@ -0,0 +1,42 @@ +sentry = $sentry; + $this->identifier = $identifier; + } + + public function authenticate(Request $request, Route $route) + { + if (($user = $this->sentry->getUser())) { + return $user->id; + } + // Logic to authenticate the user for the given request. If it fails... + throw new UnauthorizedHttpException(null, 'Your username or password is incorrect.'); + } + + /** + * Get the providers authorization method. + * + * @return string + */ + public function getAuthorizationMethod() + { + return 'sentry'; + } +} diff --git a/src/Auth/SentryShield.php b/src/Auth/SentryShield.php new file mode 100644 index 000000000..cb2c49f87 --- /dev/null +++ b/src/Auth/SentryShield.php @@ -0,0 +1,38 @@ +auth = $auth; + $this->container = $container; + $this->providers = $providers; + } + + /** + * @return \Cartalyst\Sentry\Users\UserInterface|\Illuminate\Auth\GenericUser|\Illuminate\Database\Eloquent\Model|null + */ + public function getUser() + { + if ($this->user) { + return $this->user; + } elseif (!$this->userId) { + return null; + } elseif (!($user = $this->auth->getUser())) { + $this->auth->setUser($this->auth->findUserById($this->userId)); + } + + return $this->user = $this->auth->getUser(); + } +} \ No newline at end of file diff --git a/src/Auth/Shield.php b/src/Auth/Shield.php index b305c1127..2516b266a 100644 --- a/src/Auth/Shield.php +++ b/src/Auth/Shield.php @@ -11,58 +11,59 @@ use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; -class Shield { +class Shield +{ /** * Illuminate auth instance. - * + * * @var \Illuminate\Auth\AuthManager */ protected $auth; /** * Illuminate application container instance. - * + * * @var \Illuminate\Container\Container */ protected $container; /** * Array of authentication providers. - * + * * @var array */ protected $providers; /** * The provider used for authentication. - * + * * @var \Dingo\Api\Auth\Provider */ protected $usedProvider; /** * Authenticated user ID. - * + * * @var int */ protected $userId; /** * Authenticated user instance. - * + * * @var \Illuminate\Auth\GenericUser|\Illuminate\Database\Eloquent\Model */ protected $user; - /** - * Create a new Dingo\Api\Authentication instance. - * - * @param \Illuminate\Auth\AuthManager $auth - * @param \Illuminate\Container\Container $container - * @param array $providers - * @return void - */ + /** + * Create a new Dingo\Api\Authentication instance. + * + * @param \Illuminate\Auth\AuthManager $auth + * @param \Illuminate\Container\Container $container + * @param array $providers + * @return void + */ public function __construct(AuthManager $auth, Container $container, array $providers) { $this->auth = $auth; @@ -72,7 +73,7 @@ public function __construct(AuthManager $auth, Container $container, array $prov /** * Authenticate the current request. - * + * * @return null|\Dingo\Api\Http\Response */ public function authenticate(Request $request, Route $route) @@ -82,22 +83,16 @@ public function authenticate(Request $request, Route $route) // Spin through each of the registered authentication providers and attempt to // authenticate through one of them. This allows a developer to implement // and allow a number of different authentication mechanisms. - foreach ($this->providers as $key => $provider) - { - try - { + foreach ($this->providers as $key => $provider) { + try { $id = $provider->authenticate($request, $route); $this->usedProvider = $provider; return $this->userId = $id; - } - catch (UnauthorizedHttpException $exception) - { + } catch (UnauthorizedHttpException $exception) { $exceptionStack[] = $exception; - } - catch (BadRequestHttpException $exception) - { + } catch (BadRequestHttpException $exception) { // We won't add this exception to the stack as it's thrown when the provider // is unable to authenticate due to the correct authorization header not // being set. We will throw an exception for this below. @@ -106,8 +101,7 @@ public function authenticate(Request $request, Route $route) $exception = array_shift($exceptionStack); - if ($exception === null) - { + if ($exception === null) { $exception = new UnauthorizedHttpException(null, 'Failed to authenticate because of bad credentials or an invalid authorization header.'); } @@ -116,21 +110,16 @@ public function authenticate(Request $request, Route $route) /** * Get the authenticated user. - * + * * @return \Illuminate\Auth\GenericUser|\Illuminate\Database\Eloquent\Model */ public function getUser() { - if ($this->user) - { + if ($this->user) { return $this->user; - } - elseif ( ! $this->userId) - { + } elseif (!$this->userId) { return null; - } - elseif ( ! $this->auth->check()) - { + } elseif (!$this->auth->check()) { $this->auth->onceUsingId($this->userId); } @@ -139,7 +128,7 @@ public function getUser() /** * Alias for getUser. - * + * * @return \Illuminate\Auth\GenericUser|\Illuminate\Database\Eloquent\Model */ public function user() @@ -149,8 +138,8 @@ public function user() /** * Set the authenticated user. - * - * @param \Illuminate\Auth\GenericUser|\Illuminate\Database\Eloquent\Model $user + * + * @param \Illuminate\Auth\GenericUser|\Illuminate\Database\Eloquent\Model $user * @return \Dingo\Api\Authentication */ public function setUser($user) @@ -162,17 +151,17 @@ public function setUser($user) /** * Check if a user has authenticated with the API. - * + * * @return bool */ public function check() { - return ! is_null($this->user()); + return !is_null($this->user()); } /** * Get the provider used for authentication. - * + * * @return \Dingo\Api\Auth\Provider */ public function getUsedProvider() @@ -182,9 +171,9 @@ public function getUsedProvider() /** * Extend the authentication layer with a custom provider. - * - * @param string $key - * @param object|callable $provider + * + * @param string $key + * @param object|callable $provider * @return void */ public function extend($key, $provider) diff --git a/src/Dispatcher.php b/src/Dispatcher.php index d4b60d14a..b2b008877 100644 --- a/src/Dispatcher.php +++ b/src/Dispatcher.php @@ -12,78 +12,79 @@ use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; -class Dispatcher { +class Dispatcher +{ /** * Illuminate request instance. - * + * * @var \Illuminate\Http\Request */ protected $request; /** * Illuminate url generator instance. - * + * * @var \Illuminate\Routing\UrlGenerator */ protected $url; /** * API router instance. - * + * * @var \Dingo\Api\Routing\Router */ protected $router; /** * API authentication shield instance. - * + * * @var \Dingo\Api\Auth\Shield */ protected $auth; /** * Internal request stack. - * + * * @var array */ protected $requestStack = []; /** * Internal route stack. - * + * * @var array */ protected $routeStack = []; /** * Version for the request. - * + * * @var string */ protected $version; /** * Request parameters. - * + * * @var array */ protected $parameters = []; /** * Indicates whether the authenticated user is persisted. - * + * * @var bool */ protected $persistAuthenticatedUser = true; /** * Create a new dispatcher instance. - * - * @param \Illuminate\Http\Request $request - * @param \Illuminate\Routing\UrlGenerator $url - * @param \Dingo\Api\Routing\Router $router - * @param \Dingo\Api\Auth\Shield $auth + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Routing\UrlGenerator $url + * @param \Dingo\Api\Routing\Router $router + * @param \Dingo\Api\Auth\Shield $auth * @return void */ public function __construct(Request $request, UrlGenerator $url, Router $router, Shield $auth) @@ -98,7 +99,7 @@ public function __construct(Request $request, UrlGenerator $url, Router $router, /** * Setup the request stack by cloning the initial request. - * + * * @return void */ protected function setupRequestStack() @@ -108,14 +109,13 @@ protected function setupRequestStack() /** * Internal request will be authenticated as the given user. - * - * @param \Illuminate\Auth\GenericUser|\Illuminate\Database\Eloquent\Model $user + * + * @param \Illuminate\Auth\GenericUser|\Illuminate\Database\Eloquent\Model $user * @return \Dingo\Api\Dispatcher */ public function be($user) { - if ( ! $user instanceof Model and ! $user instanceof GenericUser) - { + if (!$user instanceof Model and !$user instanceof GenericUser) { throw new RuntimeException('User must be an instance of either Illuminate\Database\Eloquent\Model or Illuminate\Auth\GenericUser.'); } @@ -126,7 +126,7 @@ public function be($user) /** * Only authenticate with the given user for a single request. - * + * * @return \Dingo\Api\Dispatcher */ public function once() @@ -138,8 +138,8 @@ public function once() /** * Set the version of the API for the next request. - * - * @param string $version + * + * @param string $version * @return \Dingo\Api\Dispatcher */ public function version($version) @@ -151,8 +151,8 @@ public function version($version) /** * Set the parameters to be sent on the next API request. - * - * @param string|array $parameters + * + * @param string|array $parameters * @return \Dingo\Api\Dispatcher */ public function with($parameters) @@ -164,15 +164,15 @@ public function with($parameters) /** * Perform an API request to a named route. - * - * @param string $name - * @param string|array $routeParameters - * @param string|array $parameters + * + * @param string $name + * @param string|array $routeParameters + * @param string|array $parameters * @return mixed */ public function route($name, $routeParameters = [], $parameters = []) { - $version = $this->version ?: $this->router->getDefaultVersion(); + $version = $this->version ? : $this->router->getDefaultVersion(); $route = $this->router->getApiRouteCollection($version)->getByName($name); @@ -183,15 +183,15 @@ public function route($name, $routeParameters = [], $parameters = []) /** * Perform an API request to a controller action. - * - * @param string $name - * @param string|array $actionParameters - * @param string|array $parameters + * + * @param string $name + * @param string|array $actionParameters + * @param string|array $parameters * @return mixed */ public function action($action, $actionParameters = [], $parameters = []) { - $version = $this->version ?: $this->router->getDefaultVersion(); + $version = $this->version ? : $this->router->getDefaultVersion(); $route = $this->router->getApiRouteCollection($version)->getByAction($action); @@ -202,9 +202,9 @@ public function action($action, $actionParameters = [], $parameters = []) /** * Perform API GET request. - * - * @param string $uri - * @param string|array $parameters + * + * @param string $uri + * @param string|array $parameters * @return mixed */ public function get($uri, $parameters = []) @@ -214,9 +214,9 @@ public function get($uri, $parameters = []) /** * Perform API POST request. - * - * @param string $uri - * @param string|array $parameters + * + * @param string $uri + * @param string|array $parameters * @return mixed */ public function post($uri, $parameters = []) @@ -226,9 +226,9 @@ public function post($uri, $parameters = []) /** * Perform API PUT request. - * - * @param string $uri - * @param string|array $parameters + * + * @param string $uri + * @param string|array $parameters * @return mixed */ public function put($uri, $parameters = []) @@ -238,9 +238,9 @@ public function put($uri, $parameters = []) /** * Perform API PATCH request. - * - * @param string $uri - * @param string|array $parameters + * + * @param string $uri + * @param string|array $parameters * @return mixed */ public function patch($uri, $parameters = []) @@ -250,9 +250,9 @@ public function patch($uri, $parameters = []) /** * Perform API DELETE request. - * - * @param string $uri - * @param string|array $parameters + * + * @param string $uri + * @param string|array $parameters * @return mixed */ public function delete($uri, $parameters = []) @@ -262,10 +262,10 @@ public function delete($uri, $parameters = []) /** * Queue up and dispatch a new request. - * - * @param string $verb - * @param string $uri - * @param string|array $parameters + * + * @param string $verb + * @param string $uri + * @param string|array $parameters * @return mixed */ protected function queueRequest($verb, $uri, $parameters) @@ -279,16 +279,15 @@ protected function queueRequest($verb, $uri, $parameters) /** * Create a new internal request from an HTTP verb and URI. - * - * @param string $verb - * @param string $uri - * @param string|array $parameters + * + * @param string $verb + * @param string $uri + * @param string|array $parameters * @return \Dingo\Api\Http\InternalRequest */ protected function createRequest($verb, $uri, $parameters) { - if ( ! isset($this->version)) - { + if (!isset($this->version)) { $this->version = $this->router->getDefaultVersion(); } @@ -296,17 +295,15 @@ protected function createRequest($verb, $uri, $parameters) // if one exists, from the router. $api = $this->router->getApiRouteCollection($this->version); - if ($prefix = $api->option('prefix') and ! starts_with($uri, $prefix)) - { + if ($prefix = $api->option('prefix') and !starts_with($uri, $prefix)) { $uri = "{$prefix}/{$uri}"; } - $parameters = array_merge($this->parameters, (array) $parameters); + $parameters = array_merge($this->parameters, (array)$parameters); $request = InternalRequest::create($uri, $verb, $parameters); - if ($domain = $api->option('domain')) - { + if ($domain = $api->option('domain')) { $request->headers->set('host', $domain); } @@ -317,35 +314,31 @@ protected function createRequest($verb, $uri, $parameters) /** * Build the "Accept" header. - * + * * @return string */ protected function buildAcceptHeader() { - return 'application/vnd.'.$this->router->getVendor().'.'.$this->version.'+json'; + return 'application/vnd.' . $this->router->getVendor() . '.' . $this->version . '+json'; } /** * Attempt to dispatch an internal request. - * - * @param \Dingo\Api\Http\InternalRequest $request + * + * @param \Dingo\Api\Http\InternalRequest $request * @return mixed */ protected function dispatch(InternalRequest $request) { $this->routeStack[] = $this->router->getCurrentRoute(); - - try - { + + try { $response = $this->router->dispatch($request); - if ( ! $response->isOk()) - { + if (!$response->isOk()) { throw new HttpException($response->getStatusCode(), $response->getOriginalContent()); } - } - catch (HttpExceptionInterface $exception) - { + } catch (HttpExceptionInterface $exception) { $this->refreshRequestStack(); throw $exception; @@ -360,20 +353,18 @@ protected function dispatch(InternalRequest $request) * Refresh the request stack by resetting the authentication, * popping the last request from the stack, replacing the * input, and resetting the version and parameters. - * + * * @return void */ protected function refreshRequestStack() { - if ( ! $this->persistAuthenticatedUser) - { + if (!$this->persistAuthenticatedUser) { $this->auth->setUser(null); $this->persistAuthenticatedUser = true; } - if ($route = array_pop($this->routeStack)) - { + if ($route = array_pop($this->routeStack)) { $this->router->setCurrentRoute($route); } @@ -386,7 +377,7 @@ protected function refreshRequestStack() /** * Replace the request input with the previous request input. - * + * * @return void */ protected function replaceRequestInput() @@ -402,14 +393,14 @@ protected function replaceRequestInput() /** * Build a request identifier by joining the verb and URI together. - * - * @param string $verb - * @param string $uri + * + * @param string $verb + * @param string $uri * @return string */ protected function buildRequestIdentifier($verb, $uri) { - return $verb.' '.$uri; + return $verb . ' ' . $uri; } } diff --git a/src/Exception/DeleteResourceFailedException.php b/src/Exception/DeleteResourceFailedException.php index a78d9bfb8..910011465 100644 --- a/src/Exception/DeleteResourceFailedException.php +++ b/src/Exception/DeleteResourceFailedException.php @@ -1,5 +1,6 @@ errors = new MessageBag; - } - else - { + } else { $this->errors = is_array($errors) ? new MessageBag($errors) : $errors; } @@ -40,7 +38,7 @@ public function __construct($message = null, $errors = null, Exception $previous /** * Get the errors message bag. - * + * * @return \Illuminate\Support\MessageBag **/ public function errors() @@ -50,7 +48,7 @@ public function errors() /** * Get the errors message bag. - * + * * @return \Illuminate\Support\MessageBag **/ public function getErrors() @@ -60,12 +58,12 @@ public function getErrors() /** * Determine if message bag has any errors. - * + * * @return bool */ public function hasErrors() { - return ! $this->errors->isEmpty(); + return !$this->errors->isEmpty(); } } diff --git a/src/Exception/StoreResourceFailedException.php b/src/Exception/StoreResourceFailedException.php index fa5aae8e8..871de6800 100644 --- a/src/Exception/StoreResourceFailedException.php +++ b/src/Exception/StoreResourceFailedException.php @@ -1,5 +1,6 @@ handlerHint($callback); - + $this->handlers[$hint] = $callback; } /** * Handle an exception if it has an existing handler. - * - * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception + * + * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception * @return \Illuminate\Http\Response */ public function handle(HttpExceptionInterface $exception) { - foreach ($this->handlers as $hint => $handler) - { - if ($exception instanceof $hint) - { + foreach ($this->handlers as $hint => $handler) { + if ($exception instanceof $hint) { $response = call_user_func($handler, $exception); - if ( ! $response instanceof Response) - { + if (!$response instanceof Response) { $response = new Response($response, $exception->getStatusCode()); } @@ -52,19 +50,21 @@ public function handle(HttpExceptionInterface $exception) /** * Determine if the handler will handle the given exception. - * - * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception + * + * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception * @return bool */ public function willHandle(HttpExceptionInterface $exception) { - return (bool) array_first($this->handlers, function($hint) use ($exception) { return $exception instanceof $hint; }, false); + return (bool)array_first($this->handlers, function ($hint) use ($exception) { + return $exception instanceof $hint; + }, false); } /** * Get the hint for an exception handler. - * - * @param callable $callback + * + * @param callable $callback * @return string */ protected function handlerHint(callable $callback) @@ -78,7 +78,7 @@ protected function handlerHint(callable $callback) /** * Get the exception handlers. - * + * * @return array */ public function getHandlers() diff --git a/src/Facades/API.php b/src/Facades/API.php index 2e2068696..65aae3d11 100644 --- a/src/Facades/API.php +++ b/src/Facades/API.php @@ -7,7 +7,8 @@ /** * @see \Dingo\Api\Routing\Router */ -class API extends Facade { +class API extends Facade +{ /** * Get the registered name of the component. @@ -15,14 +16,14 @@ class API extends Facade { * @return string */ protected static function getFacadeAccessor() - { + { return 'dingo.api.dispatcher'; } /** * Bind an exception handler. - * - * @param \Closure $callback + * + * @param \Closure $callback * @return void */ public static function error(Closure $callback) @@ -32,9 +33,9 @@ public static function error(Closure $callback) /** * Transform a class into a Fractal transformer. - * - * @param string $class - * @param string|\Closure $transformer + * + * @param string $class + * @param string|\Closure $transformer * @return \Dingo\Api\Transformer */ public static function transform($class, $transformer) @@ -44,7 +45,7 @@ public static function transform($class, $transformer) /** * Get the authentication provider. - * + * * @return \Dingo\Api\Auth\Provider */ public static function auth() @@ -54,7 +55,7 @@ public static function auth() /** * Get the authenticated API user. - * + * * @return \Illuminate\Auth\GenericUser|\Illuminate\Database\Eloquent\Model */ public static function user() @@ -64,7 +65,7 @@ public static function user() /** * Determine if a request is internal. - * + * * @return bool */ public static function internal() diff --git a/src/Http/InternalRequest.php b/src/Http/InternalRequest.php index 437b89d79..1989cc693 100644 --- a/src/Http/InternalRequest.php +++ b/src/Http/InternalRequest.php @@ -2,6 +2,7 @@ use Illuminate\Http\Request; -class InternalRequest extends Request { - +class InternalRequest extends Request +{ + } \ No newline at end of file diff --git a/src/Http/Middleware/Authentication.php b/src/Http/Middleware/Authentication.php index b8271bcf0..1ad92e3d3 100644 --- a/src/Http/Middleware/Authentication.php +++ b/src/Http/Middleware/Authentication.php @@ -10,63 +10,64 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; -class Authentication implements HttpKernelInterface { +class Authentication implements HttpKernelInterface +{ /** * The wrapped kernel implementation. - * + * * @var \Symfony\Component\HttpKernel\HttpKernelInterface */ protected $app; /** * Laravel application container. - * + * * @var \Illuminate\Container\Container */ protected $container; /** * Controller reviser instance. - * + * * @var \Dingo\Api\Routing\ControllerReviser */ protected $controllerReviser; /** * Array of resolved container bindings. - * + * * @var array */ protected $bindings = []; /** * Array of binding mappings. - * + * * @var array */ protected $mappings = ['auth' => 'dingo.api.auth']; /** * Create a new authentication middleware instance. - * - * @param \Symfony\Component\HttpKernel\HttpKernelInterface $app - * @param \Illuminate\Container\Container $container + * + * @param \Symfony\Component\HttpKernel\HttpKernelInterface $app + * @param \Illuminate\Container\Container $container * @return void */ public function __construct(HttpKernelInterface $app, Container $container, ControllerReviser $controllerReviser = null) { $this->app = $app; $this->container = $container; - $this->controllerReviser = $controllerReviser ?: new ControllerReviser($container); + $this->controllerReviser = $controllerReviser ? : new ControllerReviser($container); } /** * Handle a given request and return the response. - * - * @param \Symfony\Component\HttpFoundation\Request $request - * @param int $type - * @param bool $catch + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param int $type + * @param bool $catch * @return \Symfony\Component\HttpFoundation\Response * @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException */ @@ -77,8 +78,7 @@ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQ // service providers and other container bindings. $this->container->boot(); - if ($request instanceof InternalRequest or $this->auth->user()) - { + if ($request instanceof InternalRequest or $this->auth->user()) { return $this->app->handle($request, $type, $catch); } @@ -87,19 +87,14 @@ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQ // If a collection exists for the request and we can match a route // from the request then we'll check to see if the route is // protected and, if it is, we'll attempt to authenticate. - if ($this->router->requestTargettingApi($request) and $collection = $this->router->getApiRouteCollectionFromRequest($request)) - { - try - { + if ($this->router->requestTargettingApi($request) and $collection = $this->router->getApiRouteCollectionFromRequest($request)) { + try { $route = $this->controllerReviser->revise($collection->match($request)); - if ($this->routeIsProtected($route)) - { + if ($this->routeIsProtected($route)) { $response = $this->authenticate($request, $route); } - } - catch (NotFoundHttpException $exception) - { + } catch (NotFoundHttpException $exception) { // If we catch a not found exception it's usually because the // API is operating without a prefix so a collection is found // but a route does not exist in that collection. We'll just @@ -108,25 +103,22 @@ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQ } - return $response ?: $this->app->handle($request, $type, $catch); + return $response ? : $this->app->handle($request, $type, $catch); } /** * Authenticate the request for the given route. - * - * @param \Symfony\Component\HttpFoundation\Request $request - * @param \Illuminate\Routing\Route $route + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param \Illuminate\Routing\Route $route * @return null|\Dingo\Api\Http\Response * @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException */ protected function authenticate(Request $request, Route $route) { - try - { + try { $this->auth->authenticate($request, $route); - } - catch (UnauthorizedHttpException $exception) - { + } catch (UnauthorizedHttpException $exception) { $response = $this->router->handleException($exception); list ($version, $format) = $this->router->parseAcceptHeader($request); @@ -137,8 +129,8 @@ protected function authenticate(Request $request, Route $route) /** * Determine if a route is protected. - * - * @param \Illuminate\Routing\Route $route + * + * @param \Illuminate\Routing\Route $route * @return bool */ protected function routeIsProtected(Route $route) @@ -150,16 +142,15 @@ protected function routeIsProtected(Route $route) /** * Dynamically handle binding calls on the container. - * - * @param string $binding + * + * @param string $binding * @return mixed */ public function __get($binding) { $binding = isset($this->mappings[$binding]) ? $this->mappings[$binding] : $binding; - if (isset($this->bindings[$binding])) - { + if (isset($this->bindings[$binding])) { return $this->bindings[$binding]; } diff --git a/src/Http/Middleware/RateLimit.php b/src/Http/Middleware/RateLimit.php index ea1758f42..da0216e68 100644 --- a/src/Http/Middleware/RateLimit.php +++ b/src/Http/Middleware/RateLimit.php @@ -6,25 +6,26 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\HttpKernelInterface; -class RateLimit implements HttpKernelInterface { +class RateLimit implements HttpKernelInterface +{ /** * The wrapped kernel implementation. - * + * * @var \Symfony\Component\HttpKernel\HttpKernelInterface */ protected $app; /** * Laravel application container. - * + * * @var \Illuminate\Container\Container */ protected $container; /** * Rate limiting config. - * + * * @var array */ protected $config = [ @@ -41,30 +42,30 @@ class RateLimit implements HttpKernelInterface { /** * Array of resolved container bindings. - * + * * @var array */ protected $bindings = []; /** * Array of binding mappings. - * + * * @var array */ protected $mappings = ['auth' => 'dingo.api.auth']; /** * Indicates if the request is authenticated. - * + * * @var bool */ protected $authenticatedRequest; /** * Create a new rate limit middleware instance. - * - * @param \Symfony\Component\HttpKernel\HttpKernelInterface $app - * @param \Illuminate\Container\Container $container + * + * @param \Symfony\Component\HttpKernel\HttpKernelInterface $app + * @param \Illuminate\Container\Container $container * @return void */ public function __construct(HttpKernelInterface $app, Container $container) @@ -75,10 +76,10 @@ public function __construct(HttpKernelInterface $app, Container $container) /** * Handle a given request and return the response. - * - * @param \Symfony\Component\HttpFoundation\Request $request - * @param int $type - * @param bool $catch + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param int $type + * @param bool $catch * @return \Symfony\Component\HttpFoundation\Response * @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException */ @@ -91,8 +92,7 @@ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQ // Internal requests as well as requests that are not targetting the // API will not be rate limited. We'll also be sure not to perform // any rate limiting if it has been disabled. - if ($request instanceof InternalRequest or ! $this->router->requestTargettingApi($request) or $this->rateLimitingDisabled()) - { + if ($request instanceof InternalRequest or !$this->router->requestTargettingApi($request) or $this->rateLimitingDisabled()) { return $this->app->handle($request, $type, $catch); } @@ -100,14 +100,11 @@ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQ $this->cache->add($this->config['keys']['reset'], time() + ($this->config['reset'] * 60), $this->config['reset']); $this->cache->increment($this->config['keys']['requests']); - if ($this->exceededRateLimit()) - { + if ($this->exceededRateLimit()) { list ($version, $format) = $this->router->parseAcceptHeader($request); $response = (new Response($this->config['exceeded'], 403))->morph($format); - } - else - { + } else { $response = $this->app->handle($request, $type, $catch); } @@ -116,16 +113,15 @@ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQ /** * Adjust the response headers and return the response. - * - * @param \Dingo\Api\Http\Response $response + * + * @param \Dingo\Api\Http\Response $response * @return \Dingo\Api\Http\Response */ protected function adjustResponseHeaders($response) { $requestsRemaining = $this->config['limit'] - $this->cache->get($this->config['keys']['requests']); - if ($requestsRemaining < 0) - { + if ($requestsRemaining < 0) { $requestsRemaining = 0; } @@ -138,7 +134,7 @@ protected function adjustResponseHeaders($response) /** * Determine if the client has exceeded their rate limit. - * + * * @return bool */ protected function exceededRateLimit() @@ -148,13 +144,12 @@ protected function exceededRateLimit() /** * Deteremine if the request is authenticated. - * + * * @return bool */ protected function isAuthenticatedRequest() { - if ( ! is_null($this->authenticatedRequest)) - { + if (!is_null($this->authenticatedRequest)) { return $this->authenticatedRequest; } @@ -163,21 +158,18 @@ protected function isAuthenticatedRequest() /** * Prepare the configuration for the request. - * - * @param \Illuminate\Http\Request $request + * + * @param \Illuminate\Http\Request $request * @return void */ protected function prepareConfig($request) { $this->config = array_merge($this->config, $this->container->make('config')->get('api::rate_limiting')); - if ($this->isAuthenticatedRequest()) - { + if ($this->isAuthenticatedRequest()) { $this->config = array_merge(['exceeded' => $this->config['exceeded']], $this->config['authenticated']); - } - else - { - $this->config = array_merge(['exceeded' => $this->config['exceeded']], $this->config['unauthenticated']); + } else { + $this->config = array_merge(['exceeded' => $this->config['exceeded']], $this->config['unauthenticated']); } $this->config['keys']['requests'] = sprintf('dingo:api:requests:%s', $request->getClientIp()); @@ -186,7 +178,7 @@ protected function prepareConfig($request) /** * Determine if rate limiting is disabled. - * + * * @return bool */ protected function rateLimitingDisabled() @@ -196,16 +188,15 @@ protected function rateLimitingDisabled() /** * Dynamically handle binding calls on the container. - * - * @param string $binding + * + * @param string $binding * @return mixed */ public function __get($binding) { $binding = isset($this->mappings[$binding]) ? $this->mappings[$binding] : $binding; - if (isset($this->bindings[$binding])) - { + if (isset($this->bindings[$binding])) { return $this->bindings[$binding]; } diff --git a/src/Http/Response.php b/src/Http/Response.php index 6bc0e1d1a..b76d61fc1 100644 --- a/src/Http/Response.php +++ b/src/Http/Response.php @@ -9,26 +9,27 @@ use Illuminate\Database\Eloquent\Model as EloquentModel; use Illuminate\Database\Eloquent\Collection as EloquentCollection; -class Response extends IlluminateResponse { +class Response extends IlluminateResponse +{ /** * Array of registered formatters. - * + * * @var array */ protected static $formatters = []; /** * Transformer factory instance. - * + * * @var \Dingo\Api\Transformer\Factory */ protected static $transformer; /** * Make an API response from an existing Illuminate response. - * - * @param \Illuminate\Http\Response $response + * + * @param \Illuminate\Http\Response $response * @return \Dingo\Api\Http\Response */ public static function makeFromExisting(IlluminateResponse $response) @@ -38,15 +39,14 @@ public static function makeFromExisting(IlluminateResponse $response) /** * Process the API response. - * + * * @return \Dingo\Api\Http\Response */ public function morph($format = 'json') { $response = $this->getOriginalContent(); - if (static::$transformer->transformableResponse($response)) - { + if (static::$transformer->transformableResponse($response)) { $response = static::$transformer->transformResponse($response); } @@ -54,34 +54,22 @@ public function morph($format = 'json') // First we'll attempt to format the response if it's either an Eloquent // model or an Eloquent collection. - if ($response instanceof EloquentModel) - { + if ($response instanceof EloquentModel) { $response = $formatter->formatEloquentModel($response); - } - elseif ($response instanceof EloquentCollection) - { + } elseif ($response instanceof EloquentCollection) { $response = $formatter->formatEloquentCollection($response); - } - else - { + } else { // Next we'll attempt to format the response if it's a string, // an array or an object implementing ArrayableInterface, // an object implementing JsonableInterface or an // unknown type. - if (is_string($response)) - { + if (is_string($response)) { $response = $formatter->formatString($response); - } - elseif (is_array($response) or $response instanceof ArrayableInterface) - { + } elseif (is_array($response) or $response instanceof ArrayableInterface) { $response = $formatter->formatArrayableInterface($response); - } - elseif ($response instanceof JsonableInterface) - { + } elseif ($response instanceof JsonableInterface) { $response = $formatter->formatJsonableInterface($response); - } - else - { + } else { $response = $formatter->formatUnknown($response); } } @@ -99,16 +87,15 @@ public function morph($format = 'json') /** * Get the formatter based on the requested format type. - * - * @param string $format + * + * @param string $format * @return \Dingo\Api\Http\Format\FormatInterface * @throws \RuntimeException */ public static function getFormatter($format) { - if ( ! isset(static::$formatters[$format])) - { - throw new RuntimeException('Response formatter "'.$format.'" has not been registered.'); + if (!isset(static::$formatters[$format])) { + throw new RuntimeException('Response formatter "' . $format . '" has not been registered.'); } return static::$formatters[$format]; @@ -116,8 +103,8 @@ public static function getFormatter($format) /** * Set the response formatters. - * - * @param array $formatters + * + * @param array $formatters * @return void */ public static function setFormatters(array $formatters) @@ -127,8 +114,8 @@ public static function setFormatters(array $formatters) /** * Set the transformer factory instance. - * - * @param \Dingo\Api\Transformer\Factory $transformer + * + * @param \Dingo\Api\Transformer\Factory $transformer * @return void */ public static function setTransformer(Factory $transformer) @@ -138,7 +125,7 @@ public static function setTransformer(Factory $transformer) /** * Get the transformer factory instance. - * + * * @return \Dingo\Api\Transformer\Factory */ public static function getTransformer() diff --git a/src/Http/ResponseFormat/JsonResponseFormat.php b/src/Http/ResponseFormat/JsonResponseFormat.php index 8e90e11fd..42f08ef58 100644 --- a/src/Http/ResponseFormat/JsonResponseFormat.php +++ b/src/Http/ResponseFormat/JsonResponseFormat.php @@ -2,12 +2,13 @@ use Illuminate\Support\Contracts\ArrayableInterface; -class JsonResponseFormat implements ResponseFormatInterface { +class JsonResponseFormat implements ResponseFormatInterface +{ /** * Format an Eloquent model. - * - * @param \Illuminate\Database\Eloquent\Model $model + * + * @param \Illuminate\Database\Eloquent\Model $model * @return string */ public function formatEloquentModel($model) @@ -19,14 +20,13 @@ public function formatEloquentModel($model) /** * Format an Eloquent collection. - * - * @param \Illuminate\Database\Eloquent\Collection $collection + * + * @param \Illuminate\Database\Eloquent\Collection $collection * @return string */ public function formatEloquentCollection($collection) { - if ($collection->isEmpty()) - { + if ($collection->isEmpty()) { return $this->encode([]); } @@ -37,8 +37,8 @@ public function formatEloquentCollection($collection) /** * Format a string. - * - * @param string $string + * + * @param string $string * @return string */ public function formatString($string) @@ -48,16 +48,15 @@ public function formatString($string) /** * Format an array or instance implementing ArrayableInterface. - * - * @param \Illuminate\Support\Contracts\ArrayableInterface $response + * + * @param \Illuminate\Support\Contracts\ArrayableInterface $response * @return string */ public function formatArrayableInterface($response) { $response = $this->morphToArray($response); - array_walk_recursive($response, function(&$value) - { + array_walk_recursive($response, function (&$value) { $value = $this->morphToArray($value); }); @@ -66,8 +65,8 @@ public function formatArrayableInterface($response) /** * Format an instance implementing JsonableInterface. - * - * @param \Illuminate\Support\Contracts\JsonableInterface $response + * + * @param \Illuminate\Support\Contracts\JsonableInterface $response * @return string */ public function formatJsonableInterface($response) @@ -77,8 +76,8 @@ public function formatJsonableInterface($response) /** * Format an unknown type. - * - * @param mixed $response + * + * @param mixed $response * @return string */ public function formatUnknown($response) @@ -88,7 +87,7 @@ public function formatUnknown($response) /** * Get the response content type. - * + * * @return string */ public function getContentType() @@ -98,7 +97,7 @@ public function getContentType() /** * Morph a value to an array. - * + * * @param array|\Illuminate\Support\Contracts\ArrayableInterface * @return array */ @@ -109,8 +108,8 @@ protected function morphToArray($value) /** * Encode the content to its JSON representation. - * - * @param string $content + * + * @param string $content * @return string */ protected function encode($content) diff --git a/src/Http/ResponseFormat/ResponseFormatInterface.php b/src/Http/ResponseFormat/ResponseFormatInterface.php index 1caea753d..7e46f8455 100644 --- a/src/Http/ResponseFormat/ResponseFormatInterface.php +++ b/src/Http/ResponseFormat/ResponseFormatInterface.php @@ -1,60 +1,61 @@ matchesCollectionVersion($request)) - { - if ($this->matchDomain($request)) - { + if ($this->matchesCollectionVersion($request)) { + if ($this->matchDomain($request)) { return true; - } - elseif ($this->matchPrefix($request)) - { + } elseif ($this->matchPrefix($request)) { return true; - } - elseif ( ! $this->option('prefix') and ! $this->option('domain')) - { + } elseif (!$this->option('prefix') and !$this->option('domain')) { return true; } } @@ -75,14 +70,13 @@ public function matchesRequest(Request $request) /** * Determine if the requested version matches the collection version. - * - * @param \Illuminate\Http\Request $request + * + * @param \Illuminate\Http\Request $request * @return bool */ protected function matchesCollectionVersion($request) { - if (preg_match('#application/vnd\.\w+.(v[\d\.]+)\+\w+#', $request->header('accept'), $matches)) - { + if (preg_match('#application/vnd\.\w+.(v[\d\.]+)\+\w+#', $request->header('accept'), $matches)) { list ($accept, $version) = $matches; return $version == $this->version; @@ -94,7 +88,7 @@ protected function matchesCollectionVersion($request) /** * Matches domain if is set on route group. * - * @param \Illuminate\Http\Request $request + * @param \Illuminate\Http\Request $request * @return bool */ protected function matchDomain($request) @@ -105,13 +99,12 @@ protected function matchDomain($request) /** * Matches prefix if is set in route group. * - * @param \Illuminate\Http\Request $request + * @param \Illuminate\Http\Request $request * @return bool */ protected function matchPrefix($request) { - if ( ! $prefix = $this->option('prefix')) - { + if (!$prefix = $this->option('prefix')) { return false; } @@ -124,8 +117,8 @@ protected function matchPrefix($request) /** * Explode array on slash and remove empty values. - * - * @param array $array + * + * @param array $array * @return array */ protected function filterAndExplode($array) diff --git a/src/Routing/Controller.php b/src/Routing/Controller.php index 78299d91e..b9bb149a0 100644 --- a/src/Routing/Controller.php +++ b/src/Routing/Controller.php @@ -4,48 +4,49 @@ use Dingo\Api\Auth\Shield; use Illuminate\Routing\Controller as IlluminateController; -abstract class Controller extends IlluminateController { +abstract class Controller extends IlluminateController +{ /** * API dispatcher instance. - * + * * @var \Dingo\Api\Dispatcher */ protected $api; /** * API authentication shield instance. - * + * * @var \Dingo\Api\Auth\Shield */ protected $auth; /** * Array of unprotected controller methods. - * + * * @var array */ protected $unprotected = []; /** * Array of protected controller methods. - * + * * @var array */ protected $protected = []; /** * Array of controller method scopes. - * + * * @var array */ protected $scopedMethods = []; /** * Create a new controller instance. - * + * * @param \Dingo\Api\Dispatcher $api - * @param \Dingo\Api\Auth\Shield $auth + * @param \Dingo\Api\Auth\Shield $auth * @return void */ public function __construct(Dispatcher $api, Shield $auth) @@ -56,22 +57,18 @@ public function __construct(Dispatcher $api, Shield $auth) /** * Set the scopes for all or a subset of methods. - * - * @param string|array $scopes - * @param string|array $methods + * + * @param string|array $scopes + * @param string|array $methods * @return \Dingo\Api\Routing\Controller */ protected function scope($scopes, $methods = null) { - if (is_null($methods)) - { - $this->scopedMethods['*'] = (array) $scopes; - } - else - { - foreach ((array) $methods as $method) - { - $this->scopedMethods[$method] = (array) $scopes; + if (is_null($methods)) { + $this->scopedMethods['*'] = (array)$scopes; + } else { + foreach ((array)$methods as $method) { + $this->scopedMethods[$method] = (array)$scopes; } } @@ -80,8 +77,8 @@ protected function scope($scopes, $methods = null) /** * Unprotect controller methods. - * - * @param array $methods + * + * @param array $methods * @return \Dingo\Api\Routing\Controller */ protected function unprotect($methods) @@ -93,8 +90,8 @@ protected function unprotect($methods) /** * Protect controller methods. - * - * @param array $methods + * + * @param array $methods * @return \Dingo\Api\Routing\Controller */ protected function protect($methods) @@ -106,7 +103,7 @@ protected function protect($methods) /** * Get the protected controller methods. - * + * * @return array */ public function getProtectedMethods() @@ -116,7 +113,7 @@ public function getProtectedMethods() /** * Get the unprotected controller methods. - * + * * @return array */ public function getUnprotectedMethods() @@ -126,7 +123,7 @@ public function getUnprotectedMethods() /** * Get the scoped methods. - * + * * @return array */ public function getScopedMethods() diff --git a/src/Routing/ControllerInspector.php b/src/Routing/ControllerInspector.php index fbb6a1807..902c32494 100644 --- a/src/Routing/ControllerInspector.php +++ b/src/Routing/ControllerInspector.php @@ -3,19 +3,19 @@ use ReflectionMethod; use Illuminate\Routing\ControllerInspector as IlluminateControllerInspector; -class ControllerInspector extends IlluminateControllerInspector { +class ControllerInspector extends IlluminateControllerInspector +{ /** * Determine if the given controller method is routable. * - * @param ReflectionMethod $method - * @param string $controller + * @param ReflectionMethod $method + * @param string $controller * @return bool */ public function isRoutable(ReflectionMethod $method, $controller) { - if ($method->class == 'Dingo\Api\Routing\Controller') - { + if ($method->class == 'Dingo\Api\Routing\Controller') { return false; } diff --git a/src/Routing/ControllerReviser.php b/src/Routing/ControllerReviser.php index bf9f95b72..dd4ca4c56 100644 --- a/src/Routing/ControllerReviser.php +++ b/src/Routing/ControllerReviser.php @@ -3,41 +3,40 @@ use Illuminate\Routing\Route; use Illuminate\Container\Container; -class ControllerReviser { +class ControllerReviser +{ /** * Illuminate application container. - * + * * @var \Illuminate\Container\Container */ protected $container; /** * Create a new controller reviser instance. - * - * @param \Illuminate\Container\Container $container + * + * @param \Illuminate\Container\Container $container */ public function __construct(Container $container = null) { - $this->container = $container ?: new Container; + $this->container = $container ? : new Container; } /** * Revise a controller route by updating the protection and scopes. - * - * @param \Illuminate\Routing\Route $route + * + * @param \Illuminate\Routing\Route $route * @return \Illuminate\Routing\Route */ public function revise(Route $route) { - if ($this->routingToController($route)) - { + if ($this->routingToController($route)) { list ($class, $method) = explode('@', $route->getActionName()); $controller = $this->resolveController($class); - if ($controller instanceof Controller) - { + if ($controller instanceof Controller) { $action = $route->getAction(); $action = $this->reviseProtectedMethods($action, $controller, $method); @@ -53,7 +52,7 @@ public function revise(Route $route) /** * Determine if the route is routing to a controller. * - * @param Illuminate\Routing\Route $action + * @param Illuminate\Routing\Route $action * @return bool */ protected function routingToController(Route $route) @@ -64,30 +63,27 @@ protected function routingToController(Route $route) /** * Revise the scopes of a controller method. Scopes defined on the * controller are merged with those in the route definition. - * - * @param \Illuminate\Routing\Route $route - * @param \Dingo\Api\Routing\Controller $controller - * @param string $method + * + * @param \Illuminate\Routing\Route $route + * @param \Dingo\Api\Routing\Controller $controller + * @param string $method * @return \Illuminate\Routing\Route */ protected function reviseScopedMethods($action, $controller, $method) { - if ( ! isset($action['scopes'])) - { + if (!isset($action['scopes'])) { $action['scopes'] = []; } - $action['scopes'] = (array) $action['scopes']; + $action['scopes'] = (array)$action['scopes']; $scopedMethods = $controller->getScopedMethods(); - if (isset($scopedMethods['*'])) - { + if (isset($scopedMethods['*'])) { $action['scopes'] = array_merge($action['scopes'], $scopedMethods['*']); } - if (isset($scopedMethods[$method])) - { + if (isset($scopedMethods[$method])) { $action['scopes'] = array_merge($action['scopes'], $scopedMethods[$method]); } @@ -96,20 +92,17 @@ protected function reviseScopedMethods($action, $controller, $method) /** * Revise the protected state of a controller method. - * - * @param \Illuminate\Routing\Route $route - * @param \Dingo\Api\Routing\Controller $controller - * @param string $method + * + * @param \Illuminate\Routing\Route $route + * @param \Dingo\Api\Routing\Controller $controller + * @param string $method * @return \Illuminate\Routing\Route */ protected function reviseProtectedMethods($action, $controller, $method) { - if (in_array($method, $controller->getProtectedMethods())) - { + if (in_array($method, $controller->getProtectedMethods())) { $action['protected'] = true; - } - elseif (in_array($method, $controller->getUnprotectedMethods())) - { + } elseif (in_array($method, $controller->getUnprotectedMethods())) { $action['protected'] = false; } @@ -118,16 +111,15 @@ protected function reviseProtectedMethods($action, $controller, $method) /** * Resolve a controller from the container. - * - * @param string $class + * + * @param string $class * @return \Illuminate\Routing\Controller */ protected function resolveController($class) { $controller = $this->container->make($class); - if ( ! $this->container->bound($class)) - { + if (!$this->container->bound($class)) { $this->container->instance($class, $controller); } diff --git a/src/Routing/Router.php b/src/Routing/Router.php index fd7515779..60f74adcf 100644 --- a/src/Routing/Router.php +++ b/src/Routing/Router.php @@ -12,129 +12,125 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; -class Router extends IlluminateRouter { +class Router extends IlluminateRouter +{ /** * The API route collections. - * + * * @param array */ protected $api = []; /** * The default API version. - * + * * @var string */ protected $defaultVersion = 'v1'; /** * The default API prefix. - * + * * @var string */ protected $defaultPrefix; /** * The default API domain. - * + * * @var string */ protected $defaultDomain; /** * The default API format. - * + * * @var string */ protected $defaultFormat = 'json'; /** * The API vendor. - * + * * @var string */ protected $vendor; /** * Requested API version. - * + * * @var string */ protected $requestedVersion; /** * Requested format. - * + * * @var string */ protected $requestedFormat; /** * Exception handler instance. - * + * * @var \Dingo\Api\ExceptionHandler */ protected $exceptionHandler; /** * Controller reviser instance. - * + * * @var \Dingo\Api\Routing\ControllerReviser */ protected $reviser; /** * Array of requests targetting the API. - * + * * @var array */ protected $requestsTargettingApi = []; /** * Register an API group. - * - * @param array $options - * @param callable $callback + * + * @param array $options + * @param callable $callback * @return void */ public function api($options, callable $callback) { - if ( ! isset($options['version'])) - { + if (!isset($options['version'])) { throw new BadMethodCallException('Unable to register API without an API version.'); } - $options['version'] = (array) $options['version']; + $options['version'] = (array)$options['version']; $options[] = 'api'; - if ( ! isset($options['prefix'])) - { + if (!isset($options['prefix'])) { $options['prefix'] = $this->defaultPrefix; } - if ( ! isset($options['domain'])) - { + if (!isset($options['domain'])) { $options['domain'] = $this->defaultDomain; } - foreach ($options['version'] as $version) - { - if ( ! isset($this->api[$version])) - { + foreach ($options['version'] as $version) { + if (!isset($this->api[$version])) { $this->api[$version] = new ApiRouteCollection($version, array_except($options, 'version')); } } - + $this->group($options, $callback); } /** * Dispatch the request to the application and return either a regular response * or an API response. - * - * @param \Illuminate\Http\Request $request + * + * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response|\Dingo\Api\Http\Response */ public function dispatch(Request $request) @@ -143,33 +139,27 @@ public function dispatch(Request $request) Response::getTransformer()->setRequest($request); - try - { + try { $response = parent::dispatch($request); - } - catch (HttpExceptionInterface $exception) - { + } catch (HttpExceptionInterface $exception) { // If an exception is caught and we are currently routing an API request then // we'll handle this exception by building a new response from it. This // allows the API to gracefully handle its own exceptions. - if ($this->requestTargettingApi($request) and ! $request instanceof InternalRequest) - { + if ($this->requestTargettingApi($request) and !$request instanceof InternalRequest) { $response = $this->handleException($exception); } // If the request was an internal request then we will rethrow the exception // so that developers can easily catch them and adjust ther esponse // themselves. - else - { + else { throw $exception; } } $this->container->forgetInstance('Illuminate\Http\Request'); - if ($this->requestTargettingApi($request)) - { + if ($this->requestTargettingApi($request)) { $response = Response::makeFromExisting($response)->morph($this->requestedFormat); } @@ -178,35 +168,31 @@ public function dispatch(Request $request) /** * Handle exception thrown when dispatching a request. - * - * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception + * + * @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception * @return \Dingo\Api\Http\Response */ public function handleException(HttpExceptionInterface $exception) { // If the exception handler will handle the given exception then we'll fire // the callback registered to the handler and return the response. - if ($this->exceptionHandler->willHandle($exception)) - { + if ($this->exceptionHandler->willHandle($exception)) { $response = $this->exceptionHandler->handle($exception); return Response::makeFromExisting($response); } - if ( ! $message = $exception->getMessage()) - { + if (!$message = $exception->getMessage()) { $message = sprintf('%d %s', $exception->getStatusCode(), Response::$statusTexts[$exception->getStatusCode()]); } $response = ['message' => $message]; - if ($exception instanceof ResourceException and $exception->hasErrors()) - { + if ($exception instanceof ResourceException and $exception->hasErrors()) { $response['errors'] = $exception->getErrors(); } - if ($code = $exception->getCode()) - { + if ($code = $exception->getCode()) { $response['code'] = $code; } @@ -215,18 +201,17 @@ public function handleException(HttpExceptionInterface $exception) /** * Add a new route to either the routers collection or an API collection. - * - * @param array|string $methods - * @param string $uri - * @param callable|array|string $action + * + * @param array|string $methods + * @param string $uri + * @param callable|array|string $action * @return \Illuminate\Routing\Route */ protected function addRoute($methods, $uri, $action) { $route = $this->createRoute($methods, $uri, $action); - if ($this->routeTargettingApi($route)) - { + if ($this->routeTargettingApi($route)) { return $this->addApiRoute($route); } @@ -235,8 +220,8 @@ protected function addRoute($methods, $uri, $action) /** * Add a new route to an API collection. - * - * @param \Illuminate\Routing\Route $route + * + * @param \Illuminate\Routing\Route $route * @return \Illuminate\Routing\Route */ protected function addApiRoute($route) @@ -246,8 +231,7 @@ protected function addApiRoute($route) // that protection status from the array after the merge. $action = $route->getAction(); - if (count($this->groupStack) > 0 and isset($action['protected'])) - { + if (count($this->groupStack) > 0 and isset($action['protected'])) { $action['protected'] = is_array($action['protected']) ? last($action['protected']) : $action['protected']; $route->setAction($action); @@ -255,8 +239,7 @@ protected function addApiRoute($route) $versions = array_get(last($this->groupStack), 'version', []); - foreach ($versions as $version) - { + foreach ($versions as $version) { $this->getApiRouteCollection($version)->add($route); } @@ -265,14 +248,13 @@ protected function addApiRoute($route) /** * Find a route either from the routers collection or the API collection. - * - * @param \Illuminate\Http\Request $request + * + * @param \Illuminate\Http\Request $request * @return \Illuminate\Routing\Route */ protected function findRoute($request) { - if ($this->requestTargettingApi($request)) - { + if ($this->requestTargettingApi($request)) { list ($this->requestedVersion, $this->requestedFormat) = $this->parseAcceptHeader($request); $this->current = $route = $this->getApiRouteCollection($this->requestedVersion)->match($request); @@ -285,34 +267,28 @@ protected function findRoute($request) /** * Determine if the current request is targetting an API. - * - * @param \Illuminate\Http\Request $request + * + * @param \Illuminate\Http\Request $request * @return bool */ public function requestTargettingApi($request = null) { - $request = $request ?: $this->currentRequest; + $request = $request ? : $this->currentRequest; - if (empty($this->api)) - { + if (empty($this->api)) { return false; } - if (isset($this->requestsTargettingApi[$key = sha1($request)])) - { + if (isset($this->requestsTargettingApi[$key = sha1($request)])) { return $this->requestsTargettingApi[$key]; } - if ($collection = $this->getApiRouteCollectionFromRequest($request)) - { - try - { + if ($collection = $this->getApiRouteCollectionFromRequest($request)) { + try { $collection->match($request); return $this->requestsTargettingApi[$key] = true; - } - catch (NotFoundHttpException $exception) - { + } catch (NotFoundHttpException $exception) { // No matching route so the request is not targetting API. } } @@ -322,14 +298,13 @@ public function requestTargettingApi($request = null) /** * Parse a requests accept header. - * - * @param \Illuminate\Http\Request $request + * + * @param \Illuminate\Http\Request $request * @return array */ public function parseAcceptHeader($request) { - if (preg_match('#application/vnd\.'.$this->vendor.'.(v[\d\.]+)\+(\w+)#', $request->header('accept'), $matches)) - { + if (preg_match('#application/vnd\.' . $this->vendor . '.(v[\d\.]+)\+(\w+)#', $request->header('accept'), $matches)) { return array_slice($matches, 1); } @@ -338,22 +313,20 @@ public function parseAcceptHeader($request) /** * Get a matching API route collection from the request. - * - * @param \Illuminate\Http\Request $request + * + * @param \Illuminate\Http\Request $request * @return null|\Dingo\Api\Routing\ApiRouteCollection */ public function getApiRouteCollectionFromRequest(Request $request) { - $collection = array_first($this->api, function($key, $collection) use ($request) - { + $collection = array_first($this->api, function ($key, $collection) use ($request) { return $collection->matchesRequest($request); }); // If we don't initially find a collection then we'll grab the default // version collection instead. This is a sort of graceful fallback // and allows viewing of the latest API version in the browser. - if ( ! $collection) - { + if (!$collection) { return $this->getApiRouteCollection($this->defaultVersion); } @@ -362,15 +335,14 @@ public function getApiRouteCollectionFromRequest(Request $request) /** * Get an API route collection for a given version. - * - * @param string $version + * + * @param string $version * @return \Dingo\Api\Routing\ApiRouteCollection */ public function getApiRouteCollection($version) { - if ( ! isset($this->api[$version])) - { - throw new RuntimeException('There is no API route collection for the version "'.$version.'".'); + if (!isset($this->api[$version])) { + throw new RuntimeException('There is no API route collection for the version "' . $version . '".'); } return $this->api[$version]; @@ -378,7 +350,7 @@ public function getApiRouteCollection($version) /** * Determine if a route is targetting the API. - * + * * @param \Illuminate\Routing\Route * @return bool */ @@ -391,7 +363,7 @@ public function routeTargettingApi($route) /** * Set the exception handler instance. - * + * * @param \Dingo\Api\ExceptionHandler * @return void */ @@ -402,7 +374,7 @@ public function setExceptionHandler(ExceptionHandler $exceptionHandler) /** * Get the exception handler instance. - * + * * @return \Dingo\Api\ExceptionHandler */ public function getExceptionHandler() @@ -412,8 +384,8 @@ public function getExceptionHandler() /** * Set the default API version. - * - * @param string $defaultVersion + * + * @param string $defaultVersion * @return void */ public function setDefaultVersion($defaultVersion) @@ -423,7 +395,7 @@ public function setDefaultVersion($defaultVersion) /** * Get the default API version. - * + * * @return string */ public function getDefaultVersion() @@ -433,8 +405,8 @@ public function getDefaultVersion() /** * Set the default API prefix. - * - * @param string $defaultPrefix + * + * @param string $defaultPrefix * @return void */ public function setDefaultPrefix($defaultPrefix) @@ -444,7 +416,7 @@ public function setDefaultPrefix($defaultPrefix) /** * Get the default API prefix. - * + * * @return string */ public function getDefaultPrefix() @@ -454,8 +426,8 @@ public function getDefaultPrefix() /** * Set the default API domain. - * - * @param string $defaultDomain + * + * @param string $defaultDomain * @return void */ public function setDefaultDomain($defaultDomain) @@ -465,7 +437,7 @@ public function setDefaultDomain($defaultDomain) /** * Get the default API domain. - * + * * @return string */ public function getDefaultDomain() @@ -475,8 +447,8 @@ public function getDefaultDomain() /** * Set the API vendor. - * - * @param string $vendor + * + * @param string $vendor * @return void */ public function setVendor($vendor) @@ -486,7 +458,7 @@ public function setVendor($vendor) /** * Get the API vendor. - * + * * @return string */ public function getVendor() @@ -496,8 +468,8 @@ public function getVendor() /** * Set the default API format. - * - * @param string $defaultformat + * + * @param string $defaultformat * @return void */ public function setDefaultFormat($defaultFormat) @@ -507,7 +479,7 @@ public function setDefaultFormat($defaultFormat) /** * Get the default API format. - * + * * @return string */ public function getDefaultFormat() @@ -517,7 +489,7 @@ public function getDefaultFormat() /** * Get the requested version. - * + * * @return string */ public function getRequestedVersion() @@ -527,7 +499,7 @@ public function getRequestedVersion() /** * Get the requested format. - * + * * @return string */ public function getRequestedFormat() @@ -542,13 +514,13 @@ public function getRequestedFormat() */ public function getInspector() { - return $this->inspector ?: $this->inspector = new ControllerInspector; + return $this->inspector ? : $this->inspector = new ControllerInspector; } /** * Set the controller reviser instance. - * - * @param \Dingo\Api\Routing\ControllerReviser $reviser + * + * @param \Dingo\Api\Routing\ControllerReviser $reviser * @return void */ public function setControllerReviser(ControllerReviser $reviser) @@ -558,18 +530,18 @@ public function setControllerReviser(ControllerReviser $reviser) /** * Get the controller reviser instance. - * + * * @return \Dingo\Api\Routing\ControllerReviser */ public function getControllerReviser() { - return $this->reviser ?: new ControllerReviser($this->container); + return $this->reviser ? : new ControllerReviser($this->container); } /** * Set the current request. - * - * @param \Illuminate\Http\Request $request + * + * @param \Illuminate\Http\Request $request * @return void */ public function setCurrentRequest(Request $request) @@ -579,8 +551,8 @@ public function setCurrentRequest(Request $request) /** * Set the current route. - * - * @param \Illuminate\Routing\Route $route + * + * @param \Illuminate\Routing\Route $route * @return void */ public function setCurrentRoute(Route $route) diff --git a/src/Transformer/Factory.php b/src/Transformer/Factory.php index 4b38a4b17..942db68fc 100644 --- a/src/Transformer/Factory.php +++ b/src/Transformer/Factory.php @@ -6,33 +6,34 @@ use Illuminate\Container\Container; use Illuminate\Pagination\Paginator; -class Factory { +class Factory +{ /** * Illuminate container instance. - * + * * @var \Illuminate\Container\Container */ protected $container; /** * Transformer instance. - * + * * @var \Dingo\Api\Transformer\Transformer */ protected $transformer; /** * Array of registered transformer bindings. - * + * * @var array */ protected $bindings = []; /** * Create a new transformer factory instance. - * - * @param \Illuminate\Container\Container $container + * + * @param \Illuminate\Container\Container $container * @return void */ public function __construct(Container $container) @@ -42,9 +43,9 @@ public function __construct(Container $container) /** * Register a transformer binding resolver for a class. - * - * @param string $class - * @param string|callable|object $resolver + * + * @param string $class + * @param string|callable|object $resolver * @return \Dingo\Api\Transformer\Factory */ public function transform($class, $resolver) @@ -56,8 +57,8 @@ public function transform($class, $resolver) /** * Transform a response with a registered transformer. - * - * @param string|object $response + * + * @param string|object $response * @return mixed */ public function transformResponse($response) @@ -69,70 +70,64 @@ public function transformResponse($response) /** * Determine if a response is transformable. - * - * @param mixed $response + * + * @param mixed $response * @return bool */ public function transformableResponse($response) { return $this->transformableType($response) and ($this->hasBinding($response) or $this->boundByContract($response)); } - + /** * Deteremine if a value is of a transformable type. - * - * @param mixed $value + * + * @param mixed $value * @return bool */ public function transformableType($value) - { + { return is_object($value) or is_string($value); } /** * Resolve a transfomer binding instance. - * - * @param string|callable|object $resolver + * + * @param string|callable|object $resolver * @return mixed */ protected function resolveTransformerBinding($resolver) { - if (is_string($resolver)) - { + if (is_string($resolver)) { return $this->container->make($resolver); - } - elseif (is_callable($resolver)) - { + } elseif (is_callable($resolver)) { return call_user_func($resolver, $this->container); } - + return $resolver; } /** * Get a registered transformer binding. - * - * @param string|object $class + * + * @param string|object $class * @return string|callable|object * @throws \RuntimeException */ protected function getBinding($class) { - if ($this->isCollection($class)) - { + if ($this->isCollection($class)) { return $this->getBindingFromCollection($class); } - if ($this->boundByContract($class)) - { + if ($this->boundByContract($class)) { return $class->getTransformer(); } $class = is_object($class) ? get_class($class) : $class; - if ( ! $this->hasBinding($class)) - { - throw new RuntimeException('Unable to find bound transformer for "'.$class.'" class.'); + if (!$this->hasBinding($class)) { + throw new RuntimeException('Unable to find bound transformer for "' . $class . '" class.'); } return $this->bindings[$class]; @@ -140,8 +135,8 @@ protected function getBinding($class) /** * Get a registered transformer binding from a collection of items. - * - * @param \Illuminate\Support\Collection $collection + * + * @param \Illuminate\Support\Collection $collection * @return null|string|callable */ protected function getBindingFromCollection($collection) @@ -151,14 +146,13 @@ protected function getBindingFromCollection($collection) /** * Determine if a class has a transformer binding. - * - * @param string|object $class + * + * @param string|object $class * @return bool */ protected function hasBinding($class) { - if ($this->isCollection($class)) - { + if ($this->isCollection($class)) { $class = $class->first(); } @@ -169,14 +163,13 @@ protected function hasBinding($class) /** * Determine if the class is bound by the transformable contract. - * - * @param string|object $class + * + * @param string|object $class * @return bool */ protected function boundByContract($class) { - if ($this->isCollection($class)) - { + if ($this->isCollection($class)) { $class = $class->first(); } @@ -185,8 +178,8 @@ protected function boundByContract($class) /** * Determine if the instance is a collection. - * - * @param object $instance + * + * @param object $instance * @return bool */ protected function isCollection($instance) @@ -196,7 +189,7 @@ protected function isCollection($instance) /** * Get the array of registered transformer bindings. - * + * * @return array */ public function getTransformerBindings() @@ -206,8 +199,8 @@ public function getTransformerBindings() /** * Set the transformer instance. - * - * @param \Dingo\Api\Transformer\Transformer $transformer + * + * @param \Dingo\Api\Transformer\Transformer $transformer * @return \Dingo\Api\Transformer\Factory */ public function setTransformer(Transformer $transformer) @@ -219,14 +212,13 @@ public function setTransformer(Transformer $transformer) /** * Set the request instance on the transformer. - * - * @param \Illuminate\Http\Request $request + * + * @param \Illuminate\Http\Request $request * @return void */ public function setRequest(Request $request) { - if ( ! $this->transformer) - { + if (!$this->transformer) { throw new RuntimeException('Request cannot be set when no transformer has been registered.'); } diff --git a/src/Transformer/FractalTransformer.php b/src/Transformer/FractalTransformer.php index 0469f020b..c760c8270 100644 --- a/src/Transformer/FractalTransformer.php +++ b/src/Transformer/FractalTransformer.php @@ -7,36 +7,37 @@ use Illuminate\Pagination\Paginator as IlluminatePaginator; use League\Fractal\Resource\Collection as FractalCollection; -class FractalTransformer extends Transformer { +class FractalTransformer extends Transformer +{ /** * Fractal manager instance. - * + * * @var \League\Fractal\Manager */ protected $fractal; /** * The include query string key. - * + * * @var string */ protected $includeKey; /** * The include separator. - * + * * @var string */ protected $includeSeparator; /** * Create a new fractal transformer instance. - * + * * @param \League\Fractal\Manager $fractal - * @param \Illuminate\Http\Request $request - * @param string $includeKey - * @param string $includeSeparator + * @param \Illuminate\Http\Request $request + * @param string $includeKey + * @param string $includeSeparator * @return void */ public function __construct(Fractal $fractal, $includeKey = 'include', $includeSeparator = ',') @@ -48,8 +49,8 @@ public function __construct(Fractal $fractal, $includeKey = 'include', $includeS /** * Transform a response with a registered transformer. - * - * @param string|object $response + * + * @param string|object $response * @return array */ public function transformResponse($response, $transformer) @@ -61,8 +62,7 @@ public function transformResponse($response, $transformer) // If the response is a paginator then we'll create a new paginator // adapter for Laravel and set the paginator instance on our // collection resource. - if ($response instanceof IlluminatePaginator) - { + if ($response instanceof IlluminatePaginator) { $paginator = new IlluminatePaginatorAdapter($response); $resource->setPaginator($paginator); @@ -73,24 +73,23 @@ public function transformResponse($response, $transformer) /** * Create a Fractal resource instance. - * - * @param mixed $response + * + * @param mixed $response * @param \League\Fractal\TransformerAbstract * @return \League\Fractal\Resource\Item|\League|Fractal\Resource\Collection */ protected function createResource($response, $transformer) { - if ($response instanceof IlluminatePaginator or $response instanceof IlluminateCollection) - { + if ($response instanceof IlluminatePaginator or $response instanceof IlluminateCollection) { return new FractalCollection($response, $transformer); } - + return new FractalItem($response, $transformer); } /** * Set the requested scopes. - * + * * @return void */ protected function setRequestedScopes() diff --git a/src/Transformer/TransformableInterface.php b/src/Transformer/TransformableInterface.php index 78a51caa8..053e89342 100644 --- a/src/Transformer/TransformableInterface.php +++ b/src/Transformer/TransformableInterface.php @@ -1,10 +1,11 @@ null, + /* + |-------------------------------------------------------------------------- + | Auth Class + |-------------------------------------------------------------------------- + | + | The auth method used, ie: auth or sentry + | + */ + 'auth_provider' => 'sentry', // auth, sentry + + /* + |-------------------------------------------------------------------------- + | Auth Drivers + |-------------------------------------------------------------------------- + | + | The auth driver used, ie: auth or sentry + | + */ + 'auth_drivers' => array( + 'auth' => '\Dingo\Api\Auth\Shield', + 'sentry' => '\Dingo\Api\Auth\SentryShield', + ), + /* |-------------------------------------------------------------------------- | Authentication Providers @@ -62,9 +86,14 @@ */ 'auth' => [ - 'basic' => function($app) - { + 'basic' => function ($app) { return new Dingo\Api\Auth\BasicProvider($app['auth']); + }, + 'sentry' => function ($app) { + return new \Dingo\Api\Auth\SentryOAuthProvider($app['oauth2.resource-server'], $app['sentry']); + }, + 'logged_in_user' => function ($app) { + return new \Dingo\Api\Auth\SentryProvider($app['sentry']); } ], @@ -93,7 +122,7 @@ 'unauthenticated' => [ 'limit' => 0, - 'reset' => 60 + 'reset' => 360 ], 'exceeded' => 'API rate limit has been exceeded.' @@ -113,8 +142,7 @@ | */ - 'transformer' => function($app) - { + 'transformer' => function ($app) { $fractal = new League\Fractal\Manager; return new Dingo\Api\Transformer\FractalTransformer($fractal); @@ -136,7 +164,7 @@ 'formats' => [ 'json' => new Dingo\Api\Http\ResponseFormat\JsonResponseFormat - + ] ]; diff --git a/tests/AuthAuthorizationProviderTest.php b/tests/AuthAuthorizationProviderTest.php index b10348a11..e8306e9cd 100644 --- a/tests/AuthAuthorizationProviderTest.php +++ b/tests/AuthAuthorizationProviderTest.php @@ -1,6 +1,7 @@ headers->set('authorization', 'Basic foo'); - + $provider = new BasicProvider($this->auth); $this->auth->shouldReceive('onceBasic')->once()->with('email')->andReturn(m::mock(['getStatusCode' => 200])); - $this->auth->shouldReceive('user')->once()->andReturn((object) ['id' => 1]); + $this->auth->shouldReceive('user')->once()->andReturn((object)['id' => 1]); $this->assertEquals(1, $provider->authenticate($request, m::mock('Illuminate\Routing\Route'))); } @@ -64,7 +65,7 @@ public function testAuthenticatingWithCustomIdentifierSucceedsAndReturnsUserId() $provider = new BasicProvider($this->auth, 'username'); $this->auth->shouldReceive('onceBasic')->once()->with('username')->andReturn(m::mock(['getStatusCode' => 200])); - $this->auth->shouldReceive('user')->once()->andReturn((object) ['id' => 1]); + $this->auth->shouldReceive('user')->once()->andReturn((object)['id' => 1]); $this->assertEquals(1, $provider->authenticate($request, m::mock('Illuminate\Routing\Route'))); } diff --git a/tests/AuthDingoOAuth2ProviderTest.php b/tests/AuthDingoOAuth2ProviderTest.php index 70469fc3b..1345c18a1 100644 --- a/tests/AuthDingoOAuth2ProviderTest.php +++ b/tests/AuthDingoOAuth2ProviderTest.php @@ -6,7 +6,8 @@ use Dingo\Api\Auth\DingoOAuth2Provider; use Dingo\OAuth2\Exception\InvalidTokenException; -class AuthDingoOAuth2ProviderTest extends PHPUnit_Framework_TestCase { +class AuthDingoOAuth2ProviderTest extends PHPUnit_Framework_TestCase +{ public function tearDown() diff --git a/tests/AuthLeagueOAuth2ProviderTest.php b/tests/AuthLeagueOAuth2ProviderTest.php index c73517202..0f2e19282 100644 --- a/tests/AuthLeagueOAuth2ProviderTest.php +++ b/tests/AuthLeagueOAuth2ProviderTest.php @@ -6,7 +6,8 @@ use Dingo\Api\Auth\LeagueOAuth2Provider; use League\OAuth2\Server\Exception\InvalidAccessTokenException; -class AuthLeagueOAuth2ProviderTest extends PHPUnit_Framework_TestCase { +class AuthLeagueOAuth2ProviderTest extends PHPUnit_Framework_TestCase +{ public function tearDown() diff --git a/tests/AuthShieldTest.php b/tests/AuthShieldTest.php index 62efdf709..008cb4a9c 100644 --- a/tests/AuthShieldTest.php +++ b/tests/AuthShieldTest.php @@ -7,7 +7,8 @@ use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; -class AuthShieldTest extends PHPUnit_Framework_TestCase { +class AuthShieldTest extends PHPUnit_Framework_TestCase +{ public function setUp() @@ -103,14 +104,13 @@ public function testRegisteringCustomProviderAtRuntime() $auth->authenticate($request, $route); $this->assertInstanceOf('CustomProviderStub', $auth->getUsedProvider()); - $auth->extend('custom', function($app) - { + $auth->extend('custom', function ($app) { $this->assertInstanceOf('Illuminate\Container\Container', $app); return new CustomProviderStub; }); $auth->authenticate($request, $route); - $this->assertInstanceOf('CustomProviderStub', $auth->getUsedProvider()); + $this->assertInstanceOf('CustomProviderStub', $auth->getUsedProvider()); } diff --git a/tests/DispatcherTest.php b/tests/DispatcherTest.php index ac22a7f11..7dcbaa008 100644 --- a/tests/DispatcherTest.php +++ b/tests/DispatcherTest.php @@ -14,7 +14,8 @@ use Illuminate\Events\Dispatcher as EventsDispatcher; use Dingo\Api\Http\ResponseFormat\JsonResponseFormat; -class DispatcherTest extends PHPUnit_Framework_TestCase { +class DispatcherTest extends PHPUnit_Framework_TestCase +{ public function setUp() @@ -40,13 +41,22 @@ public function tearDown() public function testInternalRequests() { - $this->router->api(['version' => 'v1'], function() - { - $this->router->get('test', function(){ return 'test'; }); - $this->router->post('test', function(){ return 'test'; }); - $this->router->put('test', function(){ return 'test'; }); - $this->router->patch('test', function(){ return 'test'; }); - $this->router->delete('test', function(){ return 'test'; }); + $this->router->api(['version' => 'v1'], function () { + $this->router->get('test', function () { + return 'test'; + }); + $this->router->post('test', function () { + return 'test'; + }); + $this->router->put('test', function () { + return 'test'; + }); + $this->router->patch('test', function () { + return 'test'; + }); + $this->router->delete('test', function () { + return 'test'; + }); }); $this->assertEquals('test', $this->dispatcher->get('test')); @@ -59,9 +69,10 @@ public function testInternalRequests() public function testInternalRequestWithVersionAndParameters() { - $this->router->api(['version' => 'v1'], function() - { - $this->router->get('test', function(){ return 'test'; }); + $this->router->api(['version' => 'v1'], function () { + $this->router->get('test', function () { + return 'test'; + }); }); $this->assertEquals('test', $this->dispatcher->version('v1')->with(['foo' => 'bar'])->get('test')); @@ -70,9 +81,10 @@ public function testInternalRequestWithVersionAndParameters() public function testInternalRequestWithPrefix() { - $this->router->api(['version' => 'v1', 'prefix' => 'baz'], function() - { - $this->router->get('test', function(){ return 'test'; }); + $this->router->api(['version' => 'v1', 'prefix' => 'baz'], function () { + $this->router->get('test', function () { + return 'test'; + }); }); $this->assertEquals('test', $this->dispatcher->get('test')); @@ -81,9 +93,10 @@ public function testInternalRequestWithPrefix() public function testInternalRequestWithDomain() { - $this->router->api(['version' => 'v1', 'domain' => 'foo.bar'], function() - { - $this->router->get('test', function(){ return 'test'; }); + $this->router->api(['version' => 'v1', 'domain' => 'foo.bar'], function () { + $this->router->get('test', function () { + return 'test'; + }); }); $this->assertEquals('test', $this->dispatcher->get('test')); @@ -95,7 +108,8 @@ public function testInternalRequestWithDomain() */ public function testInternalRequestThrowsException() { - $this->router->api(['version' => 'v1'], function() {}); + $this->router->api(['version' => 'v1'], function () { + }); $this->dispatcher->get('test'); } @@ -106,10 +120,8 @@ public function testInternalRequestThrowsException() */ public function testInternalRequestThrowsExceptionWhenResponseIsNotOkay() { - $this->router->api(['version' => 'v1'], function() - { - $this->router->get('test', function() - { + $this->router->api(['version' => 'v1'], function () { + $this->router->get('test', function () { return new Illuminate\Http\Response('test', 401); }); }); @@ -144,9 +156,10 @@ public function testPretendingToBeUserForSingleRequest() $this->auth->shouldReceive('setUser')->once()->with($user); $this->auth->shouldReceive('setUser')->once()->with(null); - $this->router->api(['version' => 'v1'], function() - { - $this->router->get('test', function(){ return 'test'; }); + $this->router->api(['version' => 'v1'], function () { + $this->router->get('test', function () { + return 'test'; + }); }); $this->dispatcher->be($user)->once()->get('test'); @@ -155,15 +168,12 @@ public function testPretendingToBeUserForSingleRequest() public function testInternalRequestUsingRouteName() { - $this->router->api(['version' => 'v1'], function() - { - $this->router->get('test', ['as' => 'test', function() - { + $this->router->api(['version' => 'v1'], function () { + $this->router->get('test', ['as' => 'test', function () { return 'foo'; }]); - $this->router->get('test/{foo}', ['as' => 'parameters', function($parameter) - { + $this->router->get('test/{foo}', ['as' => 'parameters', function ($parameter) { return $parameter; }]); }); @@ -175,8 +185,7 @@ public function testInternalRequestUsingRouteName() public function testInternalRequestUsingControllerAction() { - $this->router->api(['version' => 'v1'], function() - { + $this->router->api(['version' => 'v1'], function () { $this->router->get('foo', 'InternalControllerActionRoutingStub@index'); }); @@ -186,9 +195,10 @@ public function testInternalRequestUsingControllerAction() public function testInternalRequestUsingRouteNameAndControllerActionDoesNotDoublePrefix() { - $this->router->api(['version' => 'v1', 'prefix' => 'api'], function() - { - $this->router->get('foo', ['as' => 'foo', function() { return 'foo'; }]); + $this->router->api(['version' => 'v1', 'prefix' => 'api'], function () { + $this->router->get('foo', ['as' => 'foo', function () { + return 'foo'; + }]); $this->router->get('bar', 'InternalControllerActionRoutingStub@index'); }); @@ -199,14 +209,16 @@ public function testInternalRequestUsingRouteNameAndControllerActionDoesNotDoubl public function testInternalRequestWithMultipleVersionsCallsCorrectVersion() { - $this->router->api(['version' => 'v1'], function() - { - $this->router->get('foo', function() { return 'foo'; }); + $this->router->api(['version' => 'v1'], function () { + $this->router->get('foo', function () { + return 'foo'; + }); }); - $this->router->api(['version' => 'v2'], function() - { - $this->router->get('foo', function() { return 'bar'; }); + $this->router->api(['version' => 'v2'], function () { + $this->router->get('foo', function () { + return 'bar'; + }); }); $this->assertEquals('bar', $this->dispatcher->version('v2')->get('foo')); @@ -217,14 +229,16 @@ public function testInternalRequestWithNestedInternalRequest() { $this->dispatcher = new Dispatcher(new Request, m::mock('Illuminate\Routing\UrlGenerator'), $this->router, m::mock('Dingo\Api\Auth\Shield')); - $this->router->api(['version' => 'v2', 'prefix' => 'api'], function() - { - $this->router->get('foo', function() { return 'bar'; }); + $this->router->api(['version' => 'v2', 'prefix' => 'api'], function () { + $this->router->get('foo', function () { + return 'bar'; + }); }); - $this->router->api(['version' => 'v3', 'prefix' => 'api'], function() - { - $this->router->get('foo', function() { return 'baz'.$this->dispatcher->version('v2')->get('foo'); }); + $this->router->api(['version' => 'v3', 'prefix' => 'api'], function () { + $this->router->get('foo', function () { + return 'baz' . $this->dispatcher->version('v2')->get('foo'); + }); }); $this->assertEquals('bazbar', $this->dispatcher->version('v3')->get('foo')); @@ -233,59 +247,50 @@ public function testInternalRequestWithNestedInternalRequest() public function testRequestStackIsMaintained() { - $this->router->api(['version' => 'v1', 'prefix' => 'api'], function() - { - $this->router->post('baz', function() - { + $this->router->api(['version' => 'v1', 'prefix' => 'api'], function () { + $this->router->post('baz', function () { $this->assertEquals('bazinga', $this->router->getCurrentRequest()->input('foo')); }); - $this->router->post('bar', function() - { + $this->router->post('bar', function () { $this->assertEquals('baz', $this->router->getCurrentRequest()->input('foo')); $this->dispatcher->with(['foo' => 'bazinga'])->post('baz'); $this->assertEquals('baz', $this->router->getCurrentRequest()->input('foo')); }); - $this->router->post('foo', function() - { + $this->router->post('foo', function () { $this->assertEquals('bar', $this->router->getCurrentRequest()->input('foo')); $this->dispatcher->with(['foo' => 'baz'])->post('bar'); $this->assertEquals('bar', $this->router->getCurrentRequest()->input('foo')); }); }); - + $this->dispatcher->with(['foo' => 'bar'])->post('foo'); } public function testRouteStackIsMaintained() { - $this->router->api(['version' => 'v1', 'prefix' => 'api'], function() - { - $this->router->post('baz', ['as' => 'bazinga', function() - { + $this->router->api(['version' => 'v1', 'prefix' => 'api'], function () { + $this->router->post('baz', ['as' => 'bazinga', function () { $this->assertEquals('bazinga', $this->router->currentRouteName()); }]); - $this->router->post('bar', ['as' => 'bar', function() - { + $this->router->post('bar', ['as' => 'bar', function () { $this->assertEquals('bar', $this->router->currentRouteName()); $this->dispatcher->post('baz'); $this->assertEquals('bar', $this->router->currentRouteName()); }]); - $this->router->post('foo', ['as' => 'foo', function() - { + $this->router->post('foo', ['as' => 'foo', function () { $this->assertEquals('foo', $this->router->currentRouteName()); $this->dispatcher->post('bar'); $this->assertEquals('foo', $this->router->currentRouteName()); }]); }); - + $this->dispatcher->post('foo'); } - } diff --git a/tests/ExceptionHandlerTest.php b/tests/ExceptionHandlerTest.php index c603af79e..2439dc18f 100644 --- a/tests/ExceptionHandlerTest.php +++ b/tests/ExceptionHandlerTest.php @@ -1,6 +1,7 @@ exceptionHandler->register(function(StubHttpException $e){}); + $this->exceptionHandler->register(function (StubHttpException $e) { + }); $this->assertArrayHasKey('StubHttpException', $this->exceptionHandler->getHandlers()); } public function testExceptionHandlerWillHandleExceptionPasses() { - $this->exceptionHandler->register(function(StubHttpException $e){}); + $this->exceptionHandler->register(function (StubHttpException $e) { + }); $this->assertTrue($this->exceptionHandler->willHandle(new StubHttpException(404))); } @@ -31,8 +34,7 @@ public function testExceptionHandlerWillHandleExceptionFails() public function testExceptionHandlerHandlesException() { - $this->exceptionHandler->register(function(StubHttpException $e) - { + $this->exceptionHandler->register(function (StubHttpException $e) { return new Illuminate\Http\Response('foo', 404); }); @@ -45,8 +47,7 @@ public function testExceptionHandlerHandlesException() public function testExceptionHandlerHandlesExceptionAndCreatesNewResponse() { - $this->exceptionHandler->register(function(StubHttpException $e) - { + $this->exceptionHandler->register(function (StubHttpException $e) { return 'foo'; }); diff --git a/tests/HttpMiddlewareAuthenticationTest.php b/tests/HttpMiddlewareAuthenticationTest.php index 8902ad730..99e913768 100644 --- a/tests/HttpMiddlewareAuthenticationTest.php +++ b/tests/HttpMiddlewareAuthenticationTest.php @@ -11,7 +11,8 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; -class HttpMiddlewareAuthenticationTest extends PHPUnit_Framework_TestCase { +class HttpMiddlewareAuthenticationTest extends PHPUnit_Framework_TestCase +{ public function setUp() diff --git a/tests/HttpMiddlewareRateLimitTest.php b/tests/HttpMiddlewareRateLimitTest.php index 7421917ab..296019314 100644 --- a/tests/HttpMiddlewareRateLimitTest.php +++ b/tests/HttpMiddlewareRateLimitTest.php @@ -9,7 +9,8 @@ use Dingo\Api\Http\ResponseFormat\JsonResponseFormat; use Symfony\Component\HttpKernel\HttpKernelInterface; -class HttpMiddlewareRateLimitTest extends PHPUnit_Framework_TestCase { +class HttpMiddlewareRateLimitTest extends PHPUnit_Framework_TestCase +{ public function setUp() @@ -107,11 +108,11 @@ public function testWrappedKernelIsHandledWhenRateLimitHasNotBeenExceeded() $ip = $request->getClientIp(); - $this->cache->shouldReceive('add')->once()->with('dingo:api:requests:'.$ip, 0, 1); + $this->cache->shouldReceive('add')->once()->with('dingo:api:requests:' . $ip, 0, 1); $this->cache->shouldReceive('add')->once(); - $this->cache->shouldReceive('increment')->once()->with('dingo:api:requests:'.$ip); - $this->cache->shouldReceive('get')->twice()->with('dingo:api:requests:'.$ip)->andReturn(1); - $this->cache->shouldReceive('get')->once()->with('dingo:api:reset:'.$ip); + $this->cache->shouldReceive('increment')->once()->with('dingo:api:requests:' . $ip); + $this->cache->shouldReceive('get')->twice()->with('dingo:api:requests:' . $ip)->andReturn(1); + $this->cache->shouldReceive('get')->once()->with('dingo:api:reset:' . $ip); $this->app->shouldReceive('handle')->once()->with($request, HttpKernelInterface::MASTER_REQUEST, true)->andReturn(new Response('test')); $response = $this->middleware->handle($request); @@ -136,11 +137,11 @@ public function testForbiddenResponseIsReturnedWhenRateLimitIsExceeded() $ip = $request->getClientIp(); - $this->cache->shouldReceive('add')->once()->with('dingo:api:requests:'.$ip, 0, 1); + $this->cache->shouldReceive('add')->once()->with('dingo:api:requests:' . $ip, 0, 1); $this->cache->shouldReceive('add')->once(); - $this->cache->shouldReceive('increment')->once()->with('dingo:api:requests:'.$ip); - $this->cache->shouldReceive('get')->twice()->with('dingo:api:requests:'.$ip)->andReturn(2); - $this->cache->shouldReceive('get')->once()->with('dingo:api:reset:'.$ip); + $this->cache->shouldReceive('increment')->once()->with('dingo:api:requests:' . $ip); + $this->cache->shouldReceive('get')->twice()->with('dingo:api:requests:' . $ip)->andReturn(2); + $this->cache->shouldReceive('get')->once()->with('dingo:api:reset:' . $ip); Dingo\Api\Http\Response::setTransformer(m::mock('Dingo\Api\Transformer\Factory')->shouldReceive('transformableResponse')->andReturn(false)->getMock()); Dingo\Api\Http\Response::setFormatters(['json' => new Dingo\Api\Http\ResponseFormat\JsonResponseFormat]); diff --git a/tests/HttpResponseFormatJsonResponseFormatTest.php b/tests/HttpResponseFormatJsonResponseFormatTest.php index 6173dfecd..a24838c05 100644 --- a/tests/HttpResponseFormatJsonResponseFormatTest.php +++ b/tests/HttpResponseFormatJsonResponseFormatTest.php @@ -4,7 +4,8 @@ use Dingo\Api\Http\Response; use Dingo\Api\Http\ResponseFormat\JsonResponseFormat; -class HttpResponseFormatJsonResponseFormatTest extends PHPUnit_Framework_TestCase { +class HttpResponseFormatJsonResponseFormatTest extends PHPUnit_Framework_TestCase +{ public function setUp() diff --git a/tests/HttpResponseTest.php b/tests/HttpResponseTest.php index e21385555..5866d94b1 100644 --- a/tests/HttpResponseTest.php +++ b/tests/HttpResponseTest.php @@ -3,14 +3,15 @@ use Mockery as m; use Dingo\Api\Http\Response; -class HttpResponseTest extends PHPUnit_Framework_TestCase { +class HttpResponseTest extends PHPUnit_Framework_TestCase +{ public function setUp() { $this->formatter = m::mock('Dingo\Api\Http\ResponseFormat\JsonResponseFormat'); $this->formatter->shouldReceive('getContentType')->andReturn('foo'); - + Response::setFormatters(['json' => $this->formatter]); Response::setTransformer(m::mock('Dingo\Api\Transformer\Factory')->shouldReceive('transformableResponse')->andReturn(false)->getMock()); } diff --git a/tests/RoutingControllerInspectorTest.php b/tests/RoutingControllerInspectorTest.php index dbb60a5de..b9bbc4eff 100644 --- a/tests/RoutingControllerInspectorTest.php +++ b/tests/RoutingControllerInspectorTest.php @@ -2,7 +2,8 @@ use Dingo\Api\Routing\ControllerInspector; -class RoutingControllerInspectorTest extends PHPUnit_Framework_TestCase { +class RoutingControllerInspectorTest extends PHPUnit_Framework_TestCase +{ public function testControllerMethodIsNotRoutable() @@ -23,8 +24,11 @@ public function testControllerMethodIsRoutable() } -class ControllerStub extends Dingo\Api\Routing\Controller { +class ControllerStub extends Dingo\Api\Routing\Controller +{ - public function getFoo() {} + public function getFoo() + { + } } diff --git a/tests/RoutingControllerReviserTest.php b/tests/RoutingControllerReviserTest.php index be274383d..e8c219ec9 100644 --- a/tests/RoutingControllerReviserTest.php +++ b/tests/RoutingControllerReviserTest.php @@ -3,7 +3,8 @@ use Illuminate\Routing\Route; use Dingo\Api\Routing\ControllerReviser; -class RoutingControllerReviserTest extends PHPUnit_Framework_TestCase { +class RoutingControllerReviserTest extends PHPUnit_Framework_TestCase +{ public function testRoutingToRevisedControllerWithWildcardScopes() diff --git a/tests/RoutingRouterTest.php b/tests/RoutingRouterTest.php index 1888ac761..3ffb8a039 100644 --- a/tests/RoutingRouterTest.php +++ b/tests/RoutingRouterTest.php @@ -10,7 +10,8 @@ use Dingo\Api\Http\ResponseFormat\JsonResponseFormat; use Symfony\Component\HttpKernel\Exception\HttpException; -class RoutingRouterTest extends PHPUnit_Framework_TestCase { +class RoutingRouterTest extends PHPUnit_Framework_TestCase +{ public function setUp() @@ -42,7 +43,11 @@ public function tearDown() public function testRegisteringApiRoutes() { - $this->router->api(['version' => 'v1'], function() { $this->router->get('foo', function() { return 'bar'; }); }); + $this->router->api(['version' => 'v1'], function () { + $this->router->get('foo', function () { + return 'bar'; + }); + }); $request = Request::create('foo', 'GET'); $this->assertInstanceOf('Dingo\Api\Routing\ApiRouteCollection', $this->router->getApiRouteCollection('v1')); } @@ -50,8 +55,16 @@ public function testRegisteringApiRoutes() public function testRegisterApiRoutesWithMultipleVersions() { - $this->router->api(['version' => ['v1', 'v2']], function() { $this->router->get('foo', function() { return 'bar'; }); }); - $this->router->api(['version' => 'v2'], function() { $this->router->get('bar', function() { return 'baz'; }); }); + $this->router->api(['version' => ['v1', 'v2']], function () { + $this->router->get('foo', function () { + return 'bar'; + }); + }); + $this->router->api(['version' => 'v2'], function () { + $this->router->get('bar', function () { + return 'baz'; + }); + }); $request = Request::create('foo', 'GET'); $request->headers->set('accept', 'application/vnd.testing.v2+json'); @@ -65,8 +78,16 @@ public function testRegisterApiRoutesWithMultipleVersions() public function testRegisterApiRoutesWithDifferentResponseForSameUri() { - $this->router->api(['version' => 'v1'], function() { $this->router->get('foo', function() { return 'foo'; }); }); - $this->router->api(['version' => 'v2'], function() { $this->router->get('foo', function() { return 'bar'; }); }); + $this->router->api(['version' => 'v1'], function () { + $this->router->get('foo', function () { + return 'foo'; + }); + }); + $this->router->api(['version' => 'v2'], function () { + $this->router->get('foo', function () { + return 'bar'; + }); + }); $request = Request::create('foo', 'GET'); $request->headers->set('accept', 'application/vnd.testing.v1+json'); $this->assertEquals('{"message":"foo"}', $this->router->dispatch($request)->getContent()); @@ -77,7 +98,11 @@ public function testRegisterApiRoutesWithDifferentResponseForSameUri() public function testApiRouteCollectionOptionsApplyToRoutes() { - $this->router->api(['version' => 'v1', 'protected' => true], function() { $this->router->get('foo', function() { return 'bar'; }); }); + $this->router->api(['version' => 'v1', 'protected' => true], function () { + $this->router->get('foo', function () { + return 'bar'; + }); + }); $route = $this->router->getApiRouteCollection('v1')->getRoutes()[0]; $this->assertTrue($route->getAction()['protected']); } @@ -88,20 +113,23 @@ public function testApiRouteCollectionOptionsApplyToRoutes() */ public function testRegisteringApiRouteGroupWithoutVersionThrowsException() { - $this->router->api([], function(){}); + $this->router->api([], function () { + }); } public function testApiRoutesWithPrefix() { - $this->router->api(['version' => 'v1', 'prefix' => 'foo/bar'], function() - { - $this->router->get('foo', function() { return 'foo'; }); + $this->router->api(['version' => 'v1', 'prefix' => 'foo/bar'], function () { + $this->router->get('foo', function () { + return 'foo'; + }); }); - $this->router->api(['version' => 'v2', 'prefix' => 'foo/bar'], function() - { - $this->router->get('foo', function() { return 'bar'; }); + $this->router->api(['version' => 'v2', 'prefix' => 'foo/bar'], function () { + $this->router->get('foo', function () { + return 'bar'; + }); }); $request = Request::create('/foo/bar/foo', 'GET'); @@ -112,14 +140,16 @@ public function testApiRoutesWithPrefix() public function testApiRoutesWithDomains() { - $this->router->api(['version' => 'v1', 'domain' => 'foo.bar'], function() - { - $this->router->get('foo', function() { return 'foo'; }); + $this->router->api(['version' => 'v1', 'domain' => 'foo.bar'], function () { + $this->router->get('foo', function () { + return 'foo'; + }); }); - $this->router->api(['version' => 'v2', 'domain' => 'foo.bar'], function() - { - $this->router->get('foo', function() { return 'bar'; }); + $this->router->api(['version' => 'v2', 'domain' => 'foo.bar'], function () { + $this->router->get('foo', function () { + return 'bar'; + }); }); $request = Request::create('http://foo.bar/foo', 'GET'); @@ -130,9 +160,10 @@ public function testApiRoutesWithDomains() public function testRouterDispatchesInternalRequests() { - $this->router->api(['version' => 'v1'], function() - { - $this->router->get('foo', function() { return 'bar'; }); + $this->router->api(['version' => 'v1'], function () { + $this->router->get('foo', function () { + return 'bar'; + }); }); $request = InternalRequest::create('foo', 'GET'); @@ -143,7 +174,9 @@ public function testRouterDispatchesInternalRequests() public function testAddingRouteFallsThroughToRouterCollection() { - $this->router->get('foo', function() { return 'bar'; }); + $this->router->get('foo', function () { + return 'bar'; + }); $this->assertCount(1, $this->router->getRoutes()); } @@ -163,16 +196,17 @@ public function testRouterCatchesHttpExceptionsAndCreatesResponse() $this->exceptionHandler->shouldReceive('willHandle')->with($exception)->andReturn(false); - $this->router->api(['version' => 'v1'], function() use ($exception) - { - $this->router->get('foo', function() use ($exception) { throw $exception; }); + $this->router->api(['version' => 'v1'], function () use ($exception) { + $this->router->get('foo', function () use ($exception) { + throw $exception; + }); }); $request = Request::create('foo', 'GET'); $request->headers->set('accept', 'application/vnd.testing.v1+json'); $response = $this->router->dispatch($request); - + $this->assertEquals(404, $response->getStatusCode()); $this->assertEquals('{"message":"404 Not Found"}', $response->getContent()); } @@ -240,9 +274,10 @@ public function testExceptionHandledByExceptionHandler() */ public function testRouterCatchesHttpExceptionsAndRethrowsForInternalRequest() { - $this->router->api(['version' => 'v1'], function() - { - $this->router->get('foo', function() { throw new HttpException(404); }); + $this->router->api(['version' => 'v1'], function () { + $this->router->get('foo', function () { + throw new HttpException(404); + }); }); $this->router->dispatch(InternalRequest::create('foo', 'GET')); @@ -251,9 +286,10 @@ public function testRouterCatchesHttpExceptionsAndRethrowsForInternalRequest() public function testRouterIgnoresRouteGroupsWithAnApiPrefix() { - $this->router->group(['prefix' => 'api'], function() - { - $this->router->get('foo', function() { return 'foo'; }); + $this->router->group(['prefix' => 'api'], function () { + $this->router->get('foo', function () { + return 'foo'; + }); }); $this->assertEquals('foo', $this->router->dispatch(Request::create('api/foo', 'GET'))->getContent()); @@ -262,11 +298,14 @@ public function testRouterIgnoresRouteGroupsWithAnApiPrefix() public function testRequestTargettingAnApiWithNoPrefixOrDomain() { - $this->router->get('/', function() { return 'foo'; }); + $this->router->get('/', function () { + return 'foo'; + }); - $this->router->api(['version' => 'v1'], function() - { - $this->router->get('foo', function() { return 'bar'; }); + $this->router->api(['version' => 'v1'], function () { + $this->router->get('foo', function () { + return 'bar'; + }); }); $this->assertFalse($this->router->requestTargettingApi(Request::create('/', 'GET'))); @@ -275,14 +314,16 @@ public function testRequestTargettingAnApiWithNoPrefixOrDomain() public function testRequestWithMultipleApisFindsTheCorrectApiRouteCollection() { - $this->router->api(['version' => 'v1', 'prefix' => 'api'], function() - { - $this->router->get('foo', function() { return 'bar'; }); + $this->router->api(['version' => 'v1', 'prefix' => 'api'], function () { + $this->router->get('foo', function () { + return 'bar'; + }); }); - $this->router->api(['version' => 'v2', 'prefix' => 'api'], function() - { - $this->router->get('bar', function() { return 'baz'; }); + $this->router->api(['version' => 'v2', 'prefix' => 'api'], function () { + $this->router->get('bar', function () { + return 'baz'; + }); }); $request = Request::create('api/bar', 'GET'); @@ -294,14 +335,16 @@ public function testRequestWithMultipleApisFindsTheCorrectApiRouteCollection() public function testApiCollectionsWithPointReleaseVersions() { - $this->router->api(['version' => 'v1.1', 'prefix' => 'api'], function() - { - $this->router->get('foo', function() { return 'bar'; }); + $this->router->api(['version' => 'v1.1', 'prefix' => 'api'], function () { + $this->router->get('foo', function () { + return 'bar'; + }); }); - $this->router->api(['version' => 'v2.0.1', 'prefix' => 'api'], function() - { - $this->router->get('bar', function() { return 'baz'; }); + $this->router->api(['version' => 'v2.0.1', 'prefix' => 'api'], function () { + $this->router->get('bar', function () { + return 'baz'; + }); }); $request = Request::create('api/foo', 'GET'); @@ -318,14 +361,16 @@ public function testApiCollectionsWithPointReleaseVersions() public function testRouterDefaultsToDefaultVersionCollectionWhenNoAcceptHeader() { - $this->router->api(['version' => 'v1', 'prefix' => 'api'], function() - { - $this->router->get('foo', function() { return 'bar'; }); + $this->router->api(['version' => 'v1', 'prefix' => 'api'], function () { + $this->router->get('foo', function () { + return 'bar'; + }); }); - $this->router->api(['version' => 'v2', 'prefix' => 'api'], function() - { - $this->router->get('foo', function() { return 'baz'; }); + $this->router->api(['version' => 'v2', 'prefix' => 'api'], function () { + $this->router->get('foo', function () { + return 'baz'; + }); }); $request = Request::create('api/foo', 'GET'); diff --git a/tests/TransformerFactoryTest.php b/tests/TransformerFactoryTest.php index af107da5e..c0ec5c57d 100644 --- a/tests/TransformerFactoryTest.php +++ b/tests/TransformerFactoryTest.php @@ -2,7 +2,8 @@ use Mockery as m; -class TransformerTest extends PHPUnit_Framework_TestCase { +class TransformerTest extends PHPUnit_Framework_TestCase +{ public function setUp() diff --git a/tests/TransformerFractalTransformerTest.php b/tests/TransformerFractalTransformerTest.php index e52df4ece..96249ea5b 100644 --- a/tests/TransformerFractalTransformerTest.php +++ b/tests/TransformerFractalTransformerTest.php @@ -2,7 +2,8 @@ use Mockery as m; -class TransformerFractalTransformerTest extends PHPUnit_Framework_TestCase { +class TransformerFractalTransformerTest extends PHPUnit_Framework_TestCase +{ public function setUp() @@ -32,8 +33,7 @@ public function testTransformingResponseUsingTransformerClassName() public function testTransformingResponseUsingCallback() { - $this->transformerFactory->transform('Foo', function() - { + $this->transformerFactory->transform('Foo', function () { return new FooTransformerStub; }); $this->assertEquals(['data' => ['foo' => 'bar']], $this->transformerFactory->transformResponse(new Foo)); @@ -51,8 +51,7 @@ public function testTransformingCollectionUsingTransformerClassName() public function testTransformingCollectionUsingCallback() { - $this->transformerFactory->transform('Foo', function() - { + $this->transformerFactory->transform('Foo', function () { return new FooTransformerStub; }); $response = new Illuminate\Support\Collection([new Foo, new Foo]); @@ -105,7 +104,7 @@ public function testTransformingPaginator() 'next' => 'http://foo.bar/?page=2' ] ] - ], $this->transformerFactory->transformResponse($paginator)); + ], $this->transformerFactory->transformResponse($paginator)); } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index aeb844733..b4a12e23a 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,5 +1,5 @@ scope(['foo', 'bar']); } - public function index() {} + public function index() + { + } } -class IndividualScopeControllerStub extends Dingo\Api\Routing\Controller { +class IndividualScopeControllerStub extends Dingo\Api\Routing\Controller +{ public function __construct() { $this->scope(['foo', 'bar'], 'index'); } - public function index() {} + public function index() + { + } } -class ProtectedControllerStub extends Dingo\Api\Routing\Controller { +class ProtectedControllerStub extends Dingo\Api\Routing\Controller +{ public function __construct() { $this->protect('index'); } - public function index() {} + public function index() + { + } } -class UnprotectedControllerStub extends Dingo\Api\Routing\Controller { +class UnprotectedControllerStub extends Dingo\Api\Routing\Controller +{ public function __construct() { $this->unprotect('index'); } - public function index() {} + public function index() + { + } } -class StubHttpException extends Symfony\Component\HttpKernel\Exception\HttpException { +class StubHttpException extends Symfony\Component\HttpKernel\Exception\HttpException +{ } -class InternalControllerActionRoutingStub extends Illuminate\Routing\Controller { +class InternalControllerActionRoutingStub extends Illuminate\Routing\Controller +{ public function index() { @@ -93,15 +111,22 @@ public function index() } -class AuthorizationProviderStub extends Dingo\Api\Auth\AuthorizationProvider { +class AuthorizationProviderStub extends Dingo\Api\Auth\AuthorizationProvider +{ - public function authenticate(Illuminate\Http\Request $request, Illuminate\Routing\Route $route) {} + public function authenticate(Illuminate\Http\Request $request, Illuminate\Routing\Route $route) + { + } - public function getAuthorizationMethod() { return 'foo'; } + public function getAuthorizationMethod() + { + return 'foo'; + } } -class CustomProviderStub extends Dingo\Api\Auth\Provider { +class CustomProviderStub extends Dingo\Api\Auth\Provider +{ public function authenticate(Illuminate\Http\Request $request, Illuminate\Routing\Route $route) { @@ -110,7 +135,8 @@ public function authenticate(Illuminate\Http\Request $request, Illuminate\Routin } -class FooTransformerStub extends League\Fractal\TransformerAbstract { +class FooTransformerStub extends League\Fractal\TransformerAbstract +{ public function transform(Foo $foo) { @@ -119,7 +145,8 @@ public function transform(Foo $foo) } -class BarTransformerStub extends League\Fractal\TransformerAbstract { +class BarTransformerStub extends League\Fractal\TransformerAbstract +{ protected $availableEmbeds = ['foo']; @@ -135,11 +162,13 @@ public function embedFoo(Bar $bar) } -class Foo { +class Foo +{ } -class Bar implements Dingo\Api\Transformer\TransformableInterface { +class Bar implements Dingo\Api\Transformer\TransformableInterface +{ public function getTransformer() { return new BarTransformerStub;