From 1072fdcbe15aaedc77879aaeb322f8cf9b649e3f Mon Sep 17 00:00:00 2001 From: StyleCI Bot Date: Mon, 15 Jul 2024 09:21:41 +0000 Subject: [PATCH] Apply fixes from StyleCI --- helpers/helpers.php | 29 +++--- src/APIBoilerplate.php | 31 ++++--- src/APIHelpers.php | 33 ++++--- .../Laravel/ControllerMakeCommand.php | 5 +- .../Commands/Laravel/ModelMakeCommand.php | 5 +- .../Commands/Laravel/PolicyMakeCommand.php | 5 +- .../Commands/Laravel/SeederMakeCommand.php | 5 +- src/Console/Commands/MakeApiResource.php | 28 +++--- src/Exceptions/RestfulApiExceptionHandler.php | 18 ++-- src/Exceptions/UnauthorizedHttpException.php | 8 +- src/Helpers.php | 2 +- .../Controllers/BaseRestfulController.php | 18 ++-- .../AuthorizesUserActionsOnModelsTrait.php | 39 ++++---- .../Features/JWTAuthenticationTrait.php | 16 ++-- .../Features/RestfulControllerTrait.php | 34 +++---- .../Controllers/RestfulChildController.php | 92 ++++++++++--------- src/Http/Controllers/RestfulController.php | 62 +++++++------ src/Http/Middleware/CheckUserRole.php | 9 +- .../SnakeCaseInputParameterKeys.php | 21 +++-- src/Http/Response/Format/Json.php | 3 +- src/L5ApiServiceProvider.php | 6 +- src/Models/Builder.php | 13 +-- src/Models/RestfulModel.php | 47 +++++----- src/Services/RestfulService.php | 77 ++++++++-------- src/Transformers/RestfulTransformer.php | 59 ++++++------ test/app/Console/Kernel.php | 3 +- test/app/Exceptions/ApiExceptionHandler.php | 3 +- test/app/Exceptions/Handler.php | 10 +- .../Http/Controllers/Auth/AuthController.php | 3 - test/app/Http/Controllers/ChildController.php | 6 +- test/app/Http/Controllers/Controller.php | 6 +- test/app/Http/Controllers/ForumController.php | 1 - test/app/Http/Controllers/PostController.php | 2 - test/app/Http/Controllers/RoleController.php | 1 - test/app/Http/Controllers/TagController.php | 1 - test/app/Http/Controllers/TopicController.php | 12 ++- test/app/Http/Kernel.php | 20 ++-- test/app/Http/Middleware/Authenticate.php | 3 +- .../Middleware/RedirectIfAuthenticated.php | 7 +- test/app/Http/Middleware/TrustProxies.php | 2 +- test/app/Models/BaseModel.php | 2 +- test/app/Models/Forum.php | 6 +- test/app/Models/Policies/BasePolicy.php | 5 +- test/app/Models/Policies/ForumPolicy.php | 36 +++++--- test/app/Models/Policies/PostPolicy.php | 33 ++++--- test/app/Models/Policies/TagPolicy.php | 33 ++++--- test/app/Models/Policies/TopicPolicy.php | 33 ++++--- test/app/Models/Post.php | 4 +- test/app/Models/Role.php | 2 +- test/app/Models/Tag.php | 3 +- test/app/Models/Topic.php | 4 +- test/app/Models/User.php | 53 ++++++----- test/app/Providers/AppServiceProvider.php | 5 +- test/app/Providers/AuthServiceProvider.php | 1 - .../Providers/BroadcastServiceProvider.php | 2 +- test/app/Providers/EventServiceProvider.php | 2 +- test/app/Providers/RouteServiceProvider.php | 2 +- .../Providers/TelescopeServiceProvider.php | 2 +- test/app/Services/PostService.php | 10 +- test/app/Services/RestfulService.php | 9 +- test/app/Transformers/BaseTransformer.php | 3 +- test/config/api.php | 12 +-- test/config/auth.php | 12 +-- test/copy-over-deps.php | 6 +- test/database/factories/UserFactory.php | 8 +- ...8_04_30_000000_create_test_roles_table.php | 4 +- ...8_04_30_000010_create_test_users_table.php | 4 +- ...0011_create_test_password_resets_table.php | 4 +- ...30_000020_create_test_user_roles_table.php | 4 +- ..._02_11_144829_create_test_forums_table.php | 5 +- ..._02_11_144835_create_test_topics_table.php | 5 +- ...9_02_11_144837_create_test_posts_table.php | 5 +- ...19_06_03_123722_create_test_tags_table.php | 5 +- ..._03_123936_create_test_post_tags_table.php | 5 +- test/database/seeds/BaseSeeder.php | 28 +++--- test/database/seeds/ForumsSeeder.php | 17 ++-- test/database/seeds/PostsSeeder.php | 26 +++--- test/database/seeds/RoleTableSeeder.php | 22 +++-- test/database/seeds/TagsSeeder.php | 18 ++-- test/database/seeds/TopicsSeeder.php | 18 ++-- test/database/seeds/UserStorySeeder.php | 10 +- test/mocks/AppServiceProvider.php | 13 ++- test/mocks/RouteServiceProvider.php | 4 +- test/routes/api-routes.php | 16 ++-- test/tests/A/FirstTest.php | 1 + test/tests/Api/Patch/PatchTest.php | 5 +- test/tests/AppTestCase.php | 15 +-- test/tests/BaseTestCase.php | 8 +- test/tests/Fixtures/Models/ModelWithCasts.php | 2 +- test/tests/SetupTestApp.php | 35 +++---- test/tests/Unit/BaseTransformerTest.php | 10 +- test/tests/Unit/Helpers/KeyCaseTest.php | 53 ++++++----- test/tests/Unit/JsonFormatterTest.php | 11 +-- test/tests/Unit/RestfulServiceTest.php | 14 +-- test/tests/Unit/SnakeCaseMiddlewareTest.php | 11 +-- 95 files changed, 755 insertions(+), 656 deletions(-) diff --git a/helpers/helpers.php b/helpers/helpers.php index 77a506a..65354dd 100644 --- a/helpers/helpers.php +++ b/helpers/helpers.php @@ -1,6 +1,6 @@ user(); @@ -9,14 +9,15 @@ function APIUser() } } -if (! function_exists('camel_case_array_keys')) { +if (!function_exists('camel_case_array_keys')) { /** - * Recursively camel-case an array's keys + * Recursively camel-case an array's keys. * * @deprecated Use Helpers.php * - * @param $array - * @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null) + * @param $array + * @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null) + * * @return array $array */ function camel_case_array_keys($array, $levels = null) @@ -25,14 +26,15 @@ function camel_case_array_keys($array, $levels = null) } } -if (! function_exists('snake_case_array_keys')) { +if (!function_exists('snake_case_array_keys')) { /** - * Recursively snake-case an array's keys + * Recursively snake-case an array's keys. * * @deprecated Use Helpers.php * - * @param $array - * @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null) + * @param $array + * @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null) + * * @return array $array */ function snake_case_array_keys(array $array, $levels = null) @@ -41,14 +43,15 @@ function snake_case_array_keys(array $array, $levels = null) } } -if (! function_exists('model_relation_name')) { +if (!function_exists('model_relation_name')) { /** - * Converts the name of a model class to the name of the relation of this resource on another model + * Converts the name of a model class to the name of the relation of this resource on another model. * * @deprecated Use Helpers.php * - * @param string $resourceName The name of the resource we are dealing with - * @param string $relationType The type of relation - ie.. one to.. X ('one', 'many') + * @param string $resourceName The name of the resource we are dealing with + * @param string $relationType The type of relation - ie.. one to.. X ('one', 'many') + * * @return string The name of the relation, as it would appear inside an eloquent model */ function model_relation_name($resourceName, $relationType = 'many') diff --git a/src/APIBoilerplate.php b/src/APIBoilerplate.php index b5f7c36..3d0a694 100644 --- a/src/APIBoilerplate.php +++ b/src/APIBoilerplate.php @@ -8,19 +8,19 @@ class APIBoilerplate { /** - * Case type constants for configuring responses + * Case type constants for configuring responses. */ const CAMEL_CASE = 'camel-case'; const SNAKE_CASE = 'snake-case'; const DEFAULT_CASE = self::CAMEL_CASE; /** - * Case type config path + * Case type config path. */ const CASE_TYPE_CONFIG_PATH = 'api.formatsOptions.caseType'; /** - * The header which can be used to override config provided case type + * The header which can be used to override config provided case type. */ const CASE_TYPE_HEADER = 'X-Accept-Case-Type'; @@ -30,7 +30,7 @@ class APIBoilerplate protected static $requestedKeyCaseFormat = null; /** - * Get the required 'case type' for transforming response data + * Get the required 'case type' for transforming response data. * * @return string */ @@ -38,13 +38,13 @@ public static function getResponseCaseType() { $format = static::$requestedKeyCaseFormat; - if (! is_null($format)) { + if (!is_null($format)) { return $format; } // See if the client is requesting a specific case type $caseFormat = request()->header(static::CASE_TYPE_HEADER, null); - if (! is_null($caseFormat)) { + if (!is_null($caseFormat)) { if ($caseFormat == static::CAMEL_CASE) { $format = static::CAMEL_CASE; } elseif ($caseFormat == static::SNAKE_CASE) { @@ -73,10 +73,11 @@ public static function getResponseCaseType() } /** - * Formats case of the input array or scalar to desired case + * Formats case of the input array or scalar to desired case. + * + * @param array|string $input + * @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null) * - * @param array|string $input - * @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null) * @return array|string $transformed */ public static function formatKeyCaseAccordingToResponseFormat($input, $levels = null) @@ -87,7 +88,7 @@ public static function formatKeyCaseAccordingToResponseFormat($input, $levels = } // Use the other function for strings - if (! is_array($input)) { + if (!is_array($input)) { return static::formatCaseAccordingToResponseFormat($input); } @@ -106,9 +107,10 @@ public static function formatKeyCaseAccordingToResponseFormat($input, $levels = } /** - * Format the provided string into the required case response format, for attributes (ie. keys) + * Format the provided string into the required case response format, for attributes (ie. keys). + * + * @param string $attributeString * - * @param string $attributeString * @return string */ public static function formatCaseAccordingToResponseFormat($attributeString) @@ -125,11 +127,12 @@ public static function formatCaseAccordingToResponseFormat($attributeString) } /** - * Format the provided key string into the required case response format + * Format the provided key string into the required case response format. * * @deprecated Use the updated function name * - * @param string $key + * @param string $key + * * @return string */ public static function formatKeyCaseAccordingToReponseFormat($value) diff --git a/src/APIHelpers.php b/src/APIHelpers.php index 52c0519..a6a25a6 100644 --- a/src/APIHelpers.php +++ b/src/APIHelpers.php @@ -7,10 +7,11 @@ class APIHelpers { /** - * Recursively camel-case an array's keys + * Recursively camel-case an array's keys. + * + * @param $array + * @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null) * - * @param $array - * @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null) * @return array $array */ public static function camelCaseArrayKeys($array, $levels = null) @@ -40,10 +41,11 @@ public static function camelCaseArrayKeys($array, $levels = null) } /** - * Recursively snake-case an array's keys + * Recursively snake-case an array's keys. + * + * @param $array + * @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null) * - * @param $array - * @param int|null $levels How many levels of an array keys to transform - by default recurse infinitely (null) * @return array $array */ public static function snakeCaseArrayKeys(array $array, $levels = null) @@ -74,9 +76,10 @@ public static function snakeCaseArrayKeys(array $array, $levels = null) /** * Str::camel wrapper - for specific extra functionality - * Note this is generally only applicable when dealing with API input/output key case + * Note this is generally only applicable when dealing with API input/output key case. + * + * @param string $value * - * @param string $value * @return string */ public static function camel($value) @@ -91,9 +94,10 @@ public static function camel($value) /** * Str::snake wrapper - for specific extra functionality - * Note this is generally only applicable when dealing with API input/output key case + * Note this is generally only applicable when dealing with API input/output key case. + * + * @param string $value * - * @param string $value * @return mixed|string|string[]|null */ public static function snake($value) @@ -113,7 +117,7 @@ public static function snake($value) } /** - * Get the calling method name + * Get the calling method name. * * @return string */ @@ -123,10 +127,11 @@ public static function getCallingMethod() } /** - * Converts the name of a model class to the name of the relation of this resource on another model + * Converts the name of a model class to the name of the relation of this resource on another model. + * + * @param string $resourceName The name of the resource we are dealing with + * @param string $relationType The type of relation - ie.. one to.. X ('one', 'many') * - * @param string $resourceName The name of the resource we are dealing with - * @param string $relationType The type of relation - ie.. one to.. X ('one', 'many') * @return string The name of the relation, as it would appear inside an eloquent model */ public static function modelRelationName($resourceName, $relationType = 'many') diff --git a/src/Console/Commands/Laravel/ControllerMakeCommand.php b/src/Console/Commands/Laravel/ControllerMakeCommand.php index 4be40c1..baa76b1 100644 --- a/src/Console/Commands/Laravel/ControllerMakeCommand.php +++ b/src/Console/Commands/Laravel/ControllerMakeCommand.php @@ -7,12 +7,13 @@ class ControllerMakeCommand extends \Illuminate\Routing\Console\ControllerMakeCo /** * Resolve the fully-qualified path to the stub. * - * @param string $stub + * @param string $stub + * * @return string */ protected function resolveStubPath($stub) { - $boilerplateStub = __DIR__. '/../../../../resources' .$stub; + $boilerplateStub = __DIR__.'/../../../../resources'.$stub; return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) ? $customPath diff --git a/src/Console/Commands/Laravel/ModelMakeCommand.php b/src/Console/Commands/Laravel/ModelMakeCommand.php index b12df52..f5106d6 100644 --- a/src/Console/Commands/Laravel/ModelMakeCommand.php +++ b/src/Console/Commands/Laravel/ModelMakeCommand.php @@ -7,12 +7,13 @@ class ModelMakeCommand extends \Illuminate\Foundation\Console\ModelMakeCommand /** * Resolve the fully-qualified path to the stub. * - * @param string $stub + * @param string $stub + * * @return string */ protected function resolveStubPath($stub) { - $boilerplateStub = __DIR__. '/../../../../resources' .$stub; + $boilerplateStub = __DIR__.'/../../../../resources'.$stub; return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) ? $customPath diff --git a/src/Console/Commands/Laravel/PolicyMakeCommand.php b/src/Console/Commands/Laravel/PolicyMakeCommand.php index 95bb76d..b59438d 100644 --- a/src/Console/Commands/Laravel/PolicyMakeCommand.php +++ b/src/Console/Commands/Laravel/PolicyMakeCommand.php @@ -7,12 +7,13 @@ class PolicyMakeCommand extends \Illuminate\Foundation\Console\PolicyMakeCommand /** * Resolve the fully-qualified path to the stub. * - * @param string $stub + * @param string $stub + * * @return string */ protected function resolveStubPath($stub) { - $boilerplateStub = __DIR__. '/../../../../resources' .$stub; + $boilerplateStub = __DIR__.'/../../../../resources'.$stub; return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) ? $customPath diff --git a/src/Console/Commands/Laravel/SeederMakeCommand.php b/src/Console/Commands/Laravel/SeederMakeCommand.php index f4a328f..a83aba5 100644 --- a/src/Console/Commands/Laravel/SeederMakeCommand.php +++ b/src/Console/Commands/Laravel/SeederMakeCommand.php @@ -7,12 +7,13 @@ class SeederMakeCommand extends \Illuminate\Database\Console\Seeds\SeederMakeCom /** * Resolve the fully-qualified path to the stub. * - * @param string $stub + * @param string $stub + * * @return string */ protected function resolveStubPath($stub) { - $boilerplateStub = __DIR__. '/../../../../resources' .$stub; + $boilerplateStub = __DIR__.'/../../../../resources'.$stub; return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) ? $customPath diff --git a/src/Console/Commands/MakeApiResource.php b/src/Console/Commands/MakeApiResource.php index b52f3ce..d488e2a 100644 --- a/src/Console/Commands/MakeApiResource.php +++ b/src/Console/Commands/MakeApiResource.php @@ -53,7 +53,7 @@ public function handle() // Conditionally create policy if ($this->anticipate('Would you like to create a policy for this resource?', ['yes', 'no']) == 'yes') { - $policyName = '../Models/Policies/' . $name . 'Policy'; + $policyName = '../Models/Policies/'.$name.'Policy'; $this->call('make:policy', ['name' => $policyName, '-m' => $name]); } @@ -67,12 +67,12 @@ public function handle() // Conditionally create seeder if ($this->anticipate('Would you like to create a Seeder for this resource?', ['yes', 'no']) == 'yes') { - $seederName = Str::plural($name) . 'Seeder'; + $seederName = Str::plural($name).'Seeder'; $this->call('make:seeder', ['name' => $seederName]); $this->line('Please add the following to your DatabaseSeeder.php file', 'important'); - $this->line('$this->call('. $seederName .'::class);', 'code'); + $this->line('$this->call('.$seederName.'::class);', 'code'); $this->line(PHP_EOL); } @@ -84,25 +84,25 @@ public function handle() $sectionName = Str::pluralStudly($name); $routePrefix = Str::plural(Str::kebab($name)); - $controllerName = $name . 'Controller'; + $controllerName = $name.'Controller'; $exampleRoutes = - '/*' . PHP_EOL . - ' * ' . $sectionName . PHP_EOL . - ' */' . PHP_EOL . - '$api->group([\'prefix\' => \''. $routePrefix .'\'], function (Router $api) {' . PHP_EOL . - ' $api->get(\'/\', \'App\Http\Controllers\\'. $controllerName .'@getAll\');' . PHP_EOL . - ' $api->get(\'/{uuid}\', \'App\Http\Controllers\\'. $controllerName .'@get\');' . PHP_EOL . - ' $api->post(\'/\', \'App\Http\Controllers\\'. $controllerName .'@post\');' . PHP_EOL . - ' $api->patch(\'/{uuid}\', \'App\Http\Controllers\\'. $controllerName .'@patch\');' . PHP_EOL . - ' $api->delete(\'/{uuid}\', \'App\Http\Controllers\\'. $controllerName .'@delete\');' . PHP_EOL . + '/*'.PHP_EOL. + ' * '.$sectionName.PHP_EOL. + ' */'.PHP_EOL. + '$api->group([\'prefix\' => \''.$routePrefix.'\'], function (Router $api) {'.PHP_EOL. + ' $api->get(\'/\', \'App\Http\Controllers\\'.$controllerName.'@getAll\');'.PHP_EOL. + ' $api->get(\'/{uuid}\', \'App\Http\Controllers\\'.$controllerName.'@get\');'.PHP_EOL. + ' $api->post(\'/\', \'App\Http\Controllers\\'.$controllerName.'@post\');'.PHP_EOL. + ' $api->patch(\'/{uuid}\', \'App\Http\Controllers\\'.$controllerName.'@patch\');'.PHP_EOL. + ' $api->delete(\'/{uuid}\', \'App\Http\Controllers\\'.$controllerName.'@delete\');'.PHP_EOL. '});'; $this->line($exampleRoutes, 'code'); } /** - * Setup styles for command + * Setup styles for command. */ protected function setupStyles() { diff --git a/src/Exceptions/RestfulApiExceptionHandler.php b/src/Exceptions/RestfulApiExceptionHandler.php index 3da8b44..e2814fb 100644 --- a/src/Exceptions/RestfulApiExceptionHandler.php +++ b/src/Exceptions/RestfulApiExceptionHandler.php @@ -2,13 +2,13 @@ namespace Specialtactics\L5Api\Exceptions; -use Throwable; use Dingo\Api\Exception\Handler as ExceptionHandler; use Specialtactics\L5Api\APIBoilerplate; use Specialtactics\L5Api\Helpers; +use Throwable; /** - * This class extends the Dingo API Exception Handler, and can be used to modify it's functionality, if required + * This class extends the Dingo API Exception Handler, and can be used to modify it's functionality, if required. * * Class ApiHandler */ @@ -20,9 +20,10 @@ class RestfulApiExceptionHandler extends ExceptionHandler protected $originalReplacements = []; /** - * Override prepare replacements function to add extra functionality + * Override prepare replacements function to add extra functionality. + * + * @param Throwable $exception * - * @param Throwable $exception * @return array */ protected function prepareReplacements(Throwable $exception) @@ -32,7 +33,7 @@ protected function prepareReplacements(Throwable $exception) // If the errors part is a MessageBag, turn it into an array so we can more easily handle it consistently $errorKey = Config('api.errorFormat.errors'); - if (array_key_exists($errorKey, $replacements) && ! is_array($replacements[$errorKey]) && is_object($replacements[$errorKey]) && $replacements[$errorKey] instanceof \Illuminate\Support\MessageBag) { + if (array_key_exists($errorKey, $replacements) && !is_array($replacements[$errorKey]) && is_object($replacements[$errorKey]) && $replacements[$errorKey] instanceof \Illuminate\Support\MessageBag) { $replacements[$errorKey] = $replacements[$errorKey]->toArray(); } @@ -55,7 +56,7 @@ protected function prepareReplacements(Throwable $exception) } /** - * Get the original replacements array + * Get the original replacements array. * * @return array */ @@ -65,9 +66,10 @@ public function getOriginalReplacements() } /** - * Formats the case of validation message keys, if response case is not snake-case + * Formats the case of validation message keys, if response case is not snake-case. + * + * @param array $replacements * - * @param array $replacements * @return array */ protected function formatCaseOfValidationMessages($replacements) diff --git a/src/Exceptions/UnauthorizedHttpException.php b/src/Exceptions/UnauthorizedHttpException.php index 55b7704..2f8d547 100644 --- a/src/Exceptions/UnauthorizedHttpException.php +++ b/src/Exceptions/UnauthorizedHttpException.php @@ -7,10 +7,10 @@ class UnauthorizedHttpException extends HttpException { /** - * @param string $message The internal exception message - * @param \Exception $previous The previous exception - * @param int $code The internal exception code - * @param array $headers + * @param string $message The internal exception message + * @param \Exception $previous The previous exception + * @param int $code The internal exception code + * @param array $headers */ public function __construct(string $message = null, \Exception $previous = null, ?int $code = 0, array $headers = []) { diff --git a/src/Helpers.php b/src/Helpers.php index bacda13..f062021 100644 --- a/src/Helpers.php +++ b/src/Helpers.php @@ -4,7 +4,7 @@ /** * This is here for backwards compatibility reasons, renamed class to "APIHelpers" to make it easier to import - * directly without having to alias + * directly without having to alias. * * Class Helpers */ diff --git a/src/Http/Controllers/BaseRestfulController.php b/src/Http/Controllers/BaseRestfulController.php index 7c15cd9..f4da92e 100644 --- a/src/Http/Controllers/BaseRestfulController.php +++ b/src/Http/Controllers/BaseRestfulController.php @@ -4,15 +4,17 @@ use App\Services\RestfulService; use App\Transformers\BaseTransformer; +use Dingo\Api\Routing\Helpers; +use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Bus\DispatchesJobs; -use Illuminate\Routing\Controller; use Illuminate\Foundation\Validation\ValidatesRequests; -use Illuminate\Foundation\Auth\Access\AuthorizesRequests; -use Dingo\Api\Routing\Helpers; +use Illuminate\Routing\Controller; class BaseRestfulController extends Controller { - use AuthorizesRequests, DispatchesJobs, ValidatesRequests; + use AuthorizesRequests; + use DispatchesJobs; + use ValidatesRequests; use Helpers; use Features\RestfulControllerTrait; use Features\AuthorizesUserActionsOnModelsTrait; @@ -24,16 +26,16 @@ class BaseRestfulController extends Controller /** * Specify the model that you want to be associated with this controller. This is the primary model that - * the controller deals with + * the controller deals with. * - * @var \App\Models\BaseModel $model + * @var \App\Models\BaseModel */ public static $model = null; /** * Usually a transformer will be associated with a model, however if you don't specify a model or with to * override the transformer at a controller level (for example if it's a controller for a dashboard resource), then - * you can do so by specifying a transformer here + * you can do so by specifying a transformer here. * * @var null|BaseTransformer The transformer this controller should use */ @@ -42,7 +44,7 @@ class BaseRestfulController extends Controller /** * RestfulController constructor. * - * @param RestfulService $restfulService + * @param RestfulService $restfulService */ public function __construct(RestfulService $restfulService) { diff --git a/src/Http/Controllers/Features/AuthorizesUserActionsOnModelsTrait.php b/src/Http/Controllers/Features/AuthorizesUserActionsOnModelsTrait.php index 1abfcc5..54dda24 100644 --- a/src/Http/Controllers/Features/AuthorizesUserActionsOnModelsTrait.php +++ b/src/Http/Controllers/Features/AuthorizesUserActionsOnModelsTrait.php @@ -7,7 +7,7 @@ use Symfony\Component\HttpKernel\Exception\HttpException; /** - * Trait AuthorizesUsersActionsAgainstModelsTrait + * Trait AuthorizesUsersActionsAgainstModelsTrait. * * These are wrappers for Illuminate\Foundation\Auth\Access\Authorizable from the perspective of a RESTful controller * authorizing the access of authenticated users on a given resource model @@ -16,12 +16,12 @@ trait AuthorizesUserActionsOnModelsTrait { /** * Shorthand function which checks the currently logged in user against an action for the controller's model, - * and throws a 403 if unauthorized + * and throws a 403 if unauthorized. * * Only checks if a policy exists for that model. * - * @param string $ability - * @param array|mixed $arguments + * @param string $ability + * @param array|mixed $arguments * * @throws AccessDeniedHttpException */ @@ -32,16 +32,17 @@ public function authorizeUserAction($ability, $arguments = []) return true; } - if (! $this->userCan($ability, $arguments)) { + if (!$this->userCan($ability, $arguments)) { throw new AccessDeniedHttpException('Unauthorized action'); } } /** * This function can be used to add conditions to the query builder, - * which will specify the currently logged in user's ownership of the model + * which will specify the currently logged in user's ownership of the model. + * + * @param \Illuminate\Database\Eloquent\Builder $query * - * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder|null */ public function qualifyCollectionQuery($query) @@ -69,8 +70,9 @@ public function qualifyCollectionQuery($query) * * Only checks if a policy exists for that model. * - * @param string $ability - * @param array|mixed $arguments + * @param string $ability + * @param array|mixed $arguments + * * @return bool */ public function userCan($ability, $arguments = []) @@ -104,8 +106,9 @@ public function userCan($ability, $arguments = []) // If not, check if we have a custom Response object, and if so, utilise it // @var $response \Illuminate\Auth\Access\Response $response = app(Gate::class)->forUser($user)->inspect($ability, $arguments); - if (! empty($response->message())) { + if (!empty($response->message())) { $responseCode = $response->code() ?? 403; + throw new HttpException($responseCode, $response->message()); } @@ -113,22 +116,24 @@ public function userCan($ability, $arguments = []) } /** - * Determine if the user does not have a given ability for the model + * Determine if the user does not have a given ability for the model. + * + * @param string $ability + * @param array|mixed $arguments * - * @param string $ability - * @param array|mixed $arguments * @return bool */ public function userCant($ability, $arguments = []) { - return ! $this->userCan($ability, $arguments); + return !$this->userCan($ability, $arguments); } /** - * Determine if the user does not have a given ability for the model + * Determine if the user does not have a given ability for the model. + * + * @param string $ability + * @param array|mixed $arguments * - * @param string $ability - * @param array|mixed $arguments * @return bool */ public function userCannot($ability, $arguments = []) diff --git a/src/Http/Controllers/Features/JWTAuthenticationTrait.php b/src/Http/Controllers/Features/JWTAuthenticationTrait.php index bd90af2..0c57733 100644 --- a/src/Http/Controllers/Features/JWTAuthenticationTrait.php +++ b/src/Http/Controllers/Features/JWTAuthenticationTrait.php @@ -2,8 +2,8 @@ namespace Specialtactics\L5Api\Http\Controllers\Features; -use Illuminate\Http\Request; use Dingo\Api\Http\Response; +use Illuminate\Http\Request; use Specialtactics\L5Api\Exceptions\UnauthorizedHttpException; trait JWTAuthenticationTrait @@ -11,7 +11,8 @@ trait JWTAuthenticationTrait /** * Get a JWT via given credentials. * - * @param Request $request + * @param Request $request + * * @return Response */ public function token(Request $request) @@ -29,7 +30,7 @@ public function token(Request $request) [$login, $password] = explode(':', $credentials, 2); // Do auth - if (! $token = auth()->attempt(['email' => $login, 'password' => $password])) { + if (!$token = auth()->attempt(['email' => $login, 'password' => $password])) { throw new UnauthorizedHttpException('Unauthorized login'); } @@ -49,7 +50,7 @@ public function logout() } /** - * Refreshes a jwt (ie. extends it's TTL) + * Refreshes a jwt (ie. extends it's TTL). * * @return Response */ @@ -65,18 +66,19 @@ public function refresh() */ public function getUser() { - return $this->api->raw()->get('users/' . $this->auth->user()->getKey()); + return $this->api->raw()->get('users/'.$this->auth->user()->getKey()); } /** * Get the token array structure. * - * @param string $token + * @param string $token + * * @return Response */ protected function respondWithToken($token) { - $tokenReponse = new \stdClass; + $tokenReponse = new \stdClass(); $tokenReponse->jwt = $token; $tokenReponse->token_type = 'bearer'; diff --git a/src/Http/Controllers/Features/RestfulControllerTrait.php b/src/Http/Controllers/Features/RestfulControllerTrait.php index 6b84fe4..3fa06ea 100644 --- a/src/Http/Controllers/Features/RestfulControllerTrait.php +++ b/src/Http/Controllers/Features/RestfulControllerTrait.php @@ -9,7 +9,7 @@ trait RestfulControllerTrait { /** - * Figure out which transformer to use + * Figure out which transformer to use. * * Order of precedence: * - Controller specified @@ -23,16 +23,16 @@ protected function getTransformer() $transformer = null; // Check if controller specifies a resource - if (! is_null(static::$transformer)) { + if (!is_null(static::$transformer)) { $transformer = static::$transformer; } // Otherwise, check if model is specified else { // If it is, check if the controller's model specifies the transformer - if (! is_null(static::$model)) { + if (!is_null(static::$model)) { // If it does, use it - if (! is_null((static::$model)::$transformer)) { + if (!is_null((static::$model)::$transformer)) { $transformer = (static::$model)::$transformer; } } @@ -43,11 +43,11 @@ protected function getTransformer() $transformer = BaseTransformer::class; } - return new $transformer; + return new $transformer(); } /** - * Check if this request's body input is a collection of objects or not + * Check if this request's body input is a collection of objects or not. * * @return bool */ @@ -70,7 +70,7 @@ protected function isRequestBodyACollection(Request $request) /** * This method determines whether the resource returned should undergo transformation or not. - * The reason is, sometimes it is useful to return the untransformed resource (for example - for internal calls) + * The reason is, sometimes it is useful to return the untransformed resource (for example - for internal calls). * * Changed recently due to https://github.com/laravel/framework/pull/34884 * @@ -84,11 +84,11 @@ protected function shouldTransform() $numberOfCallsToCheck = 20; $callsToCheck = []; - for ($i = 0; $i < sizeof($trace) && $numberOfCallsToCheck > 0; ++$i) { + for ($i = 0; $i < sizeof($trace) && $numberOfCallsToCheck > 0; $i++) { // We only want function calls if (array_key_exists('file', $trace[$i])) { $callsToCheck[] = $trace[$i]; - --$numberOfCallsToCheck; + $numberOfCallsToCheck--; } } @@ -104,26 +104,28 @@ protected function shouldTransform() /** * Prepend a Response message with a custom message - * Useful for adding error info to internal request responses before returning them + * Useful for adding error info to internal request responses before returning them. + * + * @param \Dingo\Api\Http\Response $response + * @param $message * - * @param \Dingo\Api\Http\Response $response - * @param $message * @return \Dingo\Api\Http\Response */ protected function prependResponseMessage($response, $message) { $content = $response->getOriginalContent(); - $content['message'] = $message . \Illuminate\Support\Arr::get($content, 'message', ''); + $content['message'] = $message.\Illuminate\Support\Arr::get($content, 'message', ''); $response->setContent($content); return $response; } /** - * Try to find the relation name of the child model in the parent model + * Try to find the relation name of the child model in the parent model. + * + * @param $parent Object Parent model instance + * @param $child string Child model name * - * @param $parent Object Parent model instance - * @param $child string Child model name * @return null|string */ protected function getChildRelationNameForParent($parent, $child) diff --git a/src/Http/Controllers/RestfulChildController.php b/src/Http/Controllers/RestfulChildController.php index 5622f2d..f7489a5 100644 --- a/src/Http/Controllers/RestfulChildController.php +++ b/src/Http/Controllers/RestfulChildController.php @@ -4,18 +4,18 @@ use Illuminate\Http\Request; use Illuminate\Support\Collection; +use Specialtactics\L5Api\Helpers; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use Specialtactics\L5Api\Helpers; class RestfulChildController extends BaseRestfulController { /** * Specify the parent model that you want to be associated with this controller. This is the parent model of the - * primary model the controller deals with + * primary model the controller deals with. * - * @var \App\Models\BaseModel $model + * @var \App\Models\BaseModel */ public static $parentModel = null; @@ -30,18 +30,19 @@ class RestfulChildController extends BaseRestfulController * @var array */ public $parentAbilitiesRequired = [ - 'create' => 'update', - 'view' => 'view', + 'create' => 'update', + 'view' => 'view', 'viewAll' => 'view', - 'update' => 'own', - 'delete' => 'own', + 'update' => 'own', + 'delete' => 'own', ]; /** - * Request to retrieve a collection of all items owned by the parent of this resource + * Request to retrieve a collection of all items owned by the parent of this resource. + * + * @param string $uuid + * @param Request $request * - * @param string $uuid - * @param Request $request * @return \Dingo\Api\Http\Response */ public function getAll($uuid, Request $request) @@ -60,7 +61,7 @@ public function getAll($uuid, Request $request) // Form model's with relations for parent query $withArray = []; foreach ($model::getCollectionWith() as $modelRelation) { - $withArray[] = $resourceRelationName . '.' . $modelRelation; + $withArray[] = $resourceRelationName.'.'.$modelRelation; } $withArray = array_merge([$resourceRelationName], $withArray); @@ -77,10 +78,11 @@ public function getAll($uuid, Request $request) } /** - * Request to retrieve a single child owned by the parent of this resource (hasOne relationship) + * Request to retrieve a single child owned by the parent of this resource (hasOne relationship). + * + * @param string $uuid + * @param Request $request * - * @param string $uuid - * @param Request $request * @return \Dingo\Api\Http\Response */ public function getOneFromParent($uuid, Request $request) @@ -97,7 +99,7 @@ public function getOneFromParent($uuid, Request $request) // Form model's with relations for parent query $withArray = []; foreach ($model::getItemWith() as $modelRelation) { - $withArray[] = $resourceRelationName . '.' . $modelRelation; + $withArray[] = $resourceRelationName.'.'.$modelRelation; } $withArray = array_merge([$resourceRelationName], $withArray); @@ -107,7 +109,7 @@ public function getOneFromParent($uuid, Request $request) // Make sure it exists, and if so, authorize view action if ($resource == null) { - throw new NotFoundHttpException('Can not find a "' . $resourceRelationName . '" attached to this ' . (new \ReflectionClass($parentModel))->getShortName()); + throw new NotFoundHttpException('Can not find a "'.$resourceRelationName.'" attached to this '.(new \ReflectionClass($parentModel))->getShortName()); } else { // Authorize ability to view this model $this->authorizeUserAction('view', $resource); @@ -117,13 +119,14 @@ public function getOneFromParent($uuid, Request $request) } /** - * Request to retrieve a single item of this resource + * Request to retrieve a single item of this resource. * - * @param string $parentUuid UUID of the parent resource - * @param string $uuid UUID of the resource - * @return \Dingo\Api\Http\Response + * @param string $parentUuid UUID of the parent resource + * @param string $uuid UUID of the resource * * @throws HttpException + * + * @return \Dingo\Api\Http\Response */ public function get($parentUuid, $uuid) { @@ -135,17 +138,17 @@ public function get($parentUuid, $uuid) $this->authorizeUserAction($this->parentAbilitiesRequired['view'], $parentResource); // Get resource - $model = new static::$model; + $model = new static::$model(); $resource = $model::with($model::getItemWith())->where($model->getKeyName(), '=', $uuid)->firstOrFail(); // Check resource belongs to parent if ($resource->getAttribute($parentResource->getKeyName()) != $parentResource->getKey()) { - throw new AccessDeniedHttpException('Resource \'' . class_basename(static::$model) . '\' with given UUID ' . $uuid . ' does not belong to ' . - 'resource \'' . class_basename(static::$parentModel) . '\' with given UUID ' . $parentUuid . '; '); + throw new AccessDeniedHttpException('Resource \''.class_basename(static::$model).'\' with given UUID '.$uuid.' does not belong to '. + 'resource \''.class_basename(static::$parentModel).'\' with given UUID '.$parentUuid.'; '); } - if (! $resource) { - throw new NotFoundHttpException('Resource \'' . class_basename(static::$model) . '\' with given UUID ' . $uuid . ' not found'); + if (!$resource) { + throw new NotFoundHttpException('Resource \''.class_basename(static::$model).'\' with given UUID '.$uuid.' not found'); } // Authorize ability to create this model @@ -155,14 +158,15 @@ public function get($parentUuid, $uuid) } /** - * Request to create the child resource owned by the parent resource + * Request to create the child resource owned by the parent resource. * * @oaram string $parentUuid Parent's UUID * - * @param Request $request - * @return \Dingo\Api\Http\Response + * @param Request $request * * @throws HttpException + * + * @return \Dingo\Api\Http\Response */ public function post($parentUuid, Request $request) { @@ -177,7 +181,7 @@ public function post($parentUuid, Request $request) $this->authorizeUserAction('create'); $requestData = $request->input(); - $model = new static::$model; + $model = new static::$model(); // Validate $this->restfulService->validateResource($model, $requestData); @@ -204,14 +208,15 @@ public function post($parentUuid, Request $request) } /** - * Request to update the specified child resource + * Request to update the specified child resource. * - * @param string $parentUuid UUID of the parent resource - * @param string $uuid UUID of the child resource - * @param Request $request - * @return \Dingo\Api\Http\Response + * @param string $parentUuid UUID of the parent resource + * @param string $uuid UUID of the child resource + * @param Request $request * * @throws HttpException + * + * @return \Dingo\Api\Http\Response */ public function patch($parentUuid, $uuid, Request $request) { @@ -223,13 +228,13 @@ public function patch($parentUuid, $uuid, Request $request) $this->authorizeUserAction($this->parentAbilitiesRequired['update'], $parentResource); // Get resource - $model = new static::$model; + $model = new static::$model(); $resource = static::$model::findOrFail($uuid); // Check resource belongs to parent if ($resource->getAttribute($parentResource->getKeyName()) != $parentResource->getKey()) { - throw new AccessDeniedHttpException('Resource \'' . class_basename(static::$model) . '\' with given UUID ' . $uuid . ' does not belong to ' . - 'resource \'' . class_basename(static::$parentModel) . '\' with given UUID ' . $parentUuid . '; '); + throw new AccessDeniedHttpException('Resource \''.class_basename(static::$model).'\' with given UUID '.$uuid.' does not belong to '. + 'resource \''.class_basename(static::$parentModel).'\' with given UUID '.$parentUuid.'; '); } $this->authorizeUserAction('update', $resource); @@ -253,13 +258,14 @@ public function patch($parentUuid, $uuid, Request $request) } /** - * Deletes a child resource by UUID + * Deletes a child resource by UUID. * - * @param string $parentUuid UUID of the parent resource - * @param string $uuid UUID of the child resource - * @return \Dingo\Api\Http\Response + * @param string $parentUuid UUID of the parent resource + * @param string $uuid UUID of the child resource * * @throws HttpException + * + * @return \Dingo\Api\Http\Response */ public function delete($parentUuid, $uuid) { @@ -276,8 +282,8 @@ public function delete($parentUuid, $uuid) // Check resource belongs to parent if ($resource->getAttribute($parentResource->getKeyName()) != $parentResource->getKey()) { - throw new AccessDeniedHttpException('Resource \'' . class_basename(static::$model) . '\' with given UUID ' . $uuid . ' does not belong to ' . - 'resource \'' . class_basename(static::$parentModel) . '\' with given UUID ' . $parentUuid . '; '); + throw new AccessDeniedHttpException('Resource \''.class_basename(static::$model).'\' with given UUID '.$uuid.' does not belong to '. + 'resource \''.class_basename(static::$parentModel).'\' with given UUID '.$parentUuid.'; '); } $deletedCount = $resource->delete(); diff --git a/src/Http/Controllers/RestfulController.php b/src/Http/Controllers/RestfulController.php index 3d16991..5bc567a 100644 --- a/src/Http/Controllers/RestfulController.php +++ b/src/Http/Controllers/RestfulController.php @@ -2,16 +2,16 @@ namespace Specialtactics\L5Api\Http\Controllers; +use Cache; use Illuminate\Database\QueryException; use Illuminate\Http\Request; use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use Cache; class RestfulController extends BaseRestfulController { /** - * Cache key for getAll() function - all of a collection's resources + * Cache key for getAll() function - all of a collection's resources. */ const CACHE_KEY_GET_ALL = '%s_getAll'; @@ -30,7 +30,7 @@ class RestfulController extends BaseRestfulController public static $cacheExpiresIn = 86400; /** - * Request to retrieve a collection of all items of this resource + * Request to retrieve a collection of all items of this resource. * * @return \Dingo\Api\Http\Response */ @@ -38,7 +38,7 @@ public function getAll() { $this->authorizeUserAction('viewAll'); - $model = new static::$model; + $model = new static::$model(); // If we are caching the endpont, do a simple get all resources if (static::$cacheAll) { @@ -69,21 +69,22 @@ public function getAll() } /** - * Request to retrieve a single item of this resource + * Request to retrieve a single item of this resource. * - * @param string $uuid UUID of the resource - * @return \Dingo\Api\Http\Response + * @param string $uuid UUID of the resource * * @throws HttpException + * + * @return \Dingo\Api\Http\Response */ public function get($uuid) { - $model = new static::$model; + $model = new static::$model(); $resource = $model::with($model::getItemWith())->where($model->getKeyName(), '=', $uuid)->first(); - if (! $resource) { - throw new NotFoundHttpException('Resource \'' . class_basename(static::$model) . '\' with given UUID ' . $uuid . ' not found'); + if (!$resource) { + throw new NotFoundHttpException('Resource \''.class_basename(static::$model).'\' with given UUID '.$uuid.' not found'); } $this->authorizeUserAction('view', $resource); @@ -92,18 +93,19 @@ public function get($uuid) } /** - * Request to create a new resource + * Request to create a new resource. * - * @param Request $request - * @return \Dingo\Api\Http\Response + * @param Request $request * * @throws HttpException|QueryException + * + * @return \Dingo\Api\Http\Response */ public function post(Request $request) { $this->authorizeUserAction('create'); - $model = new static::$model; + $model = new static::$model(); $this->restfulService->validateResource($model, $request->input()); @@ -122,21 +124,22 @@ public function post(Request $request) } /** - * Request to create or replace a resource + * Request to create or replace a resource. + * + * @param Request $request + * @param string $uuid * - * @param Request $request - * @param string $uuid * @return \Dingo\Api\Http\Response */ public function put(Request $request, $uuid) { $model = static::$model::find($uuid); - if (! $model) { + if (!$model) { // Doesn't exist - create $this->authorizeUserAction('create'); - $model = new static::$model; + $model = new static::$model(); $this->restfulService->validateResource($model, $request->input()); $resource = $this->restfulService->persistResource(new $model($request->input())); @@ -166,13 +169,14 @@ public function put(Request $request, $uuid) } /** - * Request to update the specified resource + * Request to update the specified resource. * - * @param string $uuid UUID of the resource - * @param Request $request - * @return \Dingo\Api\Http\Response + * @param string $uuid UUID of the resource + * @param Request $request * * @throws HttpException + * + * @return \Dingo\Api\Http\Response */ public function patch($uuid, Request $request) { @@ -194,12 +198,13 @@ public function patch($uuid, Request $request) } /** - * Deletes a resource by UUID + * Deletes a resource by UUID. * - * @param string $uuid UUID of the resource - * @return \Dingo\Api\Http\Response + * @param string $uuid UUID of the resource * * @throws NotFoundHttpException + * + * @return \Dingo\Api\Http\Response */ public function delete($uuid) { @@ -217,9 +222,10 @@ public function delete($uuid) } /** - * Get the cache key for a given endpoint in this controller + * Get the cache key for a given endpoint in this controller. + * + * @param string $endpoint * - * @param string $endpoint * @return string $cacheKey */ public static function getCacheKey(string $endpoint = 'getAll'): ?string diff --git a/src/Http/Middleware/CheckUserRole.php b/src/Http/Middleware/CheckUserRole.php index 6d47c55..f6151db 100644 --- a/src/Http/Middleware/CheckUserRole.php +++ b/src/Http/Middleware/CheckUserRole.php @@ -11,9 +11,10 @@ class CheckUserRole /** * Handle an incoming request. * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * @param array|string $roles Roles to check for + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param array|string $roles Roles to check for + * * @return mixed */ public function handle($request, Closure $next, ...$roles) @@ -25,7 +26,7 @@ public function handle($request, Closure $next, ...$roles) throw new UnauthorizedHttpException('Unauthorized - not logged in!'); } - if (! is_array($roles)) { + if (!is_array($roles)) { $roles = [$roles]; } diff --git a/src/Http/Middleware/SnakeCaseInputParameterKeys.php b/src/Http/Middleware/SnakeCaseInputParameterKeys.php index fe5254f..ea6397b 100644 --- a/src/Http/Middleware/SnakeCaseInputParameterKeys.php +++ b/src/Http/Middleware/SnakeCaseInputParameterKeys.php @@ -3,23 +3,23 @@ namespace Specialtactics\L5Api\Http\Middleware; use Closure; -use Symfony\Component\HttpFoundation\ParameterBag; use Specialtactics\L5Api\Helpers; +use Symfony\Component\HttpFoundation\ParameterBag; /** - * Class SnakeCaseInputParameterKeys + * Class SnakeCaseInputParameterKeys. * * This middleware makes sure all incoming request parameters are snake cased for the application */ class SnakeCaseInputParameterKeys { /** - * HTTP Methods we want to consider for transforming URL query params + * HTTP Methods we want to consider for transforming URL query params. */ protected const RELEVANT_METHODS_QUERY = ['POST', 'PATCH', 'PUT', 'DELETE', 'GET']; /** - * HTTP methods we want to consider for transorming request body input + * HTTP methods we want to consider for transorming request body input. */ protected const RELEVANT_METHODS_BODY = ['POST', 'PATCH', 'PUT', 'DELETE']; @@ -28,9 +28,10 @@ class SnakeCaseInputParameterKeys * * Replace all request parameter keys with snake_cased equivilents * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * @param string|null $guard + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param string|null $guard + * * @return mixed */ public function handle($request, Closure $next, $guard = null) @@ -53,15 +54,15 @@ public function handle($request, Closure $next, $guard = null) } /** - * Process parameters within a ParameterBag to snake_case the keys + * Process parameters within a ParameterBag to snake_case the keys. * - * @param ParameterBag $bag + * @param ParameterBag $bag */ protected function processParamBag(ParameterBag $bag) { $parameters = $bag->all(); - if (! empty($parameters) && count($parameters) > 0) { + if (!empty($parameters) && count($parameters) > 0) { $parameters = Helpers::snakeCaseArrayKeys($parameters); $bag->replace($parameters); diff --git a/src/Http/Response/Format/Json.php b/src/Http/Response/Format/Json.php index 3681014..10f5689 100644 --- a/src/Http/Response/Format/Json.php +++ b/src/Http/Response/Format/Json.php @@ -10,7 +10,8 @@ class Json extends \Dingo\Api\Http\Response\Format\Json /** * Format an array or instance implementing Arrayable. * - * @param array|\Illuminate\Contracts\Support\Arrayable $content + * @param array|\Illuminate\Contracts\Support\Arrayable $content + * * @return string */ public function formatArray($content) diff --git a/src/L5ApiServiceProvider.php b/src/L5ApiServiceProvider.php index 7d88c00..3e165b0 100644 --- a/src/L5ApiServiceProvider.php +++ b/src/L5ApiServiceProvider.php @@ -3,9 +3,9 @@ namespace Specialtactics\L5Api; use Illuminate\Contracts\Events\Dispatcher; +use Illuminate\Foundation\AliasLoader; use Illuminate\Routing\Router; use Illuminate\Support\ServiceProvider as LaravelServiceProvider; -use Illuminate\Foundation\AliasLoader; class L5ApiServiceProvider extends LaravelServiceProvider { @@ -16,7 +16,7 @@ public function register() { // Set API Transformer Adapter & properties $this->app['Dingo\Api\Transformer\Factory']->setAdapter(function ($app) { - return new \Dingo\Api\Transformer\Adapter\Fractal(new \League\Fractal\Manager, 'include', ','); + return new \Dingo\Api\Transformer\Adapter\Fractal(new \League\Fractal\Manager(), 'include', ','); }); // Register Fascades @@ -32,7 +32,7 @@ public function register() /** * Bootstrap the application services. * - * @param \Illuminate\Routing\Router $router + * @param \Illuminate\Routing\Router $router */ public function boot(Router $router, Dispatcher $event) { diff --git a/src/Models/Builder.php b/src/Models/Builder.php index ccd396a..6b45fc5 100644 --- a/src/Models/Builder.php +++ b/src/Models/Builder.php @@ -2,21 +2,22 @@ namespace Specialtactics\L5Api\Models; -use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Illuminate\Database\Eloquent\ModelNotFoundException; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** - * Class Builder + * Class Builder. * * This changes some default functionality to be more API-friendly */ class Builder extends \Illuminate\Database\Eloquent\Builder { /** - * Wrapper to throw a 404 instead of a 500 on model not found + * Wrapper to throw a 404 instead of a 500 on model not found. + * + * @param mixed $id + * @param array $columns * - * @param mixed $id - * @param array $columns * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model */ public function findOrFail($id, $columns = ['*']) @@ -24,7 +25,7 @@ public function findOrFail($id, $columns = ['*']) try { $resource = parent::findOrFail($id, $columns); } catch (ModelNotFoundException $e) { - throw new NotFoundHttpException('Resource \'' . class_basename($e->getModel()) . '\' with given UUID ' . $id . ' not found'); + throw new NotFoundHttpException('Resource \''.class_basename($e->getModel()).'\' with given UUID '.$id.' not found'); } return $resource; diff --git a/src/Models/RestfulModel.php b/src/Models/RestfulModel.php index b2f2e32..b302c33 100644 --- a/src/Models/RestfulModel.php +++ b/src/Models/RestfulModel.php @@ -2,12 +2,12 @@ namespace Specialtactics\L5Api\Models; -use Ramsey\Uuid\Uuid; -use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; -use Illuminate\Database\Eloquent\Model; use App\Transformers\BaseTransformer; -use Specialtactics\L5Api\Transformers\RestfulTransformer; +use Illuminate\Database\Eloquent\Model; +use Ramsey\Uuid\Uuid; use Specialtactics\L5Api\APIBoilerplate; +use Specialtactics\L5Api\Transformers\RestfulTransformer; +use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; class RestfulModel extends Model { @@ -39,7 +39,7 @@ class RestfulModel extends Model /** * Acts like $with (eager loads relations), however only for immediate controller requests for that object * This is useful if you want to use "with" for immediate resource routes, however don't want these relations - * always loaded in various service functions, for performance reasons + * always loaded in various service functions, for performance reasons. * * @deprecated Use getItemWith() and getCollectionWith() * @@ -48,7 +48,7 @@ class RestfulModel extends Model public static $localWith = null; /** - * What relations should one model of this entity be returned with, from a relevant controller + * What relations should one model of this entity be returned with, from a relevant controller. * * @var null|array */ @@ -56,21 +56,21 @@ class RestfulModel extends Model /** * What relations should a collection of models of this entity be returned with, from a relevant controller - * If left null, then $itemWith will be used + * If left null, then $itemWith will be used. * * @var null|array */ public static $collectionWith = null; /** - * You can define a custom transformer for a model, if you wish to override the functionality of the Base transformer + * You can define a custom transformer for a model, if you wish to override the functionality of the Base transformer. * * @var null|RestfulTransformer The transformer to use for this model, if overriding the default */ public static $transformer = null; /** - * Return the validation rules for this model + * Return the validation rules for this model. * * @return array Validation rules to be used for the model when creating it */ @@ -81,7 +81,7 @@ public function getValidationRules() /** * Return the validation rules for this model's update operations - * In most cases, they will be the same as for the create operations + * In most cases, they will be the same as for the create operations. * * @return array Validation roles to use for updating model */ @@ -91,7 +91,7 @@ public function getValidationRulesUpdating() } /** - * Return any custom validation rule messages to be used + * Return any custom validation rule messages to be used. * * @return array */ @@ -101,7 +101,7 @@ public function getValidationMessages() } /** - * Boot the model + * Boot the model. * * Add various functionality in the model lifecycle hooks */ @@ -114,7 +114,7 @@ public static function boot() // If the PK(s) are missing, generate them $uuidKeyName = $model->getKeyName(); - if ($uuidKeyName && ! $model->incrementing && ! is_array($uuidKeyName) && ! array_key_exists($uuidKeyName, $model->getAttributes())) { + if ($uuidKeyName && !$model->incrementing && !is_array($uuidKeyName) && !array_key_exists($uuidKeyName, $model->getAttributes())) { $model->$uuidKeyName = Uuid::uuid4()->toString(); } }); @@ -127,11 +127,11 @@ public static function boot() } // Disallow updating immutable attributes - if (! empty($model->immutableAttributes)) { + if (!empty($model->immutableAttributes)) { // For each immutable attribute, check if they have changed foreach ($model->immutableAttributes as $attributeName) { if ($model->getOriginal($attributeName) != $model->getAttribute($attributeName)) { - throw new BadRequestHttpException('Updating the "'. APIBoilerplate::formatCaseAccordingToResponseFormat($attributeName) .'" attribute is not allowed.'); + throw new BadRequestHttpException('Updating the "'.APIBoilerplate::formatCaseAccordingToResponseFormat($attributeName).'" attribute is not allowed.'); } } } @@ -139,20 +139,20 @@ public static function boot() } /** - * Return this model's transformer, or a generic one if a specific one is not defined for the model + * Return this model's transformer, or a generic one if a specific one is not defined for the model. * * @return BaseTransformer */ public static function getTransformer() { - return is_null(static::$transformer) ? new BaseTransformer : new static::$transformer; + return is_null(static::$transformer) ? new BaseTransformer() : new static::$transformer(); } /** * When Laravel creates a new model, it will add any new attributes (such as UUID) at the end. When a create * operation such as a POST returns the new resource, the UUID will thus be at the end, which doesn't look nice. * For purely aesthetic reasons, we have this function to conduct a simple reorder operation to move the UUID - * attribute to the head of the attributes array + * attribute to the head of the attributes array. * * This will be used at the end of create-related controller functions * @@ -169,7 +169,7 @@ public function orderAttributesUuidFirst() /** * If using deprecated $localWith then use that - * Otherwise, use $itemWith + * Otherwise, use $itemWith. * * @return array */ @@ -185,14 +185,14 @@ public static function getItemWith() /** * If using deprecated $localWith then use that * Otherwise, if collectionWith hasn't been set, use $itemWith by default - * Otherwise, use collectionWith + * Otherwise, use collectionWith. * * @return array */ public static function getCollectionWith() { if (is_null(static::$localWith)) { - if (! is_null(static::$collectionWith)) { + if (!is_null(static::$collectionWith)) { return static::$collectionWith; } else { return static::$itemWith; @@ -207,11 +207,12 @@ public static function getCollectionWith() ***********************************************************/ /** - * We're extending the existing Laravel Builder + * We're extending the existing Laravel Builder. * * Create a new Eloquent query builder for the model. * - * @param \Illuminate\Database\Query\Builder $query + * @param \Illuminate\Database\Query\Builder $query + * * @return \Illuminate\Database\Eloquent\Builder|static */ public function newEloquentBuilder($query) diff --git a/src/Services/RestfulService.php b/src/Services/RestfulService.php index 25ff098..f3f7765 100644 --- a/src/Services/RestfulService.php +++ b/src/Services/RestfulService.php @@ -2,34 +2,34 @@ namespace Specialtactics\L5Api\Services; -use Validator; use Config; -use Illuminate\Http\Request; -use Illuminate\Support\Str; +use Dingo\Api\Exception\StoreResourceFailedException; use Illuminate\Database\QueryException; +use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; +use Illuminate\Support\Str; +use Specialtactics\L5Api\Models\RestfulModel; +use Symfony\Component\HttpKernel\Exception\ConflictHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException; -use Symfony\Component\HttpKernel\Exception\ConflictHttpException; -use Dingo\Api\Exception\StoreResourceFailedException; -use Specialtactics\L5Api\Models\RestfulModel; +use Validator; /** - * This class contains logic for processing restful requests + * This class contains logic for processing restful requests. * * Class RestfulService */ class RestfulService { /** - * @var string $model The Model Class name + * @var string The Model Class name */ protected $model = null; /** * RestfulService constructor. * - * @param RestfulModel|null $model The model this service will be concerned with + * @param RestfulModel|null $model The model this service will be concerned with */ public function __construct($model = null) { @@ -37,9 +37,10 @@ public function __construct($model = null) } /** - * Set model to be used in the service + * Set model to be used in the service. + * + * @param string|null $model * - * @param string|null $model * @return $this */ public function setModel($model) @@ -50,10 +51,11 @@ public function setModel($model) } /** - * Deletes resources of the given model and uuid(s) + * Deletes resources of the given model and uuid(s). + * + * @param $model string Model class name + * @param $uuid string|array The UUID(s) of the models to remove * - * @param $model string Model class name - * @param $uuid string|array The UUID(s) of the models to remove * @return mixed */ public function delete($model, $uuid) @@ -68,15 +70,16 @@ public function delete($model, $uuid) } /** - * Patch a resource of the given model, with the given request + * Patch a resource of the given model, with the given request. * * @deprecated Use persistResource() instead * - * @param RestfulModel $model - * @param array $data - * @return bool + * @param RestfulModel $model + * @param array $data * * @throws HttpException + * + * @return bool */ public function patch($model, array $data) { @@ -84,13 +87,13 @@ public function patch($model, array $data) $resource = $model->update($data); } catch (\Exception $e) { // Log this as an unexpected exception, useful if API debug is off - Log::error('Error updating resource ' . get_class($model) . ': ' . $e->getMessage()); + Log::error('Error updating resource '.get_class($model).': '.$e->getMessage()); // Check for QueryException - if so, we may want to display a more meaningful message, or help with // development debugging if ($e instanceof QueryException) { if (stristr($e->getMessage(), 'duplicate')) { - throw new ConflictHttpException('The resource already exists: ' . class_basename($model)); + throw new ConflictHttpException('The resource already exists: '.class_basename($model)); } elseif (Config::get('api.debug') === true) { throw $e; } @@ -100,7 +103,7 @@ public function patch($model, array $data) $errorMessage = 'Unexpected error trying to store this resource.'; if (Config::get('api.debug') === true) { - $errorMessage .= ' ' . $e->getMessage(); + $errorMessage .= ' '.$e->getMessage(); } throw new UnprocessableEntityHttpException($errorMessage); @@ -110,10 +113,11 @@ public function patch($model, array $data) } /** - * Create model in the database + * Create model in the database. + * + * @param $model + * @param $data * - * @param $model - * @param $data * @return mixed */ public function persistResource(RestfulModel $resource) @@ -122,13 +126,13 @@ public function persistResource(RestfulModel $resource) $resource->save(); } catch (\Exception $e) { // Log this as an unexpected exception, useful if API debug is off - Log::error('Error persisting resource ' . get_class($resource) . ': ' . $e->getMessage()); + Log::error('Error persisting resource '.get_class($resource).': '.$e->getMessage()); // Check for QueryException - if so, we may want to display a more meaningful message, or help with // development debugging if ($e instanceof QueryException) { if (stristr($e->getMessage(), 'duplicate')) { - throw new ConflictHttpException('The resource already exists: ' . class_basename($resource)); + throw new ConflictHttpException('The resource already exists: '.class_basename($resource)); } elseif (Config::get('api.debug') === true) { throw $e; } @@ -138,7 +142,7 @@ public function persistResource(RestfulModel $resource) $errorMessage = 'Unexpected error trying to store this resource.'; if (Config::get('api.debug') === true) { - $errorMessage .= ' ' . $e->getMessage(); + $errorMessage .= ' '.$e->getMessage(); } throw new UnprocessableEntityHttpException($errorMessage); @@ -148,10 +152,10 @@ public function persistResource(RestfulModel $resource) } /** - * Validates a given resource (Restful Model) against a given data set, and throws an API exception on failure + * Validates a given resource (Restful Model) against a given data set, and throws an API exception on failure. * - * @param RestfulModel $resource - * @param array $data + * @param RestfulModel $resource + * @param array $data * * @throws StoreResourceFailedException */ @@ -171,10 +175,10 @@ public function validateResource($resource, array $data = null) /** * Validates a given resource (Restful Model) against a given data set in the update context - ie. validating - * only the fields updated in the provided data set, and throws an API exception on failure + * only the fields updated in the provided data set, and throws an API exception on failure. * - * @param RestfulModel $resource model resource - * @param array $data Data we are validating against + * @param RestfulModel $resource model resource + * @param array $data Data we are validating against * * @throws StoreResourceFailedException */ @@ -188,10 +192,11 @@ public function validateResourceUpdate($resource, array $data) } /** - * For a given RestfulModel resource and request's data, get the relevant validation rules for updating that resource + * For a given RestfulModel resource and request's data, get the relevant validation rules for updating that resource. + * + * @param RestfulModel $resource model resource + * @param array $data Data we are validating against * - * @param RestfulModel $resource model resource - * @param array $data Data we are validating against * @return array The relevant rules */ public function getRelevantValidationRules($resource, array $data) diff --git a/src/Transformers/RestfulTransformer.php b/src/Transformers/RestfulTransformer.php index af7fc11..12709cf 100644 --- a/src/Transformers/RestfulTransformer.php +++ b/src/Transformers/RestfulTransformer.php @@ -2,10 +2,10 @@ namespace Specialtactics\L5Api\Transformers; +use Illuminate\Database\Eloquent\Model as EloquentModel; use League\Fractal\TransformerAbstract; use Specialtactics\L5Api\APIBoilerplate; use Specialtactics\L5Api\Models\RestfulModel; -use Illuminate\Database\Eloquent\Model as EloquentModel; class RestfulTransformer extends TransformerAbstract { @@ -15,12 +15,13 @@ class RestfulTransformer extends TransformerAbstract protected $model = null; /** - * Transform an object into a jsonable array + * Transform an object into a jsonable array. * - * @param mixed $model - * @return array + * @param mixed $model * * @throws \Exception + * + * @return array */ public function transform($object) { @@ -42,9 +43,10 @@ public function transform($object) } /** - * Transform an arbitrary stdClass + * Transform an arbitrary stdClass. + * + * @param \stdClass $object * - * @param \stdClass $object * @return array */ public function transformStdClass($object) @@ -52,7 +54,7 @@ public function transformStdClass($object) $transformed = (array) $object; /** - * Transform all keys to correct case, recursively + * Transform all keys to correct case, recursively. */ $transformed = $this->transformKeysCase($transformed); @@ -60,9 +62,10 @@ public function transformStdClass($object) } /** - * Transform a restful model object into a jsonable array + * Transform a restful model object into a jsonable array. + * + * @param RestfulModel $model * - * @param RestfulModel $model * @return array */ public function transformRestfulModel(EloquentModel $model) @@ -73,19 +76,19 @@ public function transformRestfulModel(EloquentModel $model) $transformed = $model->toArray(); /** - * Filter out attributes we don't want to expose to the API + * Filter out attributes we don't want to expose to the API. */ $filterOutAttributes = $this->getFilteredOutAttributes(); $transformed = array_filter($transformed, function ($key) use ($filterOutAttributes) { - return ! in_array($key, $filterOutAttributes); + return !in_array($key, $filterOutAttributes); }, ARRAY_FILTER_USE_KEY); /* * Format all dates as Iso8601 strings, this includes the created_at and updated_at columns */ foreach ($model->getDates() as $dateColumn) { - if (! empty($model->$dateColumn) && ! in_array($dateColumn, $filterOutAttributes)) { + if (!empty($model->$dateColumn) && !in_array($dateColumn, $filterOutAttributes)) { $transformed[$dateColumn] = $model->$dateColumn->toIso8601String(); } } @@ -106,7 +109,7 @@ public function transformRestfulModel(EloquentModel $model) $transformed = $this->transformKeysCase($transformed); /** - * Get the relations for this object and transform them + * Get the relations for this object and transform them. */ $transformed = $this->transformRelations($transformed); @@ -115,9 +118,10 @@ public function transformRestfulModel(EloquentModel $model) /** * At the moment, there is no difference in implementation between this and the more specific Restfulmodel, - * however in the future there may be + * however in the future there may be. + * + * @param EloquentModel $model * - * @param EloquentModel $model * @return array */ public function transformEloquentModel(EloquentModel $model) @@ -126,9 +130,10 @@ public function transformEloquentModel(EloquentModel $model) } /** - * Transform the keys of the object to the correct case as required + * Transform the keys of the object to the correct case as required. + * + * @param array $transformed * - * @param array $transformed * @return array $transformed */ protected function transformKeysCase(array $transformed) @@ -137,21 +142,21 @@ protected function transformKeysCase(array $transformed) $levels = config('api.formatsOptions.transform_keys_levels', null); /** - * Transform all keys to required case, to the specified number of levels (by default, infinite) + * Transform all keys to required case, to the specified number of levels (by default, infinite). */ $transformed = APIBoilerplate::formatKeyCaseAccordingToResponseFormat($transformed, $levels); /* * However, if the level is 1, we also want to transform the first level of keys in a json field which has been cast to array */ - if ($levels == 1 && ! is_null($this->model)) { + if ($levels == 1 && !is_null($this->model)) { // Go through casted atrributes, figuring out what their new key name is to access them foreach ($this->model->getCasts() as $fieldName => $castType) { if ($castType == 'array') { $fieldNameFormatted = APIBoilerplate::formatKeyCaseAccordingToResponseFormat($fieldName); // Transform the keys of the array attribute - if (array_key_exists($fieldNameFormatted, $transformed) && ! empty($transformed[$fieldNameFormatted])) { + if (array_key_exists($fieldNameFormatted, $transformed) && !empty($transformed[$fieldNameFormatted])) { $transformed[$fieldNameFormatted] = APIBoilerplate::formatKeyCaseAccordingToResponseFormat($transformed[$fieldNameFormatted]); } } @@ -162,12 +167,13 @@ protected function transformKeysCase(array $transformed) } /** - * Formats case of the input array or scalar to desired case + * Formats case of the input array or scalar to desired case. * * @deprecated * - * @param array|string $input - * @param int|null $levels How many levels of an array keys to transform - by default recurse infiniately (null) + * @param array|string $input + * @param int|null $levels How many levels of an array keys to transform - by default recurse infiniately (null) + * * @return array $transformed */ protected function formatKeyCase($input, $levels = null) @@ -176,7 +182,7 @@ protected function formatKeyCase($input, $levels = null) } /** - * Filter out some attributes immediately + * Filter out some attributes immediately. * * Some attributes we never want to expose to an API consumer, for security and separation of concerns reasons * Feel free to override this function as necessary @@ -197,9 +203,10 @@ protected function getFilteredOutAttributes() } /** - * Do relation transformations + * Do relation transformations. + * + * @param array $transformed * - * @param array $transformed * @return array $transformed */ protected function transformRelations(array $transformed) diff --git a/test/app/Console/Kernel.php b/test/app/Console/Kernel.php index a8c5158..29934ca 100644 --- a/test/app/Console/Kernel.php +++ b/test/app/Console/Kernel.php @@ -19,7 +19,8 @@ class Kernel extends ConsoleKernel /** * Define the application's command schedule. * - * @param \Illuminate\Console\Scheduling\Schedule $schedule + * @param \Illuminate\Console\Scheduling\Schedule $schedule + * * @return void */ protected function schedule(Schedule $schedule) diff --git a/test/app/Exceptions/ApiExceptionHandler.php b/test/app/Exceptions/ApiExceptionHandler.php index 5c7c378..6f2d83f 100644 --- a/test/app/Exceptions/ApiExceptionHandler.php +++ b/test/app/Exceptions/ApiExceptionHandler.php @@ -5,10 +5,9 @@ use Specialtactics\L5Api\Exceptions\RestfulApiExceptionHandler; /** - * This class extends the Dingo API Exception Handler, and can be used to modify it's functionality, if required + * This class extends the Dingo API Exception Handler, and can be used to modify it's functionality, if required. * * Class ApiHandler - * @package App\Exceptions */ class ApiExceptionHandler extends RestfulApiExceptionHandler { diff --git a/test/app/Exceptions/Handler.php b/test/app/Exceptions/Handler.php index 9159de5..ab15bee 100644 --- a/test/app/Exceptions/Handler.php +++ b/test/app/Exceptions/Handler.php @@ -2,8 +2,8 @@ namespace App\Exceptions; -use Throwable; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; +use Throwable; class Handler extends ExceptionHandler { @@ -29,7 +29,8 @@ class Handler extends ExceptionHandler /** * Report or log an exception. * - * @param Throwable $e + * @param Throwable $e + * * @return void */ public function report(Throwable $e) @@ -40,8 +41,9 @@ public function report(Throwable $e) /** * Render an exception into an HTTP response. * - * @param \Illuminate\Http\Request $request - * @param Throwable $e + * @param \Illuminate\Http\Request $request + * @param Throwable $e + * * @return \Illuminate\Http\Response */ public function render($request, Throwable $e) diff --git a/test/app/Http/Controllers/Auth/AuthController.php b/test/app/Http/Controllers/Auth/AuthController.php index 3e50933..7fda9f6 100644 --- a/test/app/Http/Controllers/Auth/AuthController.php +++ b/test/app/Http/Controllers/Auth/AuthController.php @@ -2,10 +2,7 @@ namespace App\Http\Controllers\Auth; -use Illuminate\Http\Request; use App\Http\Controllers\Controller; -use App\Models\User; -use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; use Specialtactics\L5Api\Http\Controllers\Features\JWTAuthenticationTrait; class AuthController extends Controller diff --git a/test/app/Http/Controllers/ChildController.php b/test/app/Http/Controllers/ChildController.php index 6704942..65b0fdd 100644 --- a/test/app/Http/Controllers/ChildController.php +++ b/test/app/Http/Controllers/ChildController.php @@ -2,12 +2,14 @@ namespace App\Http\Controllers; +use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Validation\ValidatesRequests; -use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Specialtactics\L5Api\Http\Controllers\RestfulChildController as BaseController; class ChildController extends BaseController { - use AuthorizesRequests, DispatchesJobs, ValidatesRequests; + use AuthorizesRequests; + use DispatchesJobs; + use ValidatesRequests; } diff --git a/test/app/Http/Controllers/Controller.php b/test/app/Http/Controllers/Controller.php index 5289a7c..a9756e2 100644 --- a/test/app/Http/Controllers/Controller.php +++ b/test/app/Http/Controllers/Controller.php @@ -2,12 +2,14 @@ namespace App\Http\Controllers; +use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Validation\ValidatesRequests; -use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Specialtactics\L5Api\Http\Controllers\RestfulController as BaseController; class Controller extends BaseController { - use AuthorizesRequests, DispatchesJobs, ValidatesRequests; + use AuthorizesRequests; + use DispatchesJobs; + use ValidatesRequests; } diff --git a/test/app/Http/Controllers/ForumController.php b/test/app/Http/Controllers/ForumController.php index 25cdf6b..06e3775 100644 --- a/test/app/Http/Controllers/ForumController.php +++ b/test/app/Http/Controllers/ForumController.php @@ -2,7 +2,6 @@ namespace App\Http\Controllers; -use Illuminate\Http\Request; use App\Models\Forum; class ForumController extends Controller diff --git a/test/app/Http/Controllers/PostController.php b/test/app/Http/Controllers/PostController.php index e40bc59..d844eb5 100644 --- a/test/app/Http/Controllers/PostController.php +++ b/test/app/Http/Controllers/PostController.php @@ -2,7 +2,6 @@ namespace App\Http\Controllers; -use Illuminate\Http\Request; use App\Models\Post; use App\Models\Topic; @@ -22,5 +21,4 @@ class PostController extends ChildController * @var null|BaseTransformer The transformer this controller should use, if overriding the model & default */ public static $transformer = null; - } diff --git a/test/app/Http/Controllers/RoleController.php b/test/app/Http/Controllers/RoleController.php index 0956901..19ecc15 100644 --- a/test/app/Http/Controllers/RoleController.php +++ b/test/app/Http/Controllers/RoleController.php @@ -2,7 +2,6 @@ namespace App\Http\Controllers; -use Illuminate\Http\Request; use App\Models\Role; class RoleController extends Controller diff --git a/test/app/Http/Controllers/TagController.php b/test/app/Http/Controllers/TagController.php index 3c95258..2eebd9d 100644 --- a/test/app/Http/Controllers/TagController.php +++ b/test/app/Http/Controllers/TagController.php @@ -2,7 +2,6 @@ namespace App\Http\Controllers; -use Illuminate\Http\Request; use App\Models\Tag; class TagController extends Controller diff --git a/test/app/Http/Controllers/TopicController.php b/test/app/Http/Controllers/TopicController.php index 502ff7e..d8d7066 100644 --- a/test/app/Http/Controllers/TopicController.php +++ b/test/app/Http/Controllers/TopicController.php @@ -2,12 +2,12 @@ namespace App\Http\Controllers; +use App\Models\Forum; use App\Models\Post; -use App\Services\RestfulService; -use Illuminate\Http\Request; use App\Models\Topic; -use App\Models\Forum; use App\Services\PostService; +use App\Services\RestfulService; +use Illuminate\Http\Request; class TopicController extends ChildController { @@ -33,8 +33,9 @@ class TopicController extends ChildController /** * TopicController constructor. + * * @param RestfulService $restfulService - * @param PostService $postService + * @param PostService $postService */ public function __construct(RestfulService $restfulService, PostService $postService) { @@ -44,8 +45,9 @@ public function __construct(RestfulService $restfulService, PostService $postSer } /** - * @param $parentUuid + * @param $parentUuid * @param Request $request + * * @return \Dingo\Api\Http\Response */ /* diff --git a/test/app/Http/Kernel.php b/test/app/Http/Kernel.php index 8cb8a0c..0b019e5 100644 --- a/test/app/Http/Kernel.php +++ b/test/app/Http/Kernel.php @@ -52,16 +52,16 @@ class Kernel extends HttpKernel * @var array */ protected $routeMiddleware = [ - 'auth' => \App\Http\Middleware\Authenticate::class, - 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, - 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, + 'auth' => \App\Http\Middleware\Authenticate::class, + 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, + 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, - 'can' => \Illuminate\Auth\Middleware\Authorize::class, - 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, - 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, - 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, - 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, - 'snake_case' => \Specialtactics\L5Api\Http\Middleware\SnakeCaseInputParameterKeys::class, - 'check_role' => \Specialtactics\L5Api\Http\Middleware\CheckUserRole::class, + 'can' => \Illuminate\Auth\Middleware\Authorize::class, + 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, + 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, + 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, + 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, + 'snake_case' => \Specialtactics\L5Api\Http\Middleware\SnakeCaseInputParameterKeys::class, + 'check_role' => \Specialtactics\L5Api\Http\Middleware\CheckUserRole::class, ]; } diff --git a/test/app/Http/Middleware/Authenticate.php b/test/app/Http/Middleware/Authenticate.php index ab38cae..7271afc 100644 --- a/test/app/Http/Middleware/Authenticate.php +++ b/test/app/Http/Middleware/Authenticate.php @@ -10,7 +10,8 @@ class Authenticate extends Middleware /** * Get the path the user should be redirected to when they are not authenticated. * - * @param \Illuminate\Http\Request $request + * @param \Illuminate\Http\Request $request + * * @return string */ protected function redirectTo($request) diff --git a/test/app/Http/Middleware/RedirectIfAuthenticated.php b/test/app/Http/Middleware/RedirectIfAuthenticated.php index e4cec9c..afe1c26 100644 --- a/test/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/test/app/Http/Middleware/RedirectIfAuthenticated.php @@ -10,9 +10,10 @@ class RedirectIfAuthenticated /** * Handle an incoming request. * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * @param string|null $guard + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param string|null $guard + * * @return mixed */ public function handle($request, Closure $next, $guard = null) diff --git a/test/app/Http/Middleware/TrustProxies.php b/test/app/Http/Middleware/TrustProxies.php index f86ba4b..2b61e63 100644 --- a/test/app/Http/Middleware/TrustProxies.php +++ b/test/app/Http/Middleware/TrustProxies.php @@ -2,8 +2,8 @@ namespace App\Http\Middleware; -use Illuminate\Http\Request; use Illuminate\Http\Middleware\TrustProxies as Middleware; +use Illuminate\Http\Request; class TrustProxies extends Middleware { diff --git a/test/app/Models/BaseModel.php b/test/app/Models/BaseModel.php index 82f15a9..a57d158 100644 --- a/test/app/Models/BaseModel.php +++ b/test/app/Models/BaseModel.php @@ -7,6 +7,6 @@ class BaseModel extends RestfulModel { /** - * Add your own base customisation here + * Add your own base customisation here. */ } diff --git a/test/app/Models/Forum.php b/test/app/Models/Forum.php index df16294..6b05ae6 100644 --- a/test/app/Models/Forum.php +++ b/test/app/Models/Forum.php @@ -7,7 +7,7 @@ class Forum extends BaseModel { /** - * Types of "forum" entity + * Types of "forum" entity. */ const TYPE_FORUM = 'forum'; const TYPE_CATEGORY = 'category'; @@ -38,14 +38,14 @@ class Forum extends BaseModel protected $hidden = []; /** - * Return the validation rules for this model + * Return the validation rules for this model. * * @return array Rules */ public function getValidationRules() { return [ - 'name' => 'required|string|unique:forums', + 'name' => 'required|string|unique:forums', 'description' => 'string', ]; } diff --git a/test/app/Models/Policies/BasePolicy.php b/test/app/Models/Policies/BasePolicy.php index aee6164..fcd6564 100644 --- a/test/app/Models/Policies/BasePolicy.php +++ b/test/app/Models/Policies/BasePolicy.php @@ -2,16 +2,17 @@ namespace App\Models\Policies; -use Specialtactics\L5Api\Policies\RestfulModelPolicy; use App\Models\User; +use Specialtactics\L5Api\Policies\RestfulModelPolicy; class BasePolicy extends RestfulModelPolicy { /** - * Process 'global' authorisation rules + * Process 'global' authorisation rules. * * @param $user * @param $ability + * * @return bool */ public function before(User $user, $ability) diff --git a/test/app/Models/Policies/ForumPolicy.php b/test/app/Models/Policies/ForumPolicy.php index 87b9a1f..e1813aa 100644 --- a/test/app/Models/Policies/ForumPolicy.php +++ b/test/app/Models/Policies/ForumPolicy.php @@ -2,15 +2,16 @@ namespace App\Models\Policies; -use App\Models\User; use App\Models\Forum; +use App\Models\User; class ForumPolicy extends BasePolicy { /** * Determine whether the user can create Forum. * - * @param \App\Models\User $user + * @param \App\Models\User $user + * * @return mixed */ public function create(User $user) @@ -21,7 +22,8 @@ public function create(User $user) /** * Determine whether the user can create Forum. * - * @param \App\Models\User $user + * @param \App\Models\User $user + * * @return mixed */ public function viewAll(User $user) @@ -32,8 +34,9 @@ public function viewAll(User $user) /** * Determine whether the user can view the Forum. * - * @param \App\Models\User $user - * @param \App\Models\Forum $forum + * @param \App\Models\User $user + * @param \App\Models\Forum $forum + * * @return mixed */ public function view(User $user, Forum $forum) @@ -44,8 +47,9 @@ public function view(User $user, Forum $forum) /** * Determine whether the user can update the Forum. * - * @param \App\Models\User $user - * @param \App\Models\Forum $forum + * @param \App\Models\User $user + * @param \App\Models\Forum $forum + * * @return mixed */ public function update(User $user, Forum $forum) @@ -56,8 +60,9 @@ public function update(User $user, Forum $forum) /** * Determine whether the user can delete the Forum. * - * @param \App\Models\User $user - * @param \App\Models\Forum $forum + * @param \App\Models\User $user + * @param \App\Models\Forum $forum + * * @return mixed */ public function delete(User $user, Forum $forum) @@ -68,20 +73,23 @@ public function delete(User $user, Forum $forum) /** * Determine whether the user owns the Forum. * - * @param \App\Models\User $user - * @param \App\Models\Forum $forum + * @param \App\Models\User $user + * @param \App\Models\Forum $forum + * * @return mixed */ - public function own(User $user, Forum $forum) { + public function own(User $user, Forum $forum) + { return true; } /** * This function can be used to add conditions to the query builder, - * which will specify the user's ownership of the model for the get collection query of this model + * which will specify the user's ownership of the model for the get collection query of this model. * - * @param \App\Models\User $user A user object against which to construct the query. By default, the currently logged in user is used. + * @param \App\Models\User $user A user object against which to construct the query. By default, the currently logged in user is used. * @param \Illuminate\Database\Eloquent\Builder $query + * * @return \Illuminate\Database\Eloquent\Builder|null */ public function qualifyCollectionQueryWithUser(User $user, $query) diff --git a/test/app/Models/Policies/PostPolicy.php b/test/app/Models/Policies/PostPolicy.php index f817b76..3714c2e 100644 --- a/test/app/Models/Policies/PostPolicy.php +++ b/test/app/Models/Policies/PostPolicy.php @@ -2,15 +2,16 @@ namespace App\Models\Policies; -use App\Models\User; use App\Models\Post; +use App\Models\User; class PostPolicy extends BasePolicy { /** * Determine whether the user can create Post. * - * @param \App\Models\User $user + * @param \App\Models\User $user + * * @return mixed */ public function create(User $user) @@ -21,8 +22,9 @@ public function create(User $user) /** * Determine whether the user can view the Post. * - * @param \App\Models\User $user - * @param \App\Models\Post $post + * @param \App\Models\User $user + * @param \App\Models\Post $post + * * @return mixed */ public function view(User $user, Post $post) @@ -33,8 +35,9 @@ public function view(User $user, Post $post) /** * Determine whether the user can update the Post. * - * @param \App\Models\User $user - * @param \App\Models\Post $post + * @param \App\Models\User $user + * @param \App\Models\Post $post + * * @return mixed */ public function update(User $user, Post $post) @@ -45,8 +48,9 @@ public function update(User $user, Post $post) /** * Determine whether the user can delete the Post. * - * @param \App\Models\User $user - * @param \App\Models\Post $post + * @param \App\Models\User $user + * @param \App\Models\Post $post + * * @return mixed */ public function delete(User $user, Post $post) @@ -57,20 +61,23 @@ public function delete(User $user, Post $post) /** * Determine whether the user owns the Post. * - * @param \App\Models\User $user - * @param \App\Models\Post $post + * @param \App\Models\User $user + * @param \App\Models\Post $post + * * @return mixed */ - public function own(User $user, Post $post) { + public function own(User $user, Post $post) + { return $post->author_id == $user->user_id; } /** * This function can be used to add conditions to the query builder, - * which will specify the user's ownership of the model for the get collection query of this model + * which will specify the user's ownership of the model for the get collection query of this model. * - * @param \App\Models\User $user A user object against which to construct the query. By default, the currently logged in user is used. + * @param \App\Models\User $user A user object against which to construct the query. By default, the currently logged in user is used. * @param \Illuminate\Database\Eloquent\Builder $query + * * @return \Illuminate\Database\Eloquent\Builder|null */ public function qualifyCollectionQueryWithUser(User $user, $query) diff --git a/test/app/Models/Policies/TagPolicy.php b/test/app/Models/Policies/TagPolicy.php index a1bc521..e44ab4c 100644 --- a/test/app/Models/Policies/TagPolicy.php +++ b/test/app/Models/Policies/TagPolicy.php @@ -2,15 +2,16 @@ namespace App\Models\Policies; -use App\Models\User; use App\Models\Tag; +use App\Models\User; class TagPolicy extends BasePolicy { /** * Determine whether the user can create tag. * - * @param \App\Models\User $user + * @param \App\Models\User $user + * * @return mixed */ public function create(User $user) @@ -21,8 +22,9 @@ public function create(User $user) /** * Determine whether the user can view the tag. * - * @param \App\Models\User $user - * @param \App\Models\Tag $tag + * @param \App\Models\User $user + * @param \App\Models\Tag $tag + * * @return mixed */ public function view(User $user, Tag $tag) @@ -33,8 +35,9 @@ public function view(User $user, Tag $tag) /** * Determine whether the user can update the tag. * - * @param \App\Models\User $user - * @param \App\Models\Tag $tag + * @param \App\Models\User $user + * @param \App\Models\Tag $tag + * * @return mixed */ public function update(User $user, Tag $tag) @@ -45,8 +48,9 @@ public function update(User $user, Tag $tag) /** * Determine whether the user can delete the tag. * - * @param \App\Models\User $user - * @param \App\Models\Tag $tag + * @param \App\Models\User $user + * @param \App\Models\Tag $tag + * * @return mixed */ public function delete(User $user, Tag $tag) @@ -57,20 +61,23 @@ public function delete(User $user, Tag $tag) /** * Determine whether the user owns the tag. * - * @param \App\Models\User $user - * @param \App\Models\Tag $tag + * @param \App\Models\User $user + * @param \App\Models\Tag $tag + * * @return mixed */ - public function own(User $user, Tag $tag) { + public function own(User $user, Tag $tag) + { // } /** * This function can be used to add conditions to the query builder, - * which will specify the user's ownership of the model for the get collection query of this model + * which will specify the user's ownership of the model for the get collection query of this model. * - * @param \App\Models\User $user A user object against which to construct the query. By default, the currently logged in user is used. + * @param \App\Models\User $user A user object against which to construct the query. By default, the currently logged in user is used. * @param \Illuminate\Database\Eloquent\Builder $query + * * @return \Illuminate\Database\Eloquent\Builder|null */ public function qualifyCollectionQueryWithUser(User $user, $query) diff --git a/test/app/Models/Policies/TopicPolicy.php b/test/app/Models/Policies/TopicPolicy.php index c1ff6b8..b5255e5 100644 --- a/test/app/Models/Policies/TopicPolicy.php +++ b/test/app/Models/Policies/TopicPolicy.php @@ -2,15 +2,16 @@ namespace App\Models\Policies; -use App\Models\User; use App\Models\Topic; +use App\Models\User; class TopicPolicy extends BasePolicy { /** * Determine whether the user can create Topic. * - * @param \App\Models\User $user + * @param \App\Models\User $user + * * @return mixed */ public function create(User $user) @@ -21,8 +22,9 @@ public function create(User $user) /** * Determine whether the user can view the Topic. * - * @param \App\Models\User $user - * @param \App\Models\Topic $topic + * @param \App\Models\User $user + * @param \App\Models\Topic $topic + * * @return mixed */ public function view(User $user, Topic $topic) @@ -33,8 +35,9 @@ public function view(User $user, Topic $topic) /** * Determine whether the user can update the Topic. * - * @param \App\Models\User $user - * @param \App\Models\Topic $topic + * @param \App\Models\User $user + * @param \App\Models\Topic $topic + * * @return mixed */ public function update(User $user, Topic $topic) @@ -45,8 +48,9 @@ public function update(User $user, Topic $topic) /** * Determine whether the user can delete the Topic. * - * @param \App\Models\User $user - * @param \App\Models\Topic $topic + * @param \App\Models\User $user + * @param \App\Models\Topic $topic + * * @return mixed */ public function delete(User $user, Topic $topic) @@ -57,20 +61,23 @@ public function delete(User $user, Topic $topic) /** * Determine whether the user owns the Topic. * - * @param \App\Models\User $user - * @param \App\Models\Topic $topic + * @param \App\Models\User $user + * @param \App\Models\Topic $topic + * * @return mixed */ - public function own(User $user, Topic $topic) { + public function own(User $user, Topic $topic) + { return true; } /** * This function can be used to add conditions to the query builder, - * which will specify the user's ownership of the model for the get collection query of this model + * which will specify the user's ownership of the model for the get collection query of this model. * - * @param \App\Models\User $user A user object against which to construct the query. By default, the currently logged in user is used. + * @param \App\Models\User $user A user object against which to construct the query. By default, the currently logged in user is used. * @param \Illuminate\Database\Eloquent\Builder $query + * * @return \Illuminate\Database\Eloquent\Builder|null */ public function qualifyCollectionQueryWithUser(User $user, $query) diff --git a/test/app/Models/Post.php b/test/app/Models/Post.php index d82e300..52619d1 100644 --- a/test/app/Models/Post.php +++ b/test/app/Models/Post.php @@ -32,7 +32,7 @@ class Post extends BaseModel protected $hidden = []; /** - * Return the validation rules for this model + * Return the validation rules for this model. * * @return array Rules */ @@ -44,7 +44,7 @@ public function getValidationRules() } /** - * Boot the model + * Boot the model. * * Add various functionality in the model lifecycle hooks */ diff --git a/test/app/Models/Role.php b/test/app/Models/Role.php index 5388e04..56f9da2 100644 --- a/test/app/Models/Role.php +++ b/test/app/Models/Role.php @@ -5,7 +5,7 @@ class Role extends BaseModel { /** - * Role constants + * Role constants. */ public const ROLE_ADMIN = 'admin'; public const ROLE_REGULAR = 'regular'; diff --git a/test/app/Models/Tag.php b/test/app/Models/Tag.php index b22a69a..9fcc034 100644 --- a/test/app/Models/Tag.php +++ b/test/app/Models/Tag.php @@ -32,7 +32,7 @@ class Tag extends BaseModel protected $hidden = []; /** - * Return the validation rules for this model + * Return the validation rules for this model. * * @return array Rules */ @@ -40,5 +40,4 @@ public function getValidationRules() { return []; } - } diff --git a/test/app/Models/Topic.php b/test/app/Models/Topic.php index f3e6b50..cbf0c22 100644 --- a/test/app/Models/Topic.php +++ b/test/app/Models/Topic.php @@ -32,7 +32,7 @@ class Topic extends BaseModel protected $hidden = []; /** - * Return the validation rules for this model + * Return the validation rules for this model. * * @return array Rules */ @@ -59,7 +59,7 @@ public function forum() } /** - * Boot the model + * Boot the model. * * Add various functionality in the model lifecycle hooks */ diff --git a/test/app/Models/User.php b/test/app/Models/User.php index 697768d..56937ad 100644 --- a/test/app/Models/User.php +++ b/test/app/Models/User.php @@ -2,16 +2,15 @@ namespace App\Models; -use Illuminate\Notifications\Notifiable; +use Hash; use Illuminate\Auth\Authenticatable; use Illuminate\Auth\Passwords\CanResetPassword; -use Illuminate\Foundation\Auth\Access\Authorizable; -use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; +use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; +use Illuminate\Foundation\Auth\Access\Authorizable; +use Illuminate\Notifications\Notifiable; use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject; -use Hash; -use App\Models\Role; class User extends BaseModel implements AuthenticatableContract, @@ -19,7 +18,10 @@ class User extends BaseModel implements CanResetPasswordContract, JWTSubject { - use Authenticatable, Authorizable, CanResetPassword, Notifiable; + use Authenticatable; + use Authorizable; + use CanResetPassword; + use Notifiable; /** * @var int Auto increments integer key @@ -37,11 +39,11 @@ class User extends BaseModel implements * @var array */ protected $fillable = [ - 'name', 'email', 'password', 'primary_role' + 'name', 'email', 'password', 'primary_role', ]; /** - * The attributes that should be hidden for arrays and API output + * The attributes that should be hidden for arrays and API output. * * @var array */ @@ -50,7 +52,7 @@ class User extends BaseModel implements ]; /** - * Model's boot function + * Model's boot function. */ public static function boot() { @@ -65,40 +67,44 @@ public static function boot() } /** - * Return the validation rules for this model + * Return the validation rules for this model. * * @return array Rules */ - public function getValidationRules() { + public function getValidationRules() + { return [ - 'email' => 'email|max:255|unique:users', - 'name' => 'required|min:3', + 'email' => 'email|max:255|unique:users', + 'name' => 'required|min:3', 'password' => 'required|min:6', ]; } /** - * User's primary role + * User's primary role. * * @return \Illuminate\Database\Eloquent\Relations\belongsTo */ - public function primaryRole() { + public function primaryRole() + { return $this->belongsTo(Role::class, 'primary_role'); } /** - * User's secondary roles + * User's secondary roles. * * @return \Illuminate\Database\Eloquent\Relations\belongsToMany */ - public function roles() { + public function roles() + { return $this->belongsToMany(Role::class, 'user_roles', 'user_id', 'role_id'); } /** - * Get all user's roles + * Get all user's roles. */ - public function getRoles() { + public function getRoles() + { $allRoles = array_merge( [ $this->primaryRole->name, @@ -114,7 +120,8 @@ public function getRoles() { * * @return bool */ - public function isAdmin() { + public function isAdmin() + { return $this->primaryRole->name == Role::ROLE_ADMIN; } @@ -139,10 +146,10 @@ public function getJWTCustomClaims() { return [ 'user' => [ - 'id' => $this->getKey(), - 'name' => $this->name, + 'id' => $this->getKey(), + 'name' => $this->name, 'primaryRole' => $this->primaryRole->name, - ] + ], ]; } diff --git a/test/app/Providers/AppServiceProvider.php b/test/app/Providers/AppServiceProvider.php index 575acd5..20c992f 100644 --- a/test/app/Providers/AppServiceProvider.php +++ b/test/app/Providers/AppServiceProvider.php @@ -2,9 +2,8 @@ namespace App\Providers; -use Illuminate\Support\ServiceProvider; use App\Exceptions\ApiExceptionHandler; -use Config; +use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { @@ -29,7 +28,7 @@ public function register() } /** - * Register the exception handler - extends the Dingo one + * Register the exception handler - extends the Dingo one. * * @return void */ diff --git a/test/app/Providers/AuthServiceProvider.php b/test/app/Providers/AuthServiceProvider.php index 178cae5..c7fe934 100644 --- a/test/app/Providers/AuthServiceProvider.php +++ b/test/app/Providers/AuthServiceProvider.php @@ -8,7 +8,6 @@ use App\Policies\ForumPolicy; use App\Policies\PostPolicy; use App\Policies\TopicPolicy; -use Illuminate\Support\Facades\Gate; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider diff --git a/test/app/Providers/BroadcastServiceProvider.php b/test/app/Providers/BroadcastServiceProvider.php index 352cce4..395c518 100644 --- a/test/app/Providers/BroadcastServiceProvider.php +++ b/test/app/Providers/BroadcastServiceProvider.php @@ -2,8 +2,8 @@ namespace App\Providers; -use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Broadcast; +use Illuminate\Support\ServiceProvider; class BroadcastServiceProvider extends ServiceProvider { diff --git a/test/app/Providers/EventServiceProvider.php b/test/app/Providers/EventServiceProvider.php index fca6152..f106ba4 100644 --- a/test/app/Providers/EventServiceProvider.php +++ b/test/app/Providers/EventServiceProvider.php @@ -2,8 +2,8 @@ namespace App\Providers; -use Illuminate\Support\Facades\Event; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; +use Illuminate\Support\Facades\Event; class EventServiceProvider extends ServiceProvider { diff --git a/test/app/Providers/RouteServiceProvider.php b/test/app/Providers/RouteServiceProvider.php index 372811c..a1063e5 100644 --- a/test/app/Providers/RouteServiceProvider.php +++ b/test/app/Providers/RouteServiceProvider.php @@ -2,8 +2,8 @@ namespace App\Providers; -use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; +use Illuminate\Support\Facades\Route; class RouteServiceProvider extends ServiceProvider { diff --git a/test/app/Providers/TelescopeServiceProvider.php b/test/app/Providers/TelescopeServiceProvider.php index 73d5de0..cb58487 100644 --- a/test/app/Providers/TelescopeServiceProvider.php +++ b/test/app/Providers/TelescopeServiceProvider.php @@ -2,9 +2,9 @@ namespace App\Providers; -use Laravel\Telescope\Telescope; use Illuminate\Support\Facades\Gate; use Laravel\Telescope\IncomingEntry; +use Laravel\Telescope\Telescope; use Laravel\Telescope\TelescopeApplicationServiceProvider; class TelescopeServiceProvider extends TelescopeApplicationServiceProvider diff --git a/test/app/Services/PostService.php b/test/app/Services/PostService.php index 27c71a7..c7852f5 100644 --- a/test/app/Services/PostService.php +++ b/test/app/Services/PostService.php @@ -2,8 +2,8 @@ namespace App\Services; -use App\Models\Topic; use App\Models\Post; +use App\Models\Topic; class PostService { @@ -14,6 +14,7 @@ class PostService /** * PostService constructor. + * * @param RestfulService $restfulService */ public function __construct(RestfulService $restfulService) @@ -22,17 +23,18 @@ public function __construct(RestfulService $restfulService) } /** - * Creates a new post, and returns it + * Creates a new post, and returns it. * * @param Topic $topic * @param array $data + * * @return Post $post */ public function createPost(Topic $topic, array $data) { $fillData = $data + [$topic->getKeyName() => $topic->getKey()]; - $post = new Post; + $post = new Post(); $this->restfulService->validateResource($post, $fillData); @@ -40,4 +42,4 @@ public function createPost(Topic $topic, array $data) return $post; } -} \ No newline at end of file +} diff --git a/test/app/Services/RestfulService.php b/test/app/Services/RestfulService.php index 63dde05..faf9588 100644 --- a/test/app/Services/RestfulService.php +++ b/test/app/Services/RestfulService.php @@ -2,16 +2,13 @@ namespace App\Services; -use \Specialtactics\L5Api\Services\RestfulService as VendorRestfulService; +use Specialtactics\L5Api\Services\RestfulService as VendorRestfulService; /** - * Class RestfulService + * Class RestfulService. * * Your can extend the RestfulService functionality here - * - * @package App\Services */ class RestfulService extends VendorRestfulService { - -} \ No newline at end of file +} diff --git a/test/app/Transformers/BaseTransformer.php b/test/app/Transformers/BaseTransformer.php index e82543d..3bf8d16 100644 --- a/test/app/Transformers/BaseTransformer.php +++ b/test/app/Transformers/BaseTransformer.php @@ -6,5 +6,4 @@ class BaseTransformer extends RestfulTransformer { - -} \ No newline at end of file +} diff --git a/test/config/api.php b/test/config/api.php index 8a10eae..7493ccc 100644 --- a/test/config/api.php +++ b/test/config/api.php @@ -137,11 +137,11 @@ */ 'errorFormat' => [ - 'message' => ':message', - 'errors' => ':errors', - 'code' => ':code', + 'message' => ':message', + 'errors' => ':errors', + 'code' => ':code', 'statusCode' => ':status_code', - 'debug' => ':debug', + 'debug' => ':debug', ], /* @@ -224,10 +224,10 @@ 'json' => [ 'pretty_print' => env('API_JSON_FORMAT_PRETTY_PRINT_ENABLED', false), 'indent_style' => env('API_JSON_FORMAT_INDENT_STYLE', 'space'), - 'indent_size' => env('API_JSON_FORMAT_INDENT_SIZE', 2), + 'indent_size' => env('API_JSON_FORMAT_INDENT_SIZE', 2), ], - 'caseType' => env ('API_CASE_TYPE', 'camel-case'), + 'caseType' => env('API_CASE_TYPE', 'camel-case'), ], ]; diff --git a/test/config/auth.php b/test/config/auth.php index 966d5ed..c948582 100644 --- a/test/config/auth.php +++ b/test/config/auth.php @@ -14,7 +14,7 @@ */ 'defaults' => [ - 'guard' => 'api', + 'guard' => 'api', 'passwords' => 'users', ], @@ -37,12 +37,12 @@ 'guards' => [ 'web' => [ - 'driver' => 'session', + 'driver' => 'session', 'provider' => 'users', ], 'api' => [ - 'driver' => 'jwt', + 'driver' => 'jwt', 'provider' => 'users', ], ], @@ -67,7 +67,7 @@ 'providers' => [ 'users' => [ 'driver' => 'eloquent', - 'model' => App\Models\User::class, + 'model' => App\Models\User::class, ], // 'users' => [ @@ -94,8 +94,8 @@ 'passwords' => [ 'users' => [ 'provider' => 'users', - 'table' => 'password_resets', - 'expire' => 60, + 'table' => 'password_resets', + 'expire' => 60, ], ], diff --git a/test/copy-over-deps.php b/test/copy-over-deps.php index 25fd717..4ac6022 100755 --- a/test/copy-over-deps.php +++ b/test/copy-over-deps.php @@ -17,14 +17,14 @@ // Rename file $newFileName = str_replace('_create_', '_create_test_', $filename); - rename($migrationsDir . '/' . $filename, $migrationsDir . '/' . $newFileName); + rename($migrationsDir.'/'.$filename, $migrationsDir.'/'.$newFileName); // Rename class - $contents = file_get_contents($migrationsDir . '/' . $newFileName); + $contents = file_get_contents($migrationsDir.'/'.$newFileName); // Get classname $newContents = str_replace('class Create', 'class CreateTest', $contents); - file_put_contents($migrationsDir . '/' . $newFileName, $newContents); + file_put_contents($migrationsDir.'/'.$newFileName, $newContents); } } diff --git a/test/database/factories/UserFactory.php b/test/database/factories/UserFactory.php index 2be906c..e400a14 100644 --- a/test/database/factories/UserFactory.php +++ b/test/database/factories/UserFactory.php @@ -1,7 +1,7 @@ define(App\Models\User::class, function (Faker $faker) { return [ - 'name' => $faker->name, - 'email' => $faker->unique()->safeEmail, - 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret + 'name' => $faker->name, + 'email' => $faker->unique()->safeEmail, + 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret 'remember_token' => Str::random(10), ]; }); diff --git a/test/database/migrations/2018_04_30_000000_create_test_roles_table.php b/test/database/migrations/2018_04_30_000000_create_test_roles_table.php index a596d91..874283b 100644 --- a/test/database/migrations/2018_04_30_000000_create_test_roles_table.php +++ b/test/database/migrations/2018_04_30_000000_create_test_roles_table.php @@ -1,8 +1,8 @@ 'Test Forum', ]); } /** - * Run seeds to be ran only on production environments + * Run seeds to be ran only on production environments. * * @return mixed */ - public function runProduction() { - + public function runProduction() + { } /** - * Run seeds to be ran on every environment (including production) + * Run seeds to be ran on every environment (including production). * * @return mixed */ - public function runAlways() { - + public function runAlways() + { } } diff --git a/test/database/seeds/PostsSeeder.php b/test/database/seeds/PostsSeeder.php index ac93acd..6552d9c 100644 --- a/test/database/seeds/PostsSeeder.php +++ b/test/database/seeds/PostsSeeder.php @@ -1,45 +1,45 @@ $topic->getKey(), - 'topic' => implode(' ', $this->faker->words(3)), - 'content' => $this->faker->paragraph(3), + 'topic' => implode(' ', $this->faker->words(3)), + 'content' => $this->faker->paragraph(3), ]); } } } /** - * Run seeds to be ran only on production environments + * Run seeds to be ran only on production environments. * * @return mixed */ - public function runProduction() { - + public function runProduction() + { } /** - * Run seeds to be ran on every environment (including production) + * Run seeds to be ran on every environment (including production). * * @return mixed */ - public function runAlways() { - + public function runAlways() + { } } diff --git a/test/database/seeds/RoleTableSeeder.php b/test/database/seeds/RoleTableSeeder.php index 80a997b..d828c63 100644 --- a/test/database/seeds/RoleTableSeeder.php +++ b/test/database/seeds/RoleTableSeeder.php @@ -4,22 +4,24 @@ class RoleTableSeeder extends BaseSeeder { - public function runAlways() { + public function runAlways() + { Role::firstOrCreate([ - 'name' => 'admin', + 'name' => 'admin', 'description' => 'Administrator Users', ]); Role::firstOrCreate([ - 'name' => 'regular', + 'name' => 'regular', 'description' => 'Regular Users', ]); } - public function runFake() { - for ($i = 0; $i < 10; ++$i) { + public function runFake() + { + for ($i = 0; $i < 10; $i++) { Role::firstOrCreate([ - 'name' => $this->faker->unique()->word(), + 'name' => $this->faker->unique()->word(), 'description' => $this->faker->sentence(), ]); } @@ -27,19 +29,21 @@ public function runFake() { /** * Get a collection of random roles - * Remove duplicates to prevent SQL errors, also prevent infinite loop in case of not enough roles + * Remove duplicates to prevent SQL errors, also prevent infinite loop in case of not enough roles. * * @param $count int How many roles to get + * * @return Illuminate\Support\Collection */ - public static function getRandomRoles($count) { + public static function getRandomRoles($count) + { $roles = Role::all(); $fakeRoles = []; $i = 0; do { - ++$i; + $i++; $fakeRoles[] = $roles->whereNotIn('name', ['admin'])->random(); $fakeRoles = array_unique($fakeRoles); } while (count($fakeRoles) < $count && $i < 50); // Iteration limit diff --git a/test/database/seeds/TagsSeeder.php b/test/database/seeds/TagsSeeder.php index cd03833..59b3539 100644 --- a/test/database/seeds/TagsSeeder.php +++ b/test/database/seeds/TagsSeeder.php @@ -3,29 +3,29 @@ class TagsSeeder extends BaseSeeder { /** - * Run fake seeds - for non production environments + * Run fake seeds - for non production environments. * * @return mixed */ - public function runFake() { - + public function runFake() + { } /** - * Run seeds to be ran only on production environments + * Run seeds to be ran only on production environments. * * @return mixed */ - public function runProduction() { - + public function runProduction() + { } /** - * Run seeds to be ran on every environment (including production) + * Run seeds to be ran on every environment (including production). * * @return mixed */ - public function runAlways() { - + public function runAlways() + { } } diff --git a/test/database/seeds/TopicsSeeder.php b/test/database/seeds/TopicsSeeder.php index 75df6be..8f49a23 100644 --- a/test/database/seeds/TopicsSeeder.php +++ b/test/database/seeds/TopicsSeeder.php @@ -3,29 +3,29 @@ class TopicsSeeder extends BaseSeeder { /** - * Run fake seeds - for non production environments + * Run fake seeds - for non production environments. * * @return mixed */ - public function runFake() { - + public function runFake() + { } /** - * Run seeds to be ran only on production environments + * Run seeds to be ran only on production environments. * * @return mixed */ - public function runProduction() { - + public function runProduction() + { } /** - * Run seeds to be ran on every environment (including production) + * Run seeds to be ran on every environment (including production). * * @return mixed */ - public function runAlways() { - + public function runAlways() + { } } diff --git a/test/database/seeds/UserStorySeeder.php b/test/database/seeds/UserStorySeeder.php index 2d72e20..994273e 100644 --- a/test/database/seeds/UserStorySeeder.php +++ b/test/database/seeds/UserStorySeeder.php @@ -6,11 +6,12 @@ class UserStorySeeder extends BaseSeeder { /** - * Credentials + * Credentials. */ const ADMIN_CREDENTIALS = ['admin@admin.com', 'secret']; - public function runFake() { + public function runFake() + { // Grab all roles for reference $roles = Role::all(); @@ -33,15 +34,14 @@ public function runFake() { $fakeRolesToAssign = RoleTableSeeder::getRandomRoles($fakeRolesToAssignCount); // Assign fake roles to users - for ($i = 0; $i < 5; ++$i) { + for ($i = 0; $i < 5; $i++) { $user = factory(App\Models\User::class)->create([ 'primary_role' => $roles->random()->role_id, ]); - for ($j = 0; $j < count($fakeRolesToAssign); ++$j) { + for ($j = 0; $j < count($fakeRolesToAssign); $j++) { $user->roles()->save($fakeRolesToAssign->shift()); } } - } } diff --git a/test/mocks/AppServiceProvider.php b/test/mocks/AppServiceProvider.php index 5a2b571..7976909 100644 --- a/test/mocks/AppServiceProvider.php +++ b/test/mocks/AppServiceProvider.php @@ -2,9 +2,8 @@ namespace Specialtactics\L5Api\Test\Mocks; -use Illuminate\Support\ServiceProvider; use App\Exceptions\ApiExceptionHandler; -use Config; +use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { @@ -19,7 +18,7 @@ public function register() } /** - * Register the exception handler - extends the Dingo one + * Register the exception handler - extends the Dingo one. * * @return void */ @@ -27,11 +26,11 @@ protected function registerExceptionHandler() { $this->app->singleton('api.exception', function ($app) { return new ApiExceptionHandler($app['Illuminate\Contracts\Debug\ExceptionHandler'], Config('api.errorFormat', [ - 'message' => ':message', - 'errors' => ':errors', - 'code' => ':code', + 'message' => ':message', + 'errors' => ':errors', + 'code' => ':code', 'statusCode' => ':status_code', - 'debug' => ':debug', + 'debug' => ':debug', ]), Config('api.debug', true)); }); } diff --git a/test/mocks/RouteServiceProvider.php b/test/mocks/RouteServiceProvider.php index 23aed1d..50d2b0c 100644 --- a/test/mocks/RouteServiceProvider.php +++ b/test/mocks/RouteServiceProvider.php @@ -2,8 +2,8 @@ namespace Specialtactics\L5Api\Test\Mocks; -use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; +use Illuminate\Support\Facades\Route; class RouteServiceProvider extends ServiceProvider { @@ -50,6 +50,6 @@ protected function mapApiRoutes() { Route::middleware('api') ->namespace($this->namespace) - ->group(__DIR__ . '/../routes/api-routes.php'); + ->group(__DIR__.'/../routes/api-routes.php'); } } diff --git a/test/routes/api-routes.php b/test/routes/api-routes.php index 2f994a2..0879d4e 100644 --- a/test/routes/api-routes.php +++ b/test/routes/api-routes.php @@ -18,20 +18,19 @@ }); /** - * Welcome route - link to any public API documentation here + * Welcome route - link to any public API documentation here. */ Route::get('/', function () { echo 'Welcome to our API'; }); - /** * @var $api \Dingo\Api\Routing\Router */ $api = app('Dingo\Api\Routing\Router'); $api->version('v1', ['middleware' => ['api']], function ($api) { /** - * Authentication + * Authentication. */ $api->group(['prefix' => 'auth'], function ($api) { $api->group(['prefix' => 'jwt'], function ($api) { @@ -40,7 +39,7 @@ }); /** - * Test + * Test. */ $api->group(['prefix' => 'posts'], function ($api) { $api->get('/', 'App\Http\Controllers\PostController@getAll'); @@ -51,13 +50,12 @@ $api->get('/', 'App\Http\Controllers\ForumController@getAll'); }); - /** - * Authenticated routes + * Authenticated routes. */ $api->group(['middleware' => ['api.auth']], function ($api) { /** - * Authentication + * Authentication. */ $api->group(['prefix' => 'auth'], function ($api) { $api->group(['prefix' => 'jwt'], function ($api) { @@ -69,7 +67,7 @@ }); /** - * Users + * Users. */ $api->group(['prefix' => 'users', 'middleware' => 'check_role:admin'], function ($api) { $api->get('/', 'App\Http\Controllers\UserController@getAll'); @@ -81,7 +79,7 @@ }); /** - * Roles + * Roles. */ $api->group(['prefix' => 'roles'], function ($api) { $api->get('/', 'App\Http\Controllers\RoleController@getAll'); diff --git a/test/tests/A/FirstTest.php b/test/tests/A/FirstTest.php index 0ec0267..cbf65a4 100644 --- a/test/tests/A/FirstTest.php +++ b/test/tests/A/FirstTest.php @@ -8,6 +8,7 @@ class FirstTest extends BaseTestCase { /** * @testdox Consumes testing bootstrap time + * * @test */ public function testBootstrapTime() diff --git a/test/tests/Api/Patch/PatchTest.php b/test/tests/Api/Patch/PatchTest.php index c1c1291..c9e9bf7 100644 --- a/test/tests/Api/Patch/PatchTest.php +++ b/test/tests/Api/Patch/PatchTest.php @@ -8,6 +8,7 @@ class PatchTest extends AppTestCase { /** * @testdox Updating a forum description + * * @test */ public function patchForumDescription() @@ -18,7 +19,7 @@ public function patchForumDescription() // First create a forum $jsonResponse = $this->actingAsAdmin() ->json('POST', '/forums', [ - 'name' => 'New Forum', + 'name' => 'New Forum', 'description' => $description, ]); @@ -28,7 +29,7 @@ public function patchForumDescription() // Do the patch test $jsonResponse = $this->actingAsAdmin() - ->json('PATCH', '/forums/' . $forumId, [ + ->json('PATCH', '/forums/'.$forumId, [ 'description' => $differentDescription, ]); diff --git a/test/tests/AppTestCase.php b/test/tests/AppTestCase.php index b0656fe..74d95af 100644 --- a/test/tests/AppTestCase.php +++ b/test/tests/AppTestCase.php @@ -14,24 +14,26 @@ class AppTestCase extends SetupTestApp use DatabaseTransactions; /** - * Set the currently logged in user for the application and Authorization headers for API request + * Set the currently logged in user for the application and Authorization headers for API request. * * @param \Illuminate\Contracts\Auth\Authenticatable - * @param string|null $driver + * @param string|null $driver + * * @return $this */ public function actingAs(UserContract $user, $driver = null) { parent::actingAs($user, $driver); - return $this->withHeader('Authorization', 'Bearer ' . JWTAuth::fromUser($user)); + return $this->withHeader('Authorization', 'Bearer '.JWTAuth::fromUser($user)); } /** * API Test case helper function for setting up - * the request auth header as supplied user + * the request auth header as supplied user. * * @param array $credentials + * * @return $this */ public function actingAsUser($credentials) @@ -48,7 +50,7 @@ public function actingAsUser($credentials) } /** - * API Test case helper function for setting up the request as a logged in admin user + * API Test case helper function for setting up the request as a logged in admin user. * * @return $this */ @@ -60,9 +62,10 @@ public function actingAsAdmin() } /** - * Set the API key-case on the API boilerplate class + * Set the API key-case on the API boilerplate class. * * @param $case + * * @throws \ReflectionException */ public function setAPIKeyCase($case) diff --git a/test/tests/BaseTestCase.php b/test/tests/BaseTestCase.php index 7fb3483..d5a92a3 100644 --- a/test/tests/BaseTestCase.php +++ b/test/tests/BaseTestCase.php @@ -2,19 +2,19 @@ namespace Specialtactics\L5Api\Tests; -use Specialtactics\L5Api\APIBoilerplate; use Orchestra\Testbench\TestCase as OrchestraTestCase; +use Specialtactics\L5Api\APIBoilerplate; /** - * Class BaseTestCase - * @package Specialtactics\L5Api\Tests + * Class BaseTestCase. */ class BaseTestCase extends OrchestraTestCase { /** - * Set the API key-case on the API boilerplate class + * Set the API key-case on the API boilerplate class. * * @param $case + * * @throws \ReflectionException */ public function setAPIKeyCase($case) diff --git a/test/tests/Fixtures/Models/ModelWithCasts.php b/test/tests/Fixtures/Models/ModelWithCasts.php index e3cdedb..541b32b 100644 --- a/test/tests/Fixtures/Models/ModelWithCasts.php +++ b/test/tests/Fixtures/Models/ModelWithCasts.php @@ -20,6 +20,6 @@ class ModelWithCasts extends RestfulModel * @var array Casts */ protected $casts = [ - 'array_attribute' => 'array' + 'array_attribute' => 'array', ]; } diff --git a/test/tests/SetupTestApp.php b/test/tests/SetupTestApp.php index 5d5e40f..4886f77 100644 --- a/test/tests/SetupTestApp.php +++ b/test/tests/SetupTestApp.php @@ -2,36 +2,34 @@ namespace Specialtactics\L5Api\Tests; -use JWTAuth; use Mockery; /** - * This class sets up the necessary testing infrastructure + * This class sets up the necessary testing infrastructure. * * Class TestingSetup - * @package Specialtactics\L5Api\Tests */ class SetupTestApp extends BaseTestCase { /** - * Set up the testing environment + * Set up the testing environment. */ protected function setUp(): void { parent::setUp(); // Load migrations for tests - $this->loadMigrationsFrom(__DIR__ . '/../database/migrations'); + $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); // Load factories for tests - $this->withFactories(__DIR__ . '/../database/factories'); + $this->withFactories(__DIR__.'/../database/factories'); // Migrate and seed $this->artisan('migrate', ['--database' => 'testing', '--seed' => true]); } /** - * Tear down the testing environment + * Tear down the testing environment. */ public function tearDown(): void { @@ -41,7 +39,8 @@ public function tearDown(): void /** * Define environment setup. * - * @param \Illuminate\Foundation\Application $app + * @param \Illuminate\Foundation\Application $app + * * @return void */ protected function getEnvironmentSetUp($app) @@ -55,15 +54,16 @@ protected function getEnvironmentSetUp($app) ]); // Set the testing config files to be used by the test app - $app['config']->set('api', include __DIR__ . '/../config/api.php'); - $app['config']->set('auth', include __DIR__ . '/../config/auth.php'); - $app['config']->set('jwt', include __DIR__ . '/../config/jwt.php'); + $app['config']->set('api', include __DIR__.'/../config/api.php'); + $app['config']->set('auth', include __DIR__.'/../config/auth.php'); + $app['config']->set('jwt', include __DIR__.'/../config/jwt.php'); } /** - * Specify which service providers to use for the testing app + * Specify which service providers to use for the testing app. * * @param \Illuminate\Foundation\Application $app + * * @return array */ protected function getPackageProviders($app) @@ -78,14 +78,16 @@ protected function getPackageProviders($app) } /** - * Specify aliases/facades for the testing app + * Specify aliases/facades for the testing app. * * @param \Illuminate\Foundation\Application $app + * * @return array */ - protected function getPackageAliases($app) { + protected function getPackageAliases($app) + { return [ - 'API' => \Dingo\Api\Facade\API::class, + 'API' => \Dingo\Api\Facade\API::class, 'JWTAuth' => \PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth::class, ]; } @@ -93,7 +95,8 @@ protected function getPackageAliases($app) { /** * Resolve application HTTP Kernel implementation. * - * @param \Illuminate\Foundation\Application $app + * @param \Illuminate\Foundation\Application $app + * * @return void */ protected function resolveApplicationHttpKernel($app) diff --git a/test/tests/Unit/BaseTransformerTest.php b/test/tests/Unit/BaseTransformerTest.php index a35f889..820e9fc 100644 --- a/test/tests/Unit/BaseTransformerTest.php +++ b/test/tests/Unit/BaseTransformerTest.php @@ -12,7 +12,7 @@ class BaseTransformerTest extends AppTestCase { /** * Check that if a model has a primary key called "id", that it will be transformed correctly, - * rather than being unset + * rather than being unset. * * @test */ @@ -20,7 +20,7 @@ public function canTransformModelWithPKOfId() { $model = new ModelWithIdPK(['example_attribute' => 'abc123']); - $transformed = (new RestfulTransformer)->transform($model); + $transformed = (new RestfulTransformer())->transform($model); $this->assertArrayHasKey('id', $transformed); $this->assertArrayHasKey('exampleAttribute', $transformed); @@ -28,7 +28,7 @@ public function canTransformModelWithPKOfId() } /** - * Make sure that an array cast attribute is transformed correctly, in situations when it's blank + * Make sure that an array cast attribute is transformed correctly, in situations when it's blank. * * @test */ @@ -38,7 +38,7 @@ public function nullArrayCastWillBeEmptyArray() // Array attribute is null $model = new ModelWithCasts(['model_with_casts_id' => Uuid::uuid4()->toString(), 'array_attribute' => null]); - $transformed = (new RestfulTransformer)->transform($model); + $transformed = (new RestfulTransformer())->transform($model); $this->assertArrayHasKey('arrayAttribute', $transformed); $this->assertNull($transformed['arrayAttribute']); @@ -47,7 +47,7 @@ public function nullArrayCastWillBeEmptyArray() // Array attribute is empty $model = new ModelWithCasts(['model_with_casts_id' => Uuid::uuid4()->toString(), 'array_attribute' => []]); - $transformed = (new RestfulTransformer)->transform($model); + $transformed = (new RestfulTransformer())->transform($model); $this->assertArrayHasKey('arrayAttribute', $transformed); $this->assertCount(0, $transformed['arrayAttribute']); diff --git a/test/tests/Unit/Helpers/KeyCaseTest.php b/test/tests/Unit/Helpers/KeyCaseTest.php index 88aafeb..1d527a6 100644 --- a/test/tests/Unit/Helpers/KeyCaseTest.php +++ b/test/tests/Unit/Helpers/KeyCaseTest.php @@ -2,38 +2,38 @@ namespace Specialtactics\L5Api\Tests\Unit\Helpers; -use Specialtactics\L5Api\Tests\AppTestCase; use Specialtactics\L5Api\Helpers; +use Specialtactics\L5Api\Tests\AppTestCase; class KeyCaseTest extends AppTestCase { /** - * Keep in mind, there are always default limits on things + * Keep in mind, there are always default limits on things. */ const MAX_DEPTH = 10; /** - * An example nested array containing a multitude of cases (mostly snake) + * An example nested array containing a multitude of cases (mostly snake). */ const MIXED_CASES = [ 'snake_case' => [ - 'something' => 5, + 'something' => 5, 'snake_something' => 6, - 'another_key' => [ - 'easy' => true, + 'another_key' => [ + 'easy' => true, 'harder_one' => false, ], ], 'conversion_rates' => [ 'AUD/USD' => 123.345, - 'GBP' => [ + 'GBP' => [ 'AUD' => 111, ], ], 'alreadyCamelCase' => [ - 'camelCase' => true, + 'camelCase' => true, 'but_also_snake_Case' => true, - 'more-nesting' => [ + 'more-nesting' => [ 'this-is-a-value', 'another_value', 'justAValue', @@ -42,32 +42,32 @@ class KeyCaseTest extends AppTestCase 'WhatAboutThis' => 'interesting', // Edge cases 'why-would-anyone-do-this' => 'who knows, but probably someone will. Perhaps slugs?', - 'Another_weird_One' => true, + 'Another_weird_One' => true, ]; /** - * How the above array should look after the camel case filter + * How the above array should look after the camel case filter. */ const AFTER_CAMEL = [ 'snakeCase' => [ - 'something' => 5, + 'something' => 5, 'snakeSomething' => 6, - 'anotherKey' => [ - 'easy' => true, + 'anotherKey' => [ + 'easy' => true, 'harderOne' => false, ], ], // Components we expect to stay the same 'conversionRates' => [ 'AUD/USD' => 123.345, - 'GBP' => [ + 'GBP' => [ 'AUD' => 111, ], ], 'alreadyCamelCase' => [ - 'camelCase' => true, + 'camelCase' => true, 'butAlsoSnakeCase' => true, - 'moreNesting' => [ + 'moreNesting' => [ 'this-is-a-value', 'another_value', 'justAValue', @@ -76,32 +76,32 @@ class KeyCaseTest extends AppTestCase 'whatAboutThis' => 'interesting', // Edge cases 'whyWouldAnyoneDoThis' => 'who knows, but probably someone will. Perhaps slugs?', - 'anotherWeirdOne' => true, + 'anotherWeirdOne' => true, ]; /** - * How the above array should look after the snake case filter + * How the above array should look after the snake case filter. */ const AFTER_SNAKE = [ 'snake_case' => [ - 'something' => 5, + 'something' => 5, 'snake_something' => 6, - 'another_key' => [ - 'easy' => true, + 'another_key' => [ + 'easy' => true, 'harder_one' => false, ], ], // Components we expect to stay the same 'conversion_rates' => [ 'AUD/USD' => 123.345, - 'GBP' => [ + 'GBP' => [ 'AUD' => 111, ], ], 'already_camel_case' => [ - 'camel_case' => true, + 'camel_case' => true, 'but_also_snake_case' => true, - 'more_nesting' => [ + 'more_nesting' => [ 'this-is-a-value', 'another_value', 'justAValue', @@ -110,7 +110,7 @@ class KeyCaseTest extends AppTestCase 'what_about_this' => 'interesting', // Edge cases 'why_would_anyone_do_this' => 'who knows, but probably someone will. Perhaps slugs?', - 'another_weird_one' => true, + 'another_weird_one' => true, ]; /** @@ -139,5 +139,4 @@ public function keyCaseFiltersShouldProduceConsistentResults() $result = Helpers::camelCaseArrayKeys(Helpers::snakeCaseArrayKeys(Helpers::camelCaseArrayKeys(Helpers::snakeCaseArrayKeys(self::MIXED_CASES)))); $this->assertEqualsWithDelta($result, self::AFTER_CAMEL, self::MAX_DEPTH); } - } diff --git a/test/tests/Unit/JsonFormatterTest.php b/test/tests/Unit/JsonFormatterTest.php index 0096530..dd0439c 100644 --- a/test/tests/Unit/JsonFormatterTest.php +++ b/test/tests/Unit/JsonFormatterTest.php @@ -2,30 +2,29 @@ namespace Specialtactics\L5Api\Tests\Unit; -use Mockery; use Specialtactics\L5Api\APIBoilerplate; -use Specialtactics\L5Api\Tests\AppTestCase; use Specialtactics\L5Api\Http\Response\Format\Json; +use Specialtactics\L5Api\Tests\AppTestCase; class JsonFormatterTest extends AppTestCase { /** - * Check that the JSON Formatter, formats the meta key case correctly + * Check that the JSON Formatter, formats the meta key case correctly. * * @test */ public function formatMetaArrayKeysAccordingToFormat() { - $jsonFormatter = new Json; + $jsonFormatter = new Json(); // Camel $this->setAPIKeyCase(APIBoilerplate::CAMEL_CASE); $content = [ 'do_not_change' => 'Unchanged', - 'meta' => [ + 'meta' => [ 'needs_to_change' => true, - ] + ], ]; $json = $jsonFormatter->formatArray($content); diff --git a/test/tests/Unit/RestfulServiceTest.php b/test/tests/Unit/RestfulServiceTest.php index e3e3018..706caaf 100644 --- a/test/tests/Unit/RestfulServiceTest.php +++ b/test/tests/Unit/RestfulServiceTest.php @@ -4,13 +4,13 @@ use App\Models\BaseModel; use Mockery; -use Specialtactics\L5Api\Tests\BaseTestCase; use Specialtactics\L5Api\Services\RestfulService; +use Specialtactics\L5Api\Tests\BaseTestCase; class RestfulServiceTest extends BaseTestCase { /** - * Test validation when updating a resource, whereby validation has multi-level rule keys + * Test validation when updating a resource, whereby validation has multi-level rule keys. * * @test */ @@ -21,16 +21,16 @@ public function getRelevantValidationRulesConsidersMultiLevelRuleKeys() // Example rules $mockedModel = Mockery::Mock(BaseModel::class)->makePartial(); $mockedModel->shouldReceive('getValidationRulesUpdating')->andReturn([ - 'unrelated_attribute' => 'required', - 'array_attribute' => 'required|array', - 'array_attribute.uuid_key' => 'required|uuid' + 'unrelated_attribute' => 'required', + 'array_attribute' => 'required|array', + 'array_attribute.uuid_key' => 'required|uuid', ]); // Example request data $data = [ 'array_attribute' => [ - 'uuid_key' => 'clearly not a uuid' - ] + 'uuid_key' => 'clearly not a uuid', + ], ]; $rules = $service->getRelevantValidationRules($mockedModel, $data); diff --git a/test/tests/Unit/SnakeCaseMiddlewareTest.php b/test/tests/Unit/SnakeCaseMiddlewareTest.php index cb124cb..691efe3 100644 --- a/test/tests/Unit/SnakeCaseMiddlewareTest.php +++ b/test/tests/Unit/SnakeCaseMiddlewareTest.php @@ -3,14 +3,13 @@ namespace Specialtactics\L5Api\Tests\Unit; use Dingo\Api\Http\Request; -use Mockery; use Specialtactics\L5Api\Http\Middleware\SnakeCaseInputParameterKeys; use Specialtactics\L5Api\Tests\BaseTestCase; class SnakeCaseMiddlewareTest extends BaseTestCase { /** - * Test that we are not snake_casing keys which are all uppercase + * Test that we are not snake_casing keys which are all uppercase. * * @test */ @@ -19,14 +18,14 @@ public function dontTransformAllUpercaseKeys() // Setup request $content = [ 'keyShouldTransform' => true, - 'AUD/USD' => '0.80', - 'AUD' => '0.75' + 'AUD/USD' => '0.80', + 'AUD' => '0.75', ]; $request = Request::create('/test', 'POST', [], [], [], ['CONTENT_TYPE' => 'application/json'], json_encode($content)); - $snakeCaseMiddleware = new SnakeCaseInputParameterKeys; - $snakeCaseMiddleware->handle($request, function($request) {}); + $snakeCaseMiddleware = new SnakeCaseInputParameterKeys(); + $snakeCaseMiddleware->handle($request, function ($request) {}); $input = $request->input();