From a0055ef9a7bc2e362b02c1c4b4a437b7eef4c93a Mon Sep 17 00:00:00 2001 From: Sam Poyigi <6567634+sampoyigi@users.noreply.github.com> Date: Sun, 5 Jan 2025 00:29:17 +0000 Subject: [PATCH] feat: add strict types to test files, and update return types for methods in API resources, transformers, and repositories (v4) Signed-off-by: Sam Poyigi <6567634+sampoyigi@users.noreply.github.com> --- composer.json | 3 +- phpstan-baseline.neon | 25 ------- phpstan.neon.dist | 5 +- rector.php | 15 ++++ src/ApiResources/Categories.php | 2 + src/ApiResources/Currencies.php | 2 + src/ApiResources/Customers.php | 2 + src/ApiResources/DiningTables.php | 2 + src/ApiResources/Locations.php | 2 + src/ApiResources/MenuItemOptions.php | 2 + src/ApiResources/MenuOptions.php | 2 + src/ApiResources/Menus.php | 2 + src/ApiResources/Orders.php | 4 +- .../Repositories/CategoryRepository.php | 2 + .../Repositories/CurrencyRepository.php | 2 + .../Repositories/CustomerRepository.php | 2 + .../Repositories/DiningTableRepository.php | 2 + .../Repositories/LocationRepository.php | 2 + .../Repositories/MenuItemOptionRepository.php | 2 + .../Repositories/MenuOptionRepository.php | 2 + .../Repositories/MenuRepository.php | 2 + .../Repositories/OrderRepository.php | 2 + .../Repositories/ReservationRepository.php | 2 + .../Repositories/ReviewRepository.php | 2 + .../Requests/MenuItemOptionRequest.php | 4 +- .../Requests/MenuOptionRequest.php | 4 +- src/ApiResources/Requests/OrderRequest.php | 2 + .../Requests/ReservationRequest.php | 4 +- src/ApiResources/Reservations.php | 2 + src/ApiResources/Reviews.php | 2 + .../Transformers/AddressTransformer.php | 4 +- .../Transformers/CategoryTransformer.php | 10 +-- .../Transformers/CurrencyTransformer.php | 4 +- .../Transformers/CustomerTransformer.php | 11 +-- .../Transformers/DeliveryAreaTransformer.php | 4 +- .../Transformers/DiningTableTransformer.php | 2 + .../Transformers/IngredientTransformer.php | 4 +- .../Transformers/LocationTransformer.php | 12 ++-- .../Transformers/MealtimeTransformer.php | 4 +- .../Transformers/MediaTransformer.php | 2 + .../MenuItemOptionTransformer.php | 7 +- .../MenuItemOptionValueTransformer.php | 4 +- .../Transformers/MenuOptionTransformer.php | 6 +- .../MenuOptionValueTransformer.php | 4 +- .../Transformers/MenuTransformer.php | 16 +++-- .../Transformers/OrderTransformer.php | 20 +++--- .../Transformers/PaymentMethodTransformer.php | 4 +- .../Transformers/ReservationTransformer.php | 16 +++-- .../Transformers/ReviewTransformer.php | 8 ++- .../Transformers/StatusHistoryTransformer.php | 4 +- .../Transformers/StatusTransformer.php | 4 +- .../Transformers/StockTransformer.php | 4 +- .../Transformers/UserGroupTransformer.php | 4 +- .../Transformers/UserTransformer.php | 4 +- .../Transformers/WorkingHourTransformer.php | 2 + src/Classes/AbstractRepository.php | 27 ++++---- src/Classes/ApiController.php | 2 + src/Classes/ApiManager.php | 6 +- src/Console/IssueApiToken.php | 9 ++- src/Database/Factories/ResourceFactory.php | 2 + src/Database/Factories/TokenFactory.php | 2 + src/Exceptions/AuthenticationException.php | 2 + src/Exceptions/ErrorHandler.php | 65 +++++------------ src/Exceptions/ResourceException.php | 30 ++++---- src/Exceptions/ValidationHttpException.php | 10 +-- src/Extension.php | 14 ++-- src/Http/Actions/RestController.php | 16 +++-- src/Http/Controllers/CreateToken.php | 5 +- src/Http/Controllers/Resources.php | 4 +- src/Http/Controllers/Tokens.php | 2 + src/Http/Middleware/Authenticate.php | 6 +- src/Http/Requests/ResourceRequest.php | 2 + src/Listeners/TokenEventSubscriber.php | 9 +-- src/Models/Resource.php | 69 +++++++------------ src/Models/Token.php | 26 ++----- src/Traits/AuthorizesRequest.php | 2 + src/Traits/CreatesResponse.php | 9 +-- src/Traits/GuardsAttributes.php | 5 +- src/Traits/HasGlobalScopes.php | 14 ++-- src/Traits/MergesIdAttribute.php | 4 +- src/Traits/RestExtendable.php | 8 +-- tests/ApiResources/CategoriesTest.php | 24 ++++--- tests/ApiResources/CurrenciesTest.php | 4 +- tests/ApiResources/CustomersTest.php | 26 +++---- tests/ApiResources/DiningTablesTest.php | 13 ++-- tests/ApiResources/LocationsTest.php | 32 +++++---- tests/ApiResources/MenuItemOptionsTest.php | 26 +++---- tests/ApiResources/MenuOptionsTest.php | 26 +++---- tests/ApiResources/MenusTest.php | 36 +++++----- tests/ApiResources/OrdersTest.php | 28 ++++---- .../Requests/MenuItemOptionRequestTest.php | 6 +- .../Requests/MenuOptionRequestTest.php | 6 +- .../Requests/OrderRequestTest.php | 6 +- .../Requests/ReservationRequestTest.php | 6 +- tests/ApiResources/ReservationsTest.php | 24 ++++--- tests/ApiResources/ReviewsTest.php | 16 +++-- tests/Classes/AbstractRepositoryTest.php | 64 ++++++++--------- tests/Classes/ApiControllerTest.php | 24 ++++--- tests/Classes/ApiManagerTest.php | 24 ++++--- tests/Console/IssueApiTokenTest.php | 8 ++- .../AuthenticationExceptionTest.php | 4 +- tests/Exceptions/ErrorHandlerTest.php | 16 +++-- tests/Exceptions/ResourceExceptionTest.php | 14 ++-- tests/ExtensionTest.php | 16 +++-- tests/Fixtures/TestModel.php | 2 + tests/Fixtures/TestRepository.php | 2 + tests/Fixtures/TestResource.php | 2 + tests/Fixtures/TestTransformer.php | 2 + tests/Http/Controllers/CreateTokenTest.php | 10 +-- tests/Http/Controllers/ResourcesTest.php | 14 ++-- tests/Http/Controllers/TokensTest.php | 6 +- tests/Http/Middleware/AuthenticateTest.php | 14 ++-- tests/Http/Requests/ResourceRequestTest.php | 6 +- tests/Listeners/TokenEventSubscriberTest.php | 20 +++--- tests/Models/ResourceTest.php | 18 ++--- tests/Models/TokenTest.php | 10 +-- tests/Pest.php | 2 + tests/Traits/AuthorizesRequestTest.php | 14 ++-- tests/Traits/CreatesResponseTest.php | 8 ++- tests/Traits/GuardsAttributesTest.php | 20 +++--- tests/Traits/HasGlobalScopesTest.php | 22 +++--- tests/Traits/RestExtendableTest.php | 8 ++- 122 files changed, 688 insertions(+), 563 deletions(-) create mode 100644 rector.php diff --git a/composer.json b/composer.json index e6d9c4f..2a5df34 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,8 @@ }, "require-dev": { "laravel/pint": "^1.2", - "larastan/larastan": "^2.4.0", + "larastan/larastan": "^3.0", + "rector/rector": "^2.0", "sampoyigi/testbench": "dev-main as 1.0", "pestphp/pest-plugin-laravel": "^3.0" }, diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 2690f7d..5857535 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -130,26 +130,11 @@ parameters: count: 1 path: src/ApiResources/Transformers/ReservationTransformer.php - - - message: "#^Access to an undefined property Igniter\\\\Reservation\\\\Models\\\\Reservation\\:\\:\\$location\\.$#" - count: 1 - path: src/ApiResources/Transformers/ReservationTransformer.php - - - - message: "#^Access to an undefined property Igniter\\\\Reservation\\\\Models\\\\Reservation\\:\\:\\$status\\.$#" - count: 1 - path: src/ApiResources/Transformers/ReservationTransformer.php - - message: "#^Access to an undefined property Igniter\\\\Reservation\\\\Models\\\\Reservation\\:\\:\\$status_history\\.$#" count: 1 path: src/ApiResources/Transformers/ReservationTransformer.php - - - message: "#^Access to an undefined property Igniter\\\\Reservation\\\\Models\\\\Reservation\\:\\:\\$tables\\.$#" - count: 1 - path: src/ApiResources/Transformers/ReservationTransformer.php - - message: "#^Access to an undefined property Igniter\\\\Local\\\\Models\\\\Review\\:\\:\\$customer\\.$#" count: 1 @@ -160,16 +145,6 @@ parameters: count: 1 path: src/ApiResources/Transformers/ReviewTransformer.php - - - message: "#^Result of method Illuminate\\\\Console\\\\Command\\:\\:error\\(\\) \\(void\\) is used\\.$#" - count: 1 - path: src/Console/IssueApiToken.php - - - - message: "#^Default value of the parameter \\#2 \\$errors \\(string\\) of method Igniter\\\\Api\\\\Exceptions\\\\ResourceException\\:\\:__construct\\(\\) is incompatible with type array\\|Illuminate\\\\Support\\\\MessageBag\\.$#" - count: 1 - path: src/Exceptions/ResourceException.php - - message: "#^Access to an undefined property Illuminate\\\\Support\\\\Optional\\:\\:\\$id\\.$#" count: 1 diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 1acd961..c4c266d 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -2,7 +2,7 @@ includes: - phpstan-baseline.neon parameters: - level: 2 + level: 5 paths: - src/ - config/ @@ -10,6 +10,3 @@ parameters: - resources/ # ignoreErrors: # - '#PHPDoc tag @var#' -# excludePaths: -# - ./*/*/FileToBeExcluded.php -# checkMissingIterableValueType: false diff --git a/rector.php b/rector.php new file mode 100644 index 0000000..3381f46 --- /dev/null +++ b/rector.php @@ -0,0 +1,15 @@ +withPaths([__DIR__.'/src', __DIR__.'/tests']) + ->withSkip([ + ReturnTypeFromStrictNewArrayRector::class, + ]) + ->withTypeCoverageLevel(100) + ->withDeadCodeLevel(100) + ->withCodeQualityLevel(0); diff --git a/src/ApiResources/Categories.php b/src/ApiResources/Categories.php index 31e7e17..134af0d 100644 --- a/src/ApiResources/Categories.php +++ b/src/ApiResources/Categories.php @@ -1,5 +1,7 @@ input('order_menus', [])) { $model->addOrderMenus(json_decode(json_encode($orderMenus))); diff --git a/src/ApiResources/Repositories/CategoryRepository.php b/src/ApiResources/Repositories/CategoryRepository.php index 520a467..3c70744 100644 --- a/src/ApiResources/Repositories/CategoryRepository.php +++ b/src/ApiResources/Repositories/CategoryRepository.php @@ -1,5 +1,7 @@ ['nullable', 'integer'], diff --git a/src/ApiResources/Requests/MenuOptionRequest.php b/src/ApiResources/Requests/MenuOptionRequest.php index 6364ee2..b12d9d7 100644 --- a/src/ApiResources/Requests/MenuOptionRequest.php +++ b/src/ApiResources/Requests/MenuOptionRequest.php @@ -1,5 +1,7 @@ ['required', 'min:2', 'max:32'], diff --git a/src/ApiResources/Requests/OrderRequest.php b/src/ApiResources/Requests/OrderRequest.php index e76773c..4ee9eb2 100644 --- a/src/ApiResources/Requests/OrderRequest.php +++ b/src/ApiResources/Requests/OrderRequest.php @@ -1,5 +1,7 @@ ['sometimes', 'required', 'integer'], diff --git a/src/ApiResources/Reservations.php b/src/ApiResources/Reservations.php index 90774ad..24039a7 100644 --- a/src/ApiResources/Reservations.php +++ b/src/ApiResources/Reservations.php @@ -1,5 +1,7 @@ mergesIdAttribute($address); } diff --git a/src/ApiResources/Transformers/CategoryTransformer.php b/src/ApiResources/Transformers/CategoryTransformer.php index d7e74c1..d74afc6 100644 --- a/src/ApiResources/Transformers/CategoryTransformer.php +++ b/src/ApiResources/Transformers/CategoryTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($category); } - public function includeMedia(Category $category) + public function includeMedia(Category $category): ?\League\Fractal\Resource\Item { return ($thumb = $category->getFirstMedia()) ? $this->item($thumb, new MediaTransformer, 'media') : null; } - public function includeMenus(Category $category) + public function includeMenus(Category $category): ?\League\Fractal\Resource\Collection { return $this->collection($category->menus, new MenuTransformer, 'menus'); } - public function includeLocations(Category $category) + public function includeLocations(Category $category): ?\League\Fractal\Resource\Collection { return $this->collection($category->locations, new LocationTransformer, 'locations'); } diff --git a/src/ApiResources/Transformers/CurrencyTransformer.php b/src/ApiResources/Transformers/CurrencyTransformer.php index 55ea1ca..3f61a76 100644 --- a/src/ApiResources/Transformers/CurrencyTransformer.php +++ b/src/ApiResources/Transformers/CurrencyTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($currency); } diff --git a/src/ApiResources/Transformers/CustomerTransformer.php b/src/ApiResources/Transformers/CustomerTransformer.php index 837b577..af0857b 100644 --- a/src/ApiResources/Transformers/CustomerTransformer.php +++ b/src/ApiResources/Transformers/CustomerTransformer.php @@ -1,9 +1,12 @@ mergesIdAttribute($customer); } - public function includeAddresses(Customer $customer) + public function includeAddresses(Customer $customer): Collection { return $this->collection($customer->addresses, new AddressTransformer, 'addresses'); } - public function includeOrders(Customer $customer) + public function includeOrders(Customer $customer): Collection { return $this->collection($customer->orders, new OrderTransformer, 'orders'); } - public function includeReservations(Customer $customer) + public function includeReservations(Customer $customer): Collection { return $this->collection($customer->reservations, new ReservationTransformer, 'reservations'); } diff --git a/src/ApiResources/Transformers/DeliveryAreaTransformer.php b/src/ApiResources/Transformers/DeliveryAreaTransformer.php index 91f2a88..c9166cb 100644 --- a/src/ApiResources/Transformers/DeliveryAreaTransformer.php +++ b/src/ApiResources/Transformers/DeliveryAreaTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($deliveryArea); } diff --git a/src/ApiResources/Transformers/DiningTableTransformer.php b/src/ApiResources/Transformers/DiningTableTransformer.php index 74a9371..3f7c9cf 100644 --- a/src/ApiResources/Transformers/DiningTableTransformer.php +++ b/src/ApiResources/Transformers/DiningTableTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($ingredient); } diff --git a/src/ApiResources/Transformers/LocationTransformer.php b/src/ApiResources/Transformers/LocationTransformer.php index bd1b322..af25801 100644 --- a/src/ApiResources/Transformers/LocationTransformer.php +++ b/src/ApiResources/Transformers/LocationTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($location); } - public function includeMedia(Location $location) + public function includeMedia(Location $location): ?\League\Fractal\Resource\Item { return ($thumb = $location->getFirstMedia()) ? $this->item($thumb, new MediaTransformer, 'media') : null; } - public function includeWorkingHours(Location $location) + public function includeWorkingHours(Location $location): ?\League\Fractal\Resource\Collection { return $this->collection( $location->working_hours, @@ -36,7 +38,7 @@ public function includeWorkingHours(Location $location) ); } - public function includeDeliveryAreas(Location $location) + public function includeDeliveryAreas(Location $location): ?\League\Fractal\Resource\Collection { return $this->collection( $location->delivery_areas, @@ -45,7 +47,7 @@ public function includeDeliveryAreas(Location $location) ); } - public function includeReviews(Location $location) + public function includeReviews(Location $location): ?\League\Fractal\Resource\Collection { return $this->collection( $location->reviews, diff --git a/src/ApiResources/Transformers/MealtimeTransformer.php b/src/ApiResources/Transformers/MealtimeTransformer.php index 2edcd21..34681ca 100644 --- a/src/ApiResources/Transformers/MealtimeTransformer.php +++ b/src/ApiResources/Transformers/MealtimeTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($mealTime); } diff --git a/src/ApiResources/Transformers/MediaTransformer.php b/src/ApiResources/Transformers/MediaTransformer.php index 2527aaf..641b828 100644 --- a/src/ApiResources/Transformers/MediaTransformer.php +++ b/src/ApiResources/Transformers/MediaTransformer.php @@ -1,5 +1,7 @@ toArray(), [ 'id' => $menuItemOption->menu_option_id, @@ -19,7 +22,7 @@ public function transform(MenuItemOption $menuItemOption) ]); } - public function includeMenuOptionValues(MenuItemOption $menuItemOption) + public function includeMenuOptionValues(MenuItemOption $menuItemOption): Collection { return $this->collection( $menuItemOption->menu_option_values, diff --git a/src/ApiResources/Transformers/MenuItemOptionValueTransformer.php b/src/ApiResources/Transformers/MenuItemOptionValueTransformer.php index 5e7af1a..07d40f7 100644 --- a/src/ApiResources/Transformers/MenuItemOptionValueTransformer.php +++ b/src/ApiResources/Transformers/MenuItemOptionValueTransformer.php @@ -1,5 +1,7 @@ toArray(); diff --git a/src/ApiResources/Transformers/MenuOptionTransformer.php b/src/ApiResources/Transformers/MenuOptionTransformer.php index a4707ce..03e6905 100644 --- a/src/ApiResources/Transformers/MenuOptionTransformer.php +++ b/src/ApiResources/Transformers/MenuOptionTransformer.php @@ -1,5 +1,7 @@ toArray(), [ 'id' => $menuOption->option_id, ]); } - public function includeOptionValues(MenuOption $menuOption) + public function includeOptionValues(MenuOption $menuOption): \League\Fractal\Resource\Collection { return $this->collection( $menuOption->option_values, diff --git a/src/ApiResources/Transformers/MenuOptionValueTransformer.php b/src/ApiResources/Transformers/MenuOptionValueTransformer.php index 82fe6af..2f80a6c 100644 --- a/src/ApiResources/Transformers/MenuOptionValueTransformer.php +++ b/src/ApiResources/Transformers/MenuOptionValueTransformer.php @@ -1,5 +1,7 @@ toArray(); diff --git a/src/ApiResources/Transformers/MenuTransformer.php b/src/ApiResources/Transformers/MenuTransformer.php index 01ddb14..41fd3cb 100644 --- a/src/ApiResources/Transformers/MenuTransformer.php +++ b/src/ApiResources/Transformers/MenuTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($menuItem, [ 'currency' => app('currency')->getDefault()->currency_code, ]); } - public function includeMedia(Menu $menuItem) + public function includeMedia(Menu $menuItem): ?\League\Fractal\Resource\Item { return ($thumb = $menuItem->getFirstMedia()) ? $this->item($thumb, new MediaTransformer, 'media') : null; } - public function includeCategories(Menu $menuItem) + public function includeCategories(Menu $menuItem): ?\League\Fractal\Resource\Collection { return $this->collection( $menuItem->categories, @@ -40,7 +42,7 @@ public function includeCategories(Menu $menuItem) ); } - public function includeMenuOptions(Menu $menuItem) + public function includeMenuOptions(Menu $menuItem): ?\League\Fractal\Resource\Collection { return $this->collection( $menuItem->menu_options, @@ -49,7 +51,7 @@ public function includeMenuOptions(Menu $menuItem) ); } - public function includeIngredients(Menu $menuItem) + public function includeIngredients(Menu $menuItem): ?\League\Fractal\Resource\Collection { return $this->collection( $menuItem->ingredients, @@ -58,7 +60,7 @@ public function includeIngredients(Menu $menuItem) ); } - public function includeMealtimes(Menu $menuItem) + public function includeMealtimes(Menu $menuItem): ?\League\Fractal\Resource\Collection { return $this->collection( $menuItem->mealtimes, @@ -67,7 +69,7 @@ public function includeMealtimes(Menu $menuItem) ); } - public function includeStocks(Menu $menuItem) + public function includeStocks(Menu $menuItem): ?\League\Fractal\Resource\Collection { return $this->collection( $menuItem->stocks, diff --git a/src/ApiResources/Transformers/OrderTransformer.php b/src/ApiResources/Transformers/OrderTransformer.php index cee2607..b46c11b 100644 --- a/src/ApiResources/Transformers/OrderTransformer.php +++ b/src/ApiResources/Transformers/OrderTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($order, [ 'currency' => app('currency')->getDefault()->currency_code, @@ -30,42 +32,42 @@ public function transform(Order $order) ]); } - public function includeCustomer(Order $order) + public function includeCustomer(Order $order): ?\League\Fractal\Resource\Item { return $order->customer ? $this->item($order->customer, new CustomerTransformer, 'customers') : null; } - public function includeLocation(Order $order) + public function includeLocation(Order $order): \League\Fractal\Resource\Item { return $this->item($order->location, new LocationTransformer, 'locations'); } - public function includeAddress(Order $order) + public function includeAddress(Order $order): ?\League\Fractal\Resource\Item { return $order->address ? $this->item($order->address, new AddressTransformer, 'addresses') : null; } - public function includePaymentMethod(Order $order) + public function includePaymentMethod(Order $order): ?\League\Fractal\Resource\Item { return $order->payment_method ? $this->item($order->payment_method, new PaymentMethodTransformer, 'payment_methods') : null; } - public function includeStatus(Order $order) + public function includeStatus(Order $order): \League\Fractal\Resource\Item { return $this->item($order->status, new StatusTransformer, 'statuses'); } - public function includeStatusHistory(Order $order) + public function includeStatusHistory(Order $order): \League\Fractal\Resource\Collection { return $this->collection($order->status_history, new StatusHistoryTransformer, 'status_history'); } - public function includeAssignee(Order $order) + public function includeAssignee(Order $order): ?\League\Fractal\Resource\Item { return $order->assignee ? $this->item($order->assignee, new UserTransformer, 'assignee') : null; } - public function includeAssigneeGroup(Order $order) + public function includeAssigneeGroup(Order $order): ?\League\Fractal\Resource\Item { return $order->assignee_group ? $this->item($order->assignee_group, new UserGroupTransformer, 'assignee_group') : null; } diff --git a/src/ApiResources/Transformers/PaymentMethodTransformer.php b/src/ApiResources/Transformers/PaymentMethodTransformer.php index 2c04b33..1011faf 100644 --- a/src/ApiResources/Transformers/PaymentMethodTransformer.php +++ b/src/ApiResources/Transformers/PaymentMethodTransformer.php @@ -1,5 +1,7 @@ $payment->getKey(), diff --git a/src/ApiResources/Transformers/ReservationTransformer.php b/src/ApiResources/Transformers/ReservationTransformer.php index 812168b..b4c8263 100644 --- a/src/ApiResources/Transformers/ReservationTransformer.php +++ b/src/ApiResources/Transformers/ReservationTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($reservation); } - public function includeLocation(Reservation $reservation) + public function includeLocation(Reservation $reservation): \League\Fractal\Resource\Item { return $this->item($reservation->location, new LocationTransformer, 'locations'); } - public function includeTables(Reservation $reservation) + public function includeTables(Reservation $reservation): \League\Fractal\Resource\Collection { return $this->collection($reservation->tables, new DiningTableTransformer, 'tables'); } - public function includeStatus(Reservation $reservation) + public function includeStatus(Reservation $reservation): \League\Fractal\Resource\Item { return $this->item($reservation->status, new StatusTransformer, 'statuses'); } - public function includeStatusHistory(Reservation $reservation) + public function includeStatusHistory(Reservation $reservation): \League\Fractal\Resource\Collection { return $this->collection($reservation->status_history, new StatusHistoryTransformer, 'status_history'); } - public function includeAssignee(Reservation $reservation) + public function includeAssignee(Reservation $reservation): \League\Fractal\Resource\Item { return $this->item($reservation->assignee, new UserTransformer, 'assignee'); } - public function includeAssigneeGroup(Reservation $reservation) + public function includeAssigneeGroup(Reservation $reservation): \League\Fractal\Resource\Item { return $this->item($reservation->assignee_group, new UserGroupTransformer, 'assignee_group'); } diff --git a/src/ApiResources/Transformers/ReviewTransformer.php b/src/ApiResources/Transformers/ReviewTransformer.php index f405034..f39f94a 100644 --- a/src/ApiResources/Transformers/ReviewTransformer.php +++ b/src/ApiResources/Transformers/ReviewTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($review); } - public function includeCustomer(Review $review) + public function includeCustomer(Review $review): \League\Fractal\Resource\Item { return $this->item($review->customer, new CustomerTransformer, 'customers'); } - public function includeLocation(Review $review) + public function includeLocation(Review $review): \League\Fractal\Resource\Item { return $this->item($review->location, new LocationTransformer, 'locations'); } diff --git a/src/ApiResources/Transformers/StatusHistoryTransformer.php b/src/ApiResources/Transformers/StatusHistoryTransformer.php index 526bea3..900efa2 100644 --- a/src/ApiResources/Transformers/StatusHistoryTransformer.php +++ b/src/ApiResources/Transformers/StatusHistoryTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($statusHistory); } diff --git a/src/ApiResources/Transformers/StatusTransformer.php b/src/ApiResources/Transformers/StatusTransformer.php index b02651b..d2439f8 100644 --- a/src/ApiResources/Transformers/StatusTransformer.php +++ b/src/ApiResources/Transformers/StatusTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($status); } diff --git a/src/ApiResources/Transformers/StockTransformer.php b/src/ApiResources/Transformers/StockTransformer.php index 2aa1d46..268bc33 100644 --- a/src/ApiResources/Transformers/StockTransformer.php +++ b/src/ApiResources/Transformers/StockTransformer.php @@ -1,5 +1,7 @@ toArray(), []); } diff --git a/src/ApiResources/Transformers/UserGroupTransformer.php b/src/ApiResources/Transformers/UserGroupTransformer.php index c25f52b..83cb852 100644 --- a/src/ApiResources/Transformers/UserGroupTransformer.php +++ b/src/ApiResources/Transformers/UserGroupTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($userGroup); } diff --git a/src/ApiResources/Transformers/UserTransformer.php b/src/ApiResources/Transformers/UserTransformer.php index e362fca..2dca312 100644 --- a/src/ApiResources/Transformers/UserTransformer.php +++ b/src/ApiResources/Transformers/UserTransformer.php @@ -1,5 +1,7 @@ mergesIdAttribute($user); } diff --git a/src/ApiResources/Transformers/WorkingHourTransformer.php b/src/ApiResources/Transformers/WorkingHourTransformer.php index ccc89dd..f26d7d1 100644 --- a/src/ApiResources/Transformers/WorkingHourTransformer.php +++ b/src/ApiResources/Transformers/WorkingHourTransformer.php @@ -1,5 +1,7 @@ paginate($perPage, $page, $columns, $pageName); } - public function create(Model $model, array $attributes) + public function create(Model $model, array $attributes): Model { $this->fireSystemEvent('api.repository.beforeCreate', [$model, $attributes]); @@ -87,7 +89,7 @@ public function create(Model $model, array $attributes) $this->setCustomerAwareAttributes($model); - DB::transaction(function() { + DB::transaction(function(): void { foreach ($this->modelsToSave as $modelToSave) { $modelToSave->save(); } @@ -115,7 +117,7 @@ public function update($id, array $attributes = []) $this->modelsToSave = []; $this->setModelAttributes($model, $attributes); - DB::transaction(function() { + DB::transaction(function(): void { foreach ($this->modelsToSave as $modelToSave) { $modelToSave->save(); } @@ -144,17 +146,17 @@ public function delete(int $id) public function getModelClass() { if (!strlen($modelClass = $this->modelClass)) { - throw new SystemException('Missing model on '.get_class($this)); + throw new SystemException('Missing model on '.static::class); } return $modelClass; } - public function createModel(): \Illuminate\Database\Eloquent\Model + public function createModel(): Model { $modelClass = $this->getModelClass(); - if (!class_exists('\\'.ltrim($modelClass, '\\'))) { + if (!class_exists('\\'.ltrim((string)$modelClass, '\\'))) { throw new SystemException("Class $modelClass does NOT exist!"); } @@ -165,7 +167,7 @@ public function createModel(): \Illuminate\Database\Eloquent\Model protected function prepareModel(string $modelClass): void { - $modelClass::extend(function(Model $model) { + $modelClass::extend(function(Model $model): void { if ($fillable = $this->getFillable()) { $model->mergeFillable($fillable); } @@ -182,14 +184,15 @@ protected function prepareModel(string $modelClass): void $model->setVisible($visible); } - if ($relationKeys = collect($model->getRelationDefinitions())->collapse()->keys()) { + $relationKeys = collect($model->getRelationDefinitions())->collapse()->keys(); + if ($relationKeys->isNotEmpty()) { $model->makeHidden($relationKeys->toArray()); } $this->extendModel($model); - $model->bindEvent('model.getAttribute', [$this, 'getModelAttribute']); - $model->bindEvent('model.setAttribute', [$this, 'setModelAttribute']); + $model->bindEvent('model.getAttribute', $this->getModelAttribute(...)); + $model->bindEvent('model.setAttribute', $this->setModelAttribute(...)); foreach ([ 'beforeCreate', 'afterCreate', @@ -197,7 +200,7 @@ protected function prepareModel(string $modelClass): void 'beforeSave', 'afterSave', 'beforeDelete', 'afterDelete', ] as $method) { - $model->bindEvent('model.'.$method, function() use ($model, $method) { + $model->bindEvent('model.'.$method, function() use ($model, $method): void { if (method_exists($this, $method)) { $this->$method($model); } @@ -299,7 +302,7 @@ protected function getCustomerAwareColumn() return array_get(static::$customerAwareConfig, 'column', 'customer_id'); } - protected function getCustomerAwareUser() + protected function getCustomerAwareUser(): ?Customer { return ($customer = request()->user()) instanceof Customer ? $customer : null; } diff --git a/src/Classes/ApiController.php b/src/Classes/ApiController.php index 2137154..6734382 100644 --- a/src/Classes/ApiController.php +++ b/src/Classes/ApiController.php @@ -1,5 +1,7 @@ resources = $resources; } - public static function registerRoutes() + public static function registerRoutes(): void { if (!Igniter::hasDatabase() || !Schema::hasTable('igniter_api_resources')) { return; @@ -73,7 +75,7 @@ public static function registerRoutes() Route::middleware(config('igniter.api.middleware')) ->as('igniter.api.') ->prefix(config('igniter.api.prefix')) - ->group(function($router) { + ->group(function($router): void { foreach (resolve(static::class)->getResources() as $endpoint => $resourceObj) { if (!class_exists($resourceObj->controller)) { continue; diff --git a/src/Console/IssueApiToken.php b/src/Console/IssueApiToken.php index 2e10b12..d79a6ea 100644 --- a/src/Console/IssueApiToken.php +++ b/src/Console/IssueApiToken.php @@ -1,5 +1,7 @@ option('name'); $email = $this->option('email'); @@ -38,7 +39,9 @@ public function handle() $query->where('email', $email); if (!$user = $query->first()) { - return $this->error('User does not exist!'); + $this->error('User does not exist!'); + + return; } $accessToken = Token::createToken($user, $name, $abilities ?: ['*']); diff --git a/src/Database/Factories/ResourceFactory.php b/src/Database/Factories/ResourceFactory.php index f4986de..be223a1 100644 --- a/src/Database/Factories/ResourceFactory.php +++ b/src/Database/Factories/ResourceFactory.php @@ -1,5 +1,7 @@ parentHandler = $handler; - $this->format = $format; - $this->debug = $debug; - - if (method_exists($handler, 'renderable')) { - $handler->renderable(function(Throwable $ex) { - return $this->render(request(), $ex); - }); + /** + * @param bool $debug + */ + public function __construct( + protected ExceptionHandler $parentHandler, + protected array $format, + protected $debug, + ) { + if (method_exists($this->parentHandler, 'renderable')) { + $this->parentHandler->renderable(fn(Throwable $ex) => $this->render(request(), $ex)); } } @@ -82,16 +62,15 @@ public function render($request, Throwable $e) /** * Handle a generic error response if there is no handler available. * - * @return \Illuminate\Http\Response * @throws Throwable */ - protected function genericResponse(Throwable $exception) + protected function genericResponse(Throwable $exception): Response { $replacements = $this->prepareReplacements($exception); $response = $this->format; - array_walk_recursive($response, function(&$value, $key) use ($replacements) { + array_walk_recursive($response, function(&$value, $key) use ($replacements): void { if (Str::startsWith($value, ':') && isset($replacements[$value])) { $value = $replacements[$value]; } @@ -125,20 +104,16 @@ protected function getStatusCode(Throwable $exception) /** * Get the headers from the exception. - * - * @return array */ - protected function getHeaders(Throwable $exception) + protected function getHeaders(Throwable $exception): array { return $exception instanceof HttpExceptionInterface ? $exception->getHeaders() : []; } /** * Prepare the replacements array by gathering the keys and values. - * - * @return array */ - protected function prepareReplacements(Throwable $exception) + protected function prepareReplacements(Throwable $exception): array { $statusCode = $this->getStatusCode($exception); @@ -163,7 +138,7 @@ protected function prepareReplacements(Throwable $exception) $replacements[':debug'] = [ 'line' => $exception->getLine(), 'file' => $exception->getFile(), - 'class' => get_class($exception), + 'class' => $exception::class, 'trace' => explode("\n", $exception->getTraceAsString()), ]; @@ -183,10 +158,8 @@ protected function prepareReplacements(Throwable $exception) /** * Recursively remove any empty replacement values in the response array. - * - * @return array */ - protected function recursivelyRemoveEmptyReplacements(array $input) + protected function recursivelyRemoveEmptyReplacements(array $input): array { foreach ($input as &$value) { if (is_array($value)) { @@ -194,7 +167,7 @@ protected function recursivelyRemoveEmptyReplacements(array $input) } } - return array_filter($input, function($value) { + return array_filter($input, function($value): bool { if (is_string($value)) { return !Str::startsWith($value, ':'); } diff --git a/src/Exceptions/ResourceException.php b/src/Exceptions/ResourceException.php index 04e2867..d1e7390 100644 --- a/src/Exceptions/ResourceException.php +++ b/src/Exceptions/ResourceException.php @@ -1,5 +1,7 @@ errors = new MessageBag; } else { @@ -38,10 +36,8 @@ public function __construct($message = null, $errors = '', ?Throwable $previous /** * Get the errors message bag. - * - * @return \Illuminate\Support\MessageBag */ - public function getErrors() + public function getErrors(): MessageBag|string { return $this->errors; } @@ -53,10 +49,8 @@ public function errors() /** * Determine if message bag has any errors. - * - * @return bool */ - public function hasErrors() + public function hasErrors(): bool { return !$this->errors->isEmpty(); } diff --git a/src/Exceptions/ValidationHttpException.php b/src/Exceptions/ValidationHttpException.php index c691aaf..044fb02 100644 --- a/src/Exceptions/ValidationHttpException.php +++ b/src/Exceptions/ValidationHttpException.php @@ -1,5 +1,7 @@ mergeConfigFrom(__DIR__.'/../config/api.php', 'igniter.api'); @@ -44,7 +46,7 @@ public function register() $this->registerConsoleCommand('api.token', Console\IssueApiToken::class); } - public function boot() + public function boot(): void { $this->configureRateLimiting(); @@ -82,7 +84,7 @@ public function registerPermissions(): array ]; } - public function registerApiResources() + public function registerApiResources(): array { return [ 'categories' => [ @@ -196,7 +198,7 @@ public function registerApiResources() protected function registerErrorHandler() { - $this->callAfterResolving(ExceptionHandler::class, function($handler) { + $this->callAfterResolving(ExceptionHandler::class, function($handler): void { new ErrorHandler($handler, config('igniter.api.errorFormat', []), config('igniter.api.debug', [])); }); } @@ -220,8 +222,6 @@ protected function sanctumConfigureAuth() protected function configureRateLimiting() { - RateLimiter::for('api', function(Request $request) { - return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip()); - }); + RateLimiter::for('api', fn(Request $request) => Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip())); } } diff --git a/src/Http/Actions/RestController.php b/src/Http/Actions/RestController.php index b1d0ac3..ec25175 100644 --- a/src/Http/Actions/RestController.php +++ b/src/Http/Actions/RestController.php @@ -1,5 +1,7 @@ bindEvent('repository.extendQuery', function($query) { + $repository->bindEvent('repository.extendQuery', function($query): void { $this->controller->restExtendQuery($query); }); } protected function bindCreateEvents(AbstractRepository $repository): void { - $repository->bindEvent('repository.beforeCreate', function($model) { + $repository->bindEvent('repository.beforeCreate', function($model): void { $this->controller->restBeforeSave($model); $this->controller->restBeforeCreate($model); }); - $repository->bindEvent('repository.afterCreate', function($model) { + $repository->bindEvent('repository.afterCreate', function($model): void { $this->controller->restAfterSave($model); $this->controller->restAfterCreate($model); }); @@ -210,12 +212,12 @@ protected function bindCreateEvents(AbstractRepository $repository): void protected function bindUpdateEvents(AbstractRepository $repository): void { - $repository->bindEvent('repository.beforeUpdate', function($model) { + $repository->bindEvent('repository.beforeUpdate', function($model): void { $this->controller->restBeforeSave($model); $this->controller->restAfterUpdate($model); }); - $repository->bindEvent('repository.afterUpdate', function($model) { + $repository->bindEvent('repository.afterUpdate', function($model): void { $this->controller->restAfterSave($model); $this->controller->restAfterUpdate($model); }); @@ -223,7 +225,7 @@ protected function bindUpdateEvents(AbstractRepository $repository): void protected function bindDeleteEvents(AbstractRepository $repository): void { - $repository->bindEvent('repository.afterDelete', function($model) { + $repository->bindEvent('repository.afterDelete', function($model): void { $this->controller->restAfterDelete($model); }); } diff --git a/src/Http/Controllers/CreateToken.php b/src/Http/Controllers/CreateToken.php index ceafb71..32e7d66 100644 --- a/src/Http/Controllers/CreateToken.php +++ b/src/Http/Controllers/CreateToken.php @@ -1,15 +1,18 @@ validate([ 'email' => ['required', 'email:filter'], diff --git a/src/Http/Controllers/Resources.php b/src/Http/Controllers/Resources.php index 0c9d67b..c6a9bfa 100755 --- a/src/Http/Controllers/Resources.php +++ b/src/Http/Controllers/Resources.php @@ -1,5 +1,7 @@ listen( TokenAuthenticated::class, - [$this, 'handleTokenAuthenticated'], + $this->handleTokenAuthenticated(...), ); } - protected function checkGroup(mixed $group, mixed $token) + protected function checkGroup(mixed $group, mixed $token): bool { if ($group == 'guest') { return false; diff --git a/src/Models/Resource.php b/src/Models/Resource.php index e9a8c2e..3e415db 100644 --- a/src/Models/Resource.php +++ b/src/Models/Resource.php @@ -1,5 +1,7 @@ |Resource applyFilters(array $options = []) - * @method static \Igniter\Flame\Database\Builder|Resource applySorts(array $sorts = []) * @method static \Igniter\Flame\Database\Builder|Resource dropdown(string $column, string $key = null) * @method static \Igniter\Flame\Database\Builder|Resource findSimilarSlugs($attribute, array $config, $slug) - * @method static \Igniter\Flame\Database\Builder|Resource like(string $column, string $value, string $side = 'both', string $boolean = 'and') - * @method static \Igniter\Flame\Database\Builder|Resource listFrontEnd(array $options = []) * @method static \Igniter\Flame\Database\Builder|Resource lists(string $column, string $key = null) - * @method static \Igniter\Flame\Database\Builder|Resource newModelQuery() - * @method static \Igniter\Flame\Database\Builder|Resource newQuery() - * @method static \Igniter\Flame\Database\Builder|Resource orLike(string $column, string $value, string $side = 'both') - * @method static \Igniter\Flame\Database\Builder|Resource orSearch(string $term, string $columns = [], string $mode = 'all') - * @method static array pluckDates(string $column, string $keyFormat = 'Y-m', string $valueFormat = 'F Y') * @method static \Igniter\Flame\Database\Builder|Resource query() * @method static \Igniter\Flame\Database\Builder|Resource search(string $term, string $columns = [], string $mode = 'all') - * @method static \Igniter\Flame\Database\Builder|Resource whereDescription($value) - * @method static \Igniter\Flame\Database\Builder|Resource whereEndpoint($value) - * @method static \Igniter\Flame\Database\Builder|Resource whereId($value) - * @method static \Igniter\Flame\Database\Builder|Resource whereIsCustom($value) - * @method static \Igniter\Flame\Database\Builder|Resource whereMeta($value) - * @method static \Igniter\Flame\Database\Builder|Resource whereName($value) - * @method static \Igniter\Flame\Database\Builder|Resource whereSlug(string $slug) * @mixin \Igniter\Flame\Database\Model */ class Resource extends Model @@ -74,7 +60,7 @@ class Resource extends Model public $table = 'igniter_api_resources'; /** - * @var array fillable fields + * @var array fillable fields */ protected $fillable = ['name', 'description', 'endpoint', 'model', 'meta']; @@ -91,24 +77,24 @@ class Resource extends Model public function getMetaOptions() { - $registeredResource = array_get(self::listRegisteredResources(), $this->endpoint, []); + $registeredResource = array_get(static::listRegisteredResources(), $this->endpoint, []); - return array_get($registeredResource, 'options.names', self::$defaultActionDefinition); + return array_get($registeredResource, 'options.names', static::$defaultActionDefinition); } - public function getBaseEndpointAttribute($value) + public function getBaseEndpointAttribute($value): string { return sprintf('/%s/%s', config('igniter.api.prefix'), $this->endpoint); } public function getControllerAttribute() { - return array_get($this->listRegisteredResources(), $this->endpoint.'.controller'); + return array_get(static::listRegisteredResources(), $this->endpoint.'.controller'); } - public function getAvailableActions() + public function getAvailableActions(): array { - $registeredResource = array_get(self::listRegisteredResources(), $this->endpoint, []); + $registeredResource = array_get(static::listRegisteredResources(), $this->endpoint, []); $registeredActions = array_get($registeredResource, 'options.actions', []); $dbActions = (array)array_get($this->meta, 'actions', []); @@ -132,16 +118,14 @@ public function renderSetupPartial() // // Manager // - /** * Synchronise all resources to the database. - * @return void */ - public static function syncAll() + public static function syncAll(): void { $registeredResources = (new static)->listRegisteredResources(); $resources = collect($registeredResources)->keyBy('endpoint')->toArray(); - $dbResources = self::lists('is_custom', 'endpoint')->toArray(); + $dbResources = static::lists('is_custom', 'endpoint')->toArray(); $newResources = array_diff_key($resources, $dbResources); // Clean up non-customized api resources @@ -151,13 +135,13 @@ public static function syncAll() } if (!array_key_exists($endpoint, $resources)) { - self::where('endpoint', $endpoint)->delete(); + static::where('endpoint', $endpoint)->delete(); } } // Create new resources foreach ($newResources as $definition) { - $model = self::make(); + $model = static::make(); $model->endpoint = array_get($definition, 'endpoint'); $model->name = array_get($definition, 'name'); $model->description = array_get($definition, 'description'); @@ -169,7 +153,7 @@ public static function syncAll() public static function getResources() { - return self::all()->keyBy('endpoint')->all(); + return static::all()->keyBy('endpoint')->all(); } /** @@ -178,15 +162,15 @@ public static function getResources() */ public static function listResources() { - $registeredResources = self::listRegisteredResources(); - $dbResources = self::all()->keyBy('endpoint')->all(); + $registeredResources = static::listRegisteredResources(); + $dbResources = static::all()->keyBy('endpoint')->all(); $resources = $registeredResources + $dbResources; ksort($resources); return $resources; } - protected function processOptions($definition) + protected function processOptions($definition): array { $actions = array_get($definition, 'actions', []); @@ -196,9 +180,9 @@ protected function processOptions($definition) $action = $name; } - $action = explode(':', $action, 2); + $action = explode(':', (string)$action, 2); $result[$action[0]] = $action[1] ?? 'all'; - $names[$action[0]] = array_get(self::$defaultActionDefinition, $action[0], $name); + $names[$action[0]] = array_get(static::$defaultActionDefinition, $action[0], $name); } return [ @@ -218,18 +202,17 @@ protected function processOptions($definition) */ public static function listRegisteredResources() { - if (self::$registeredResources === null) { + if (static::$registeredResources === null) { (new static)->loadRegisteredResources(); } - return self::$registeredResources; + return static::$registeredResources; } /** * Loads registered resources from extensions - * @return void */ - public function loadRegisteredResources() + public function loadRegisteredResources(): void { if (!static::$registeredResources) { static::$registeredResources = []; @@ -248,7 +231,7 @@ public function loadRegisteredResources() /** * Registers the api resources. */ - public function registerResources(array $definitions, ?string $owner = null) + public function registerResources(array $definitions, ?string $owner = null): void { $defaultDefinitions = [ 'name' => null, @@ -285,14 +268,14 @@ public function registerResources(array $definitions, ?string $owner = null) * * @param callable $callback A callable function. */ - public function registerCallback(callable $callback) + public function registerCallback(callable $callback): void { static::$callbacks[] = $callback; } - public static function clearInternalCache() + public static function clearInternalCache(): void { - self::$registeredResources = null; + static::$registeredResources = null; static::$callbacks = []; static::$resourceCache = []; } diff --git a/src/Models/Token.php b/src/Models/Token.php index 55deeb7..2197cf0 100644 --- a/src/Models/Token.php +++ b/src/Models/Token.php @@ -1,5 +1,7 @@ |Token newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|Token newQuery() + * @property-read \Illuminate\Database\Eloquent\Model|\Igniter\Flame\Database\Model $tokenable * @method static \Illuminate\Database\Eloquent\Builder|Token query() - * @method static \Illuminate\Database\Eloquent\Builder|Token whereAbilities($value) - * @method static \Illuminate\Database\Eloquent\Builder|Token whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|Token whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|Token whereLastUsedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|Token whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|Token whereToken($value) - * @method static \Illuminate\Database\Eloquent\Builder|Token whereTokenableId($value) - * @method static \Illuminate\Database\Eloquent\Builder|Token whereTokenableType($value) - * @method static \Illuminate\Database\Eloquent\Builder|Token whereUpdatedAt($value) * @mixin \Igniter\Flame\Database\Model */ class Token extends PersonalAccessToken @@ -49,9 +40,8 @@ class Token extends PersonalAccessToken * Create a new personal access token for the user. * * @param \Igniter\Flame\Database\Model $tokenable - * @return \Laravel\Sanctum\NewAccessToken */ - public static function createToken($tokenable, string $name, array $abilities = ['*']) + public static function createToken($tokenable, string $name, array $abilities = ['*']): NewAccessToken { $token = $tokenable->tokens()->create([ 'name' => $name, @@ -64,20 +54,16 @@ public static function createToken($tokenable, string $name, array $abilities = /** * Determine if the token belongs to a admin - * - * @return bool */ - public function isForAdmin() + public function isForAdmin(): bool { return $this->tokenable_type == User::make()->getMorphClass(); } /** * Determine if the token belongs to a customer - * - * @return bool */ - public function isForCustomer() + public function isForCustomer(): bool { return $this->tokenable_type == Customer::make()->getMorphClass(); } diff --git a/src/Traits/AuthorizesRequest.php b/src/Traits/AuthorizesRequest.php index 4aa4394..4042b99 100755 --- a/src/Traits/AuthorizesRequest.php +++ b/src/Traits/AuthorizesRequest.php @@ -1,5 +1,7 @@ json() instead'); } diff --git a/src/Traits/GuardsAttributes.php b/src/Traits/GuardsAttributes.php index f535aa8..13dfce3 100644 --- a/src/Traits/GuardsAttributes.php +++ b/src/Traits/GuardsAttributes.php @@ -1,5 +1,7 @@ scopes[static::class][$scope] = $implementation; } elseif ($scope instanceof Closure) { return $this->scopes[static::class][spl_object_hash($scope)] = $scope; } elseif ($scope instanceof Scope) { - return $this->scopes[static::class][get_class($scope)] = $scope; + return $this->scopes[static::class][$scope::class] = $scope; } throw new InvalidArgumentException('Global scope must be an instance of Closure or Scope.'); diff --git a/src/Traits/MergesIdAttribute.php b/src/Traits/MergesIdAttribute.php index 66ad7bf..226238f 100644 --- a/src/Traits/MergesIdAttribute.php +++ b/src/Traits/MergesIdAttribute.php @@ -1,12 +1,14 @@ toArray(); if (array_key_exists($model->getKeyName(), $array)) { diff --git a/src/Traits/RestExtendable.php b/src/Traits/RestExtendable.php index 75a8b87..0a8f121 100644 --- a/src/Traits/RestExtendable.php +++ b/src/Traits/RestExtendable.php @@ -1,5 +1,7 @@ create(), ['categories:*']); $category = Category::first(); @@ -19,7 +21,7 @@ ->assertJsonPath('data.0.attributes.name', $category->name); }); -it('shows a category', function() { +it('shows a category', function(): void { Sanctum::actingAs(User::factory()->create(), ['categories:*']); $category = Category::first(); @@ -30,7 +32,7 @@ ->assertJsonPath('data.attributes.name', $category->name); }); -it('shows a category with media relationship', function() { +it('shows a category with media relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['categories:*']); $category = Category::first(); $categoryMedia = $category->media()->create(['file_name' => 'test.jpg', 'tag' => 'thumb']); @@ -45,7 +47,7 @@ ->assertJsonPath('included.0.attributes.file_name', 'test.jpg'); }); -it('shows a category with menus relationship', function() { +it('shows a category with menus relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['categories:*']); $category = Category::first(); $categoryMenu = $category->menus()->create(['menu_name' => 'Test Menu']); @@ -60,7 +62,7 @@ ->assertJsonPath('included.0.attributes.menu_name', 'Test Menu'); }); -it('shows a category with locations relationship', function() { +it('shows a category with locations relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['categories:*']); $category = Category::first(); $categoryLocation = $category->locations()->create(['location_name' => 'Test Location']); @@ -75,7 +77,7 @@ ->assertJsonPath('included.0.attributes.location_name', 'Test Location'); }); -it('creates a category', function() { +it('creates a category', function(): void { Sanctum::actingAs(User::factory()->create(), ['categories:*']); $this @@ -86,7 +88,7 @@ ->assertJsonPath('data.attributes.name', 'Test Category'); }); -it('creates a category fails on validation', function() { +it('creates a category fails on validation', function(): void { Sanctum::actingAs(User::factory()->create(), ['categories:*']); $this @@ -94,7 +96,7 @@ ->assertStatus(422); }); -it('validates request data successfully', function() { +it('validates request data successfully', function(): void { $controller = new class extends ApiController { public array $restConfig = [ @@ -104,7 +106,7 @@ 'request' => null, ]; - public function restValidate() + public function restValidate(): array { return ['validated' => 'data']; } @@ -116,7 +118,7 @@ public function restValidate() expect($result)->toBe(['validated' => 'data']); }); -it('updates a category', function() { +it('updates a category', function(): void { Sanctum::actingAs(User::factory()->create(), ['categories:*']); $category = Category::first(); @@ -128,7 +130,7 @@ public function restValidate() ->assertJsonPath('data.attributes.name', 'Test Category'); }); -it('deletes a category', function() { +it('deletes a category', function(): void { Sanctum::actingAs(User::factory()->create(), ['categories:*']); $category = Category::first(); diff --git a/tests/ApiResources/CurrenciesTest.php b/tests/ApiResources/CurrenciesTest.php index 853a4d5..ef785ff 100644 --- a/tests/ApiResources/CurrenciesTest.php +++ b/tests/ApiResources/CurrenciesTest.php @@ -1,12 +1,14 @@ create(), ['currencies:*']); $currency = Currency::listFrontEnd()->first(); diff --git a/tests/ApiResources/CustomersTest.php b/tests/ApiResources/CustomersTest.php index bebd1ec..59a0391 100644 --- a/tests/ApiResources/CustomersTest.php +++ b/tests/ApiResources/CustomersTest.php @@ -1,12 +1,14 @@ create(), ['customers:*']); $this @@ -24,7 +26,7 @@ ->assertJsonMissing(['customer_id' => 9999]); }); -it('returns only authenticated customer', function() { +it('returns only authenticated customer', function(): void { Customer::factory()->count(5)->create(); Sanctum::actingAs($customer = Customer::factory()->create(), ['customers:*']); @@ -35,7 +37,7 @@ ->assertJsonCount(1, 'data'); }); -it('can not show unauthenticated customer', function() { +it('can not show unauthenticated customer', function(): void { $anotherCustomer = Customer::factory()->create(); Sanctum::actingAs(Customer::factory()->create(), ['customers:*']); @@ -44,7 +46,7 @@ ->assertStatus(404); }); -it('returns all customers', function() { +it('returns all customers', function(): void { Sanctum::actingAs(User::factory()->create(), ['customers:*']); Customer::factory()->count(5)->create(); $customer = Customer::first(); @@ -57,7 +59,7 @@ ->assertJsonCount(5, 'data'); }); -it('shows a customer', function() { +it('shows a customer', function(): void { Sanctum::actingAs(User::factory()->create(), ['customers:*']); $customer = Customer::factory()->create(); @@ -68,7 +70,7 @@ ->assertJsonPath('data.attributes.full_name', $customer->full_name); }); -it('shows a customer with addresses relationship', function() { +it('shows a customer with addresses relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['customers:*']); $customer = Customer::factory()->create(); $customerAddress = $customer->addresses()->create(['address_1' => '123 Test Address', 'country_id' => 1]); @@ -83,7 +85,7 @@ ->assertJsonPath('included.0.attributes.address_1', '123 Test Address'); }); -it('shows a customer with orders relationship', function() { +it('shows a customer with orders relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['customers:*']); $customer = Customer::factory()->create(); $customerOrder = $customer->orders()->create(['order_type' => 'collection']); @@ -98,7 +100,7 @@ ->assertJsonPath('included.0.attributes.order_type', 'collection'); }); -it('shows a customer with reservations relationship', function() { +it('shows a customer with reservations relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['customers:*']); $customer = Customer::factory()->create(); $customerReservation = $customer->reservations()->create(['email' => 'user-reservation@example.com']); @@ -113,7 +115,7 @@ ->assertJsonPath('included.0.attributes.email', 'user-reservation@example.com'); }); -it('creates a customer', function() { +it('creates a customer', function(): void { Sanctum::actingAs(User::factory()->create(), ['customers:*']); $this @@ -129,7 +131,7 @@ ->assertJsonPath('data.attributes.full_name', 'Test Customer'); }); -it('creates a customer as customer', function() { +it('creates a customer as customer', function(): void { $customer = Sanctum::actingAs(Customer::factory()->create(), ['customers:*']); $customer->currentAccessToken()->shouldReceive('isForCustomer')->andReturnTrue(); @@ -147,7 +149,7 @@ ->assertJsonPath('data.attributes.full_name', 'Test Customer'); }); -it('updates a customer', function() { +it('updates a customer', function(): void { Sanctum::actingAs(User::factory()->create(), ['customers:*']); $customer = Customer::factory()->create(); @@ -164,7 +166,7 @@ ->assertJsonPath('data.attributes.full_name', 'Test Customer'); }); -it('deletes a customer', function() { +it('deletes a customer', function(): void { Sanctum::actingAs(User::factory()->create(), ['customers:*']); $customer = Customer::factory()->create(); diff --git a/tests/ApiResources/DiningTablesTest.php b/tests/ApiResources/DiningTablesTest.php index e2026b4..6408449 100644 --- a/tests/ApiResources/DiningTablesTest.php +++ b/tests/ApiResources/DiningTablesTest.php @@ -1,5 +1,7 @@ create(), ['tables:*']); $diningTable = DiningTable::first(); @@ -18,7 +20,7 @@ ->assertJsonPath('data.0.attributes.name', $diningTable->name); }); -it('shows a dining table', function() { +it('shows a dining table', function(): void { Sanctum::actingAs(User::factory()->create(), ['tables:*']); $diningTable = DiningTable::first(); @@ -29,7 +31,7 @@ ->assertJsonPath('data.attributes.name', $diningTable->name); }); -it('creates a dining table', function() { +it('creates a dining table', function(): void { Sanctum::actingAs(User::factory()->create(), ['tables:*']); $this @@ -45,7 +47,7 @@ ->assertJsonPath('data.attributes.name', 'Test Table'); }); -it('updates a dining table', function() { +it('updates a dining table', function(): void { Sanctum::actingAs(User::factory()->create(), ['tables:*']); $diningTable = DiningTable::first(); @@ -61,7 +63,7 @@ ->assertJsonPath('data.attributes.name', 'Test Table updated'); }); -it('deletes a dining table', function() { +it('deletes a dining table', function(): void { Sanctum::actingAs(User::factory()->create(), ['tables:*']); $diningTable = DiningTable::first(); @@ -71,4 +73,3 @@ expect(DiningTable::find($diningTable->getKey()))->toBeNull(); }); - diff --git a/tests/ApiResources/LocationsTest.php b/tests/ApiResources/LocationsTest.php index a24414b..3c31c33 100644 --- a/tests/ApiResources/LocationsTest.php +++ b/tests/ApiResources/LocationsTest.php @@ -1,5 +1,7 @@ create(), ['locations:*']); Location::factory()->count(4)->create(); @@ -18,15 +20,15 @@ ->assertJsonCount(5, 'data'); }); -it('shows a location', function() { +it('shows a location', function(): void { Sanctum::actingAs(User::factory()->create(), ['locations:*']); $location = Location::first(); $this ->get(route('igniter.api.locations.show', [$location->getKey()])) ->assertOk() - ->assertJson(fn(AssertableJson $json) => $json - ->has('data.attributes', fn(AssertableJson $json) => $json + ->assertJson(fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json + ->has('data.attributes', fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json ->where('location_name', $location->location_name) ->where('location_email', $location->location_email) ->where('location_address_1', $location->location_address_1) @@ -34,7 +36,7 @@ )); }); -it('shows a location with media relationship', function() { +it('shows a location with media relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['locations:*']); $location = Location::first(); $locationMedia = $location->media()->create(['file_name' => 'test.jpg', 'tag' => 'thumb']); @@ -48,7 +50,7 @@ ->assertJsonPath('included.0.attributes.file_name', 'test.jpg'); }); -it('shows a location with working_hours relationship', function() { +it('shows a location with working_hours relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['locations:*']); $location = Location::first(); $location->working_hours()->create(['weekday' => 1, 'opening_time' => '09:00', 'closing_time' => '17:00']); @@ -63,7 +65,7 @@ ->assertJsonPath('included.0.attributes.closing_time', '17:00:00'); }); -it('shows a location with delivery_areas relationship', function() { +it('shows a location with delivery_areas relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['locations:*']); $location = Location::first(); $locationDeliveryArea = $location->delivery_areas()->create(['name' => 'Test Area']); @@ -76,7 +78,7 @@ ->assertJsonPath('included.0.attributes.name', 'Test Area'); }); -it('shows a location with reviews relationship', function() { +it('shows a location with reviews relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['locations:*']); $location = Location::first(); $locationReview = $location->reviews()->create(['review_text' => 'Test Review']); @@ -89,7 +91,7 @@ ->assertJsonPath('included.0.attributes.review_text', 'Test Review'); }); -it('creates a location', function() { +it('creates a location', function(): void { Sanctum::actingAs(User::factory()->create(), ['locations:*']); $this @@ -102,8 +104,8 @@ 'location_lng' => '0', ]) ->assertCreated() - ->assertJson(fn(AssertableJson $json) => $json - ->has('data.attributes', fn(AssertableJson $json) => $json + ->assertJson(fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json + ->has('data.attributes', fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json ->where('location_name', 'Test Location') ->where('location_email', 'test@location.tld') ->where('location_address_1', '123 Test Address') @@ -111,7 +113,7 @@ )); }); -it('updates a location', function() { +it('updates a location', function(): void { Sanctum::actingAs(User::factory()->create(), ['locations:*']); $location = Location::factory()->create(); @@ -125,8 +127,8 @@ 'location_lng' => '0', ]) ->assertOk() - ->assertJson(fn(AssertableJson $json) => $json - ->has('data.attributes', fn(AssertableJson $json) => $json + ->assertJson(fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json + ->has('data.attributes', fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json ->where('location_name', 'Test Location') ->where('location_email', 'test@location.tld') ->where('location_address_1', '123 Test Address') @@ -134,7 +136,7 @@ )); }); -it('deletes a location', function() { +it('deletes a location', function(): void { Sanctum::actingAs(User::factory()->create(), ['locations:*']); $location = Location::factory()->create(); diff --git a/tests/ApiResources/MenuItemOptionsTest.php b/tests/ApiResources/MenuItemOptionsTest.php index 149e8e9..af63f94 100644 --- a/tests/ApiResources/MenuItemOptionsTest.php +++ b/tests/ApiResources/MenuItemOptionsTest.php @@ -1,5 +1,7 @@ create(), ['menu_item_options:*']); $menuItemOption = MenuItemOption::first(); @@ -19,7 +21,7 @@ ->assertJsonPath('data.0.attributes.option_name', $menuItemOption->option_name); }); -it('shows a menu item option', function() { +it('shows a menu item option', function(): void { Sanctum::actingAs(User::factory()->create(), ['menu_item_options:*']); $menuItemOption = MenuItemOption::first(); @@ -27,16 +29,16 @@ ->get(route('igniter.api.menu_item_options.show', [$menuItemOption->getKey()])) ->assertOk() ->assertJsonPath('data.id', (string)$menuItemOption->getKey()) - ->assertJson(fn(AssertableJson $json) => $json + ->assertJson(fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json ->has('data.attributes.option') - ->has('data.attributes', fn(AssertableJson $json) => $json + ->has('data.attributes', fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json ->where('option_id', $menuItemOption->option->getKey()) ->etc(), )->etc(), ); }); -it('shows a menu item option with menu_option_values relationship', function() { +it('shows a menu item option with menu_option_values relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['menu_item_options:*']); $menuItemOption = MenuItemOption::first(); $menuItemOption->menu_option_values()->create(['option_value_id' => 1]); @@ -49,7 +51,7 @@ ->assertJsonPath('data.relationships.menu_option_values.data.0.type', 'menu_option_values'); }); -it('creates a menu item option', function() { +it('creates a menu item option', function(): void { Sanctum::actingAs(User::factory()->create(), ['menu_item_options:*']); $menuOption = MenuOption::first(); @@ -62,14 +64,14 @@ ], ]) ->assertCreated() - ->assertJson(fn(AssertableJson $json) => $json - ->has('data.attributes', fn(AssertableJson $json) => $json + ->assertJson(fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json + ->has('data.attributes', fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json ->where('option_id', $menuOption->getKey()) ->etc(), )); }); -it('updates a menu item option', function() { +it('updates a menu item option', function(): void { Sanctum::actingAs(User::factory()->create(), ['menu_item_options:*']); $menuItemOption = MenuItemOption::first(); @@ -78,14 +80,14 @@ 'option_id' => $menuItemOption->option->getKey(), ]) ->assertOk() - ->assertJson(fn(AssertableJson $json) => $json - ->has('data.attributes', fn(AssertableJson $json) => $json + ->assertJson(fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json + ->has('data.attributes', fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json ->where('option_id', $menuItemOption->option->getKey()) ->etc(), )->etc()); }); -it('deletes a menu item option', function() { +it('deletes a menu item option', function(): void { Sanctum::actingAs(User::factory()->create(), ['menu_item_options:*']); $menuItemOption = MenuItemOption::first(); diff --git a/tests/ApiResources/MenuOptionsTest.php b/tests/ApiResources/MenuOptionsTest.php index 888dc26..12f7ee7 100644 --- a/tests/ApiResources/MenuOptionsTest.php +++ b/tests/ApiResources/MenuOptionsTest.php @@ -1,5 +1,7 @@ create(), ['menu_options:*']); $menuOption = MenuOption::first(); @@ -18,7 +20,7 @@ ->assertJsonPath('data.0.attributes.option_name', $menuOption->option_name); }); -it('shows a menu option', function() { +it('shows a menu option', function(): void { Sanctum::actingAs(User::factory()->create(), ['menu_options:*']); $menuOption = MenuOption::first(); @@ -26,8 +28,8 @@ ->get(route('igniter.api.menu_options.show', [$menuOption->getKey()])) ->assertOk() ->assertJsonPath('data.id', (string)$menuOption->getKey()) - ->assertJson(fn(AssertableJson $json) => $json - ->has('data.attributes', fn(AssertableJson $json) => $json + ->assertJson(fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json + ->has('data.attributes', fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json ->where('option_name', $menuOption->option_name) ->where('display_type', $menuOption->display_type) ->etc(), @@ -35,7 +37,7 @@ ); }); -it('shows a menu option with option_values relationship', function() { +it('shows a menu option with option_values relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['menu_options:*']); $menuOption = MenuOption::first(); $menuOptionValue = $menuOption->option_values()->create(['name' => 'Test Value']); @@ -50,7 +52,7 @@ ->assertJsonPath('included.3.attributes.name', 'Test Value'); }); -it('creates a menu option', function() { +it('creates a menu option', function(): void { Sanctum::actingAs(User::factory()->create(), ['menu_options:*']); $menuOption = MenuOption::first(); @@ -60,15 +62,15 @@ 'display_type' => 'radio', ]) ->assertCreated() - ->assertJson(fn(AssertableJson $json) => $json - ->has('data.attributes', fn(AssertableJson $json) => $json + ->assertJson(fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json + ->has('data.attributes', fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json ->where('option_name', 'Test menu option') ->where('display_type', 'radio') ->etc(), )); }); -it('updates a menu option', function() { +it('updates a menu option', function(): void { Sanctum::actingAs(User::factory()->create(), ['menu_options:*']); $menuOption = MenuOption::first(); @@ -78,15 +80,15 @@ 'display_type' => 'radio', ]) ->assertOk() - ->assertJson(fn(AssertableJson $json) => $json - ->has('data.attributes', fn(AssertableJson $json) => $json + ->assertJson(fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json + ->has('data.attributes', fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json ->where('option_name', 'Test menu option') ->where('display_type', 'radio') ->etc(), )->etc()); }); -it('deletes a menu option', function() { +it('deletes a menu option', function(): void { Sanctum::actingAs(User::factory()->create(), ['menu_options:*']); $menuOption = MenuOption::first(); diff --git a/tests/ApiResources/MenusTest.php b/tests/ApiResources/MenusTest.php index aa77593..89e9c96 100644 --- a/tests/ApiResources/MenusTest.php +++ b/tests/ApiResources/MenusTest.php @@ -1,5 +1,7 @@ create(), ['menus:*']); $menu = Menu::first(); @@ -18,7 +20,7 @@ ->assertJsonPath('data.0.attributes.menu_name', $menu->menu_name); }); -it('shows a menu item', function() { +it('shows a menu item', function(): void { Sanctum::actingAs(User::factory()->create(), ['menus:*']); $menu = Menu::first(); @@ -26,8 +28,8 @@ ->get(route('igniter.api.menus.show', [$menu->getKey()])) ->assertOk() ->assertJsonPath('data.id', (string)$menu->getKey()) - ->assertJson(fn(AssertableJson $json) => $json - ->has('data.attributes', fn(AssertableJson $json) => $json + ->assertJson(fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json + ->has('data.attributes', fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json ->where('menu_name', $menu->menu_name) ->where('menu_price', $menu->menu_price) ->etc(), @@ -35,7 +37,7 @@ ); }); -it('shows a menu item with media relationship', function() { +it('shows a menu item with media relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['menus:*']); $menu = Menu::first(); $menuMedia = $menu->media()->create(['file_name' => 'test.jpg', 'tag' => 'thumb']); @@ -49,7 +51,7 @@ ->assertJsonPath('included.0.attributes.file_name', 'test.jpg'); }); -it('shows a menu item with categories relationship', function() { +it('shows a menu item with categories relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['menus:*']); $menu = Menu::first(); $menuCategory = $menu->categories()->create(['name' => 'Test Category']); @@ -63,7 +65,7 @@ ->assertJsonPath('included.0.attributes.name', 'Test Category'); }); -it('shows a menu item with menu_options relationship', function() { +it('shows a menu item with menu_options relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['menus:*']); $menu = Menu::first(); $menuOption = $menu->menu_options()->create(['min_selected' => 2, 'max_selected' => 4, 'option_id' => 1]); @@ -78,7 +80,7 @@ ->assertJsonPath('included.3.attributes.max_selected', 4); }); -it('shows a menu item with ingredients relationship', function() { +it('shows a menu item with ingredients relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['menus:*']); $menu = Menu::first(); $menuIngredient = $menu->ingredients()->create(['name' => 'Test Ingredient']); @@ -92,7 +94,7 @@ ->assertJsonPath('included.0.attributes.name', 'Test Ingredient'); }); -it('shows a menu item with mealtimes relationship', function() { +it('shows a menu item with mealtimes relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['menus:*']); $menu = Menu::first(); $menuMealtime = $menu->mealtimes()->create(['start_time' => '09:00', 'end_time' => '17:00']); @@ -107,7 +109,7 @@ ->assertJsonPath('included.0.attributes.end_time', '17:00:00'); }); -it('shows a menu item with stocks relationship', function() { +it('shows a menu item with stocks relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['menus:*']); $menu = Menu::first(); $menu->stocks()->create(['quantity' => 10]); @@ -119,7 +121,7 @@ ->assertJsonPath('data.relationships.stocks.data.0.type', 'stocks'); }); -it('creates a menu item', function() { +it('creates a menu item', function(): void { Sanctum::actingAs(User::factory()->create(), ['menus:*']); $menu = Menu::first(); @@ -129,15 +131,15 @@ 'menu_price' => 99.999, ]) ->assertCreated() - ->assertJson(fn(AssertableJson $json) => $json - ->has('data.attributes', fn(AssertableJson $json) => $json + ->assertJson(fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json + ->has('data.attributes', fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json ->where('menu_name', 'Test menu item') ->where('menu_price', 99.999) ->etc(), )); }); -it('updates a menu item', function() { +it('updates a menu item', function(): void { Sanctum::actingAs(User::factory()->create(), ['menus:*']); $menu = Menu::first(); @@ -147,15 +149,15 @@ 'menu_price' => 99.999, ]) ->assertOk() - ->assertJson(fn(AssertableJson $json) => $json - ->has('data.attributes', fn(AssertableJson $json) => $json + ->assertJson(fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json + ->has('data.attributes', fn(AssertableJson $json): \Illuminate\Testing\Fluent\AssertableJson => $json ->where('menu_name', 'Test menu item') ->where('menu_price', 99.999) ->etc(), )->etc()); }); -it('deletes a menu item', function() { +it('deletes a menu item', function(): void { Sanctum::actingAs(User::factory()->create(), ['menus:*']); $menu = Menu::first(); diff --git a/tests/ApiResources/OrdersTest.php b/tests/ApiResources/OrdersTest.php index 79c5ede..50c7e43 100644 --- a/tests/ApiResources/OrdersTest.php +++ b/tests/ApiResources/OrdersTest.php @@ -1,5 +1,7 @@ create(), ['orders:*']); Order::factory()->count(3)->create(); $order = Order::first(); @@ -24,7 +26,7 @@ ->assertJsonPath('data.0.attributes.email', $order->email); }); -it('shows an order', function() { +it('shows an order', function(): void { Sanctum::actingAs(User::factory()->create(), ['orders:*']); $order = Order::factory()->create(); @@ -35,7 +37,7 @@ ->assertJsonPath('data.attributes.email', $order->email); }); -it('shows an order with customer relationship', function() { +it('shows an order with customer relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['orders:*']); $order = Order::factory()->create(); $order->customer()->associate($orderCustomer = Customer::factory()->create(['first_name' => 'Test', 'last_name' => 'User']))->save(); @@ -49,7 +51,7 @@ ->assertJsonPath('included.0.attributes.full_name', 'Test User'); }); -it('shows an order with location relationship', function() { +it('shows an order with location relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['orders:*']); $order = Order::factory()->create(); $order->location()->associate($orderLocation = Location::factory()->create())->save(); @@ -63,7 +65,7 @@ ->assertJsonPath('included.0.attributes.location_name', $order->location->location_name); }); -it('shows an order with address relationship', function() { +it('shows an order with address relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['orders:*']); $order = Order::factory()->create(); $order->address()->associate( @@ -79,7 +81,7 @@ ->assertJsonPath('included.0.attributes.address_1', '123 Test St'); }); -it('shows an order with payment_method relationship', function() { +it('shows an order with payment_method relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['orders:*']); $order = Order::factory()->create([ 'payment' => 'cod', @@ -93,7 +95,7 @@ ->assertJsonPath('included.0.attributes.code', 'cod'); }); -it('shows an order with status relationship', function() { +it('shows an order with status relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['orders:*']); $order = Order::factory()->create(); $order->status()->associate($orderStatus = Status::isForOrder()->first())->save(); @@ -107,7 +109,7 @@ ->assertJsonPath('included.0.attributes.name', $order->status->name); }); -it('shows an order with status_history relationship', function() { +it('shows an order with status_history relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['orders:*']); $order = Order::factory()->create(); $orderStatusHistory = $order->status_history()->create(['status_id' => Status::isForOrder()->first()->getKey()]); @@ -121,7 +123,7 @@ ->assertJsonPath('included.0.attributes.status_id', $orderStatusHistory->status_id); }); -it('shows an order with assignee relationship', function() { +it('shows an order with assignee relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['orders:*']); $order = Order::factory()->create(); $assignee = User::factory()->create(); @@ -136,7 +138,7 @@ ->assertJsonPath('included.0.attributes.name', $assignee->name); }); -it('shows an order with assignee_group relationship', function() { +it('shows an order with assignee_group relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['orders:*']); $order = Order::factory()->create(); $order->assignee_group()->associate( @@ -152,7 +154,7 @@ ->assertJsonPath('included.0.attributes.user_group_name', 'Test Group'); }); -it('creates an order', function() { +it('creates an order', function(): void { Mail::fake(); Sanctum::actingAs(User::factory()->create(), ['orders:*']); @@ -195,7 +197,7 @@ ->assertJsonPath('data.attributes.email', 'test-user@domain.tld'); }); -it('updates an order', function() { +it('updates an order', function(): void { Mail::fake(); Sanctum::actingAs(User::factory()->create(), ['orders:*']); @@ -211,7 +213,7 @@ ->assertJsonPath('data.attributes.order_type', Location::COLLECTION); }); -it('deletes an order', function() { +it('deletes an order', function(): void { Sanctum::actingAs(User::factory()->create(), ['orders:*']); $order = Order::factory()->create(); diff --git a/tests/ApiResources/Requests/MenuItemOptionRequestTest.php b/tests/ApiResources/Requests/MenuItemOptionRequestTest.php index 33f4de2..c422a4d 100644 --- a/tests/ApiResources/Requests/MenuItemOptionRequestTest.php +++ b/tests/ApiResources/Requests/MenuItemOptionRequestTest.php @@ -1,10 +1,12 @@ attributes(); @@ -18,7 +20,7 @@ ->and($attributes)->toHaveKey('menu_option_values.*', lang('admin::lang.label_option_value_id')); }); -it('returns correct validation rules', function() { +it('returns correct validation rules', function(): void { $request = new MenuItemOptionRequest(); $rules = $request->rules(); diff --git a/tests/ApiResources/Requests/MenuOptionRequestTest.php b/tests/ApiResources/Requests/MenuOptionRequestTest.php index 9bff2cc..9252a91 100644 --- a/tests/ApiResources/Requests/MenuOptionRequestTest.php +++ b/tests/ApiResources/Requests/MenuOptionRequestTest.php @@ -1,10 +1,12 @@ attributes(); @@ -21,7 +23,7 @@ ->and($attributes)->toHaveKey('option_values.*.allergens.*', lang('igniter.cart::default.menus.label_allergens')); }); -it('returns correct validation rules', function() { +it('returns correct validation rules', function(): void { $request = new MenuOptionRequest(); $rules = $request->rules(); diff --git a/tests/ApiResources/Requests/OrderRequestTest.php b/tests/ApiResources/Requests/OrderRequestTest.php index 5339d5b..069e2ba 100644 --- a/tests/ApiResources/Requests/OrderRequestTest.php +++ b/tests/ApiResources/Requests/OrderRequestTest.php @@ -1,10 +1,12 @@ attributes(); @@ -25,7 +27,7 @@ ->and($attributes)->toHaveKey('address.country_id', lang('igniter.cart::default.checkout.label_country')); }); -it('returns correct validation rules', function() { +it('returns correct validation rules', function(): void { $request = new OrderRequest(); $request->setMethod('POST'); $request->merge([ diff --git a/tests/ApiResources/Requests/ReservationRequestTest.php b/tests/ApiResources/Requests/ReservationRequestTest.php index 1452196..861ddfd 100644 --- a/tests/ApiResources/Requests/ReservationRequestTest.php +++ b/tests/ApiResources/Requests/ReservationRequestTest.php @@ -1,10 +1,12 @@ attributes(); @@ -21,7 +23,7 @@ ->and($attributes)->toHaveKey('comment', lang('igniter.reservation::default.label_comment')); }); -it('returns correct validation rules', function() { +it('returns correct validation rules', function(): void { $request = new ReservationRequest(); $rules = $request->rules(); diff --git a/tests/ApiResources/ReservationsTest.php b/tests/ApiResources/ReservationsTest.php index 63d12a2..ee70d09 100644 --- a/tests/ApiResources/ReservationsTest.php +++ b/tests/ApiResources/ReservationsTest.php @@ -1,5 +1,7 @@ create(), ['reservations:*']); Reservation::factory()->count(3)->create(); $reservation = Reservation::first(); @@ -21,7 +23,7 @@ ->assertJsonPath('data.0.attributes.email', $reservation->email); }); -it('shows a reservation', function() { +it('shows a reservation', function(): void { Sanctum::actingAs(User::factory()->create(), ['reservations:*']); $reservation = Reservation::factory()->create(); @@ -32,7 +34,7 @@ ->assertJsonPath('data.attributes.email', $reservation->email); }); -it('shows a reservation with location relationship', function() { +it('shows a reservation with location relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['reservations:*']); $reservation = Reservation::factory()->create(); $reservation->location()->associate($reservationLocation = Location::factory()->create())->save(); @@ -46,7 +48,7 @@ ->assertJsonPath('included.0.attributes.location_name', $reservation->location->location_name); }); -it('shows a reservation with tables relationship', function() { +it('shows a reservation with tables relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['reservations:*']); $reservation = Reservation::factory()->create(); $reservationTable = $reservation->tables()->create(['name' => 'Table 1']); @@ -61,7 +63,7 @@ ->assertJsonPath('included.0.attributes.name', 'Table 1'); }); -it('shows a reservation with status relationship', function() { +it('shows a reservation with status relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['reservations:*']); $reservation = Reservation::factory()->create(); $reservation->status()->associate($reservationStatus = Status::factory()->create())->save(); @@ -75,7 +77,7 @@ ->assertJsonPath('included.0.attributes.status_name', $reservationStatus->status_name); }); -it('shows a reservation with status_history relationship', function() { +it('shows a reservation with status_history relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['reservations:*']); $reservation = Reservation::factory()->create(); $reservationStatusHistory = $reservation->status_history()->create(['status_id' => 1]); @@ -89,7 +91,7 @@ ->assertJsonPath('included.0.attributes.status_id', 1); }); -it('shows a reservation with assignee relationship', function() { +it('shows a reservation with assignee relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['reservations:*']); $reservation = Reservation::factory()->create(); $reservation->assignee()->associate($reservationAssignee = User::factory()->create())->save(); @@ -103,7 +105,7 @@ ->assertJsonPath('included.0.attributes.first_name', $reservationAssignee->first_name); }); -it('shows a reservation with assignee_group relationship', function() { +it('shows a reservation with assignee_group relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['reservations:*']); $reservation = Reservation::factory()->create(); $reservation->assignee_group()->associate($reservationAssigneeGroup = UserGroup::factory()->create())->save(); @@ -117,7 +119,7 @@ ->assertJsonPath('included.0.attributes.first_name', $reservation->assignee_group->first_name); }); -it('creates a reservation', function() { +it('creates a reservation', function(): void { Sanctum::actingAs(User::factory()->create(), ['reservations:*']); $this @@ -137,7 +139,7 @@ ->assertJsonPath('data.attributes.email', 'test-user@domain.tld'); }); -it('updates a reservation', function() { +it('updates a reservation', function(): void { Sanctum::actingAs(User::factory()->create(), ['reservations:*']); $reservation = Reservation::factory()->create(); @@ -157,7 +159,7 @@ ->assertJsonPath('data.attributes.reserve_time', '23:00'); }); -it('deletes a reservation', function() { +it('deletes a reservation', function(): void { Sanctum::actingAs(User::factory()->create(), ['reservations:*']); $reservation = Reservation::factory()->create(); diff --git a/tests/ApiResources/ReviewsTest.php b/tests/ApiResources/ReviewsTest.php index f819a7c..553dd6e 100644 --- a/tests/ApiResources/ReviewsTest.php +++ b/tests/ApiResources/ReviewsTest.php @@ -1,5 +1,7 @@ create(), ['reviews:*']); Review::factory()->count(3)->create(); $review = Review::first(); @@ -21,7 +23,7 @@ ->assertJsonPath('data.0.attributes.author', $review->author); }); -it('shows a review', function() { +it('shows a review', function(): void { Sanctum::actingAs(User::factory()->create(), ['reviews:*']); $review = Review::factory()->create(); @@ -32,7 +34,7 @@ ->assertJsonPath('data.attributes.author', $review->author); }); -it('shows a review with location relationship', function() { +it('shows a review with location relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['reviews:*']); $review = Review::factory()->create(); $review->location()->associate($reviewLocation = Location::factory()->create())->save(); @@ -46,7 +48,7 @@ ->assertJsonPath('included.0.attributes.location_name', $reviewLocation->location_name); }); -it('shows a review with customer relationship', function() { +it('shows a review with customer relationship', function(): void { Sanctum::actingAs(User::factory()->create(), ['reviews:*']); $review = Review::factory()->create(); $review->customer()->associate($reviewCustomer = Customer::factory()->create())->save(); @@ -60,7 +62,7 @@ ->assertJsonPath('included.0.attributes.first_name', $reviewCustomer->first_name); }); -it('creates a review', function() { +it('creates a review', function(): void { Sanctum::actingAs(User::factory()->create(), ['reviews:*']); $order = Order::factory()->create(); @@ -82,7 +84,7 @@ ->assertJsonPath('data.attributes.author', 'Test User'); }); -it('updates a review', function() { +it('updates a review', function(): void { Sanctum::actingAs(User::factory()->create(), ['reviews:*']); $order = Order::factory()->create(); @@ -108,7 +110,7 @@ ->assertJsonPath('data.attributes.review_text', 'This is an updated test review'); }); -it('deletes a review', function() { +it('deletes a review', function(): void { Sanctum::actingAs(User::factory()->create(), ['reviews:*']); $review = Review::factory()->create(); diff --git a/tests/Classes/AbstractRepositoryTest.php b/tests/Classes/AbstractRepositoryTest.php index 5872461..bae0309 100644 --- a/tests/Classes/AbstractRepositoryTest.php +++ b/tests/Classes/AbstractRepositoryTest.php @@ -1,5 +1,7 @@ repository = Mockery::mock(AbstractRepository::class)->makePartial()->shouldAllowMockingProtectedMethods(); $this->model = Mockery::mock(Model::class)->makePartial(); }); -it('finds a record by id', function() { +it('finds a record by id', function(): void { $this->repository->shouldReceive('createModel')->andReturn($this->model); $this->repository->shouldReceive('prepareQuery')->andReturn($this->model); $this->model->shouldReceive('find')->with(1, ['*'])->andReturn($this->model); @@ -28,7 +30,7 @@ expect($result)->toBe($this->model); }); -it('finds a record by id and applies location aware scope', function() { +it('finds a record by id and applies location aware scope', function(): void { $model = Mockery::mock(Order::class)->makePartial(); $this->repository->shouldReceive('createModel')->andReturn($model); $this->repository->shouldReceive('prepareQuery')->andReturn($model); @@ -39,7 +41,7 @@ expect($result)->toBe($model); }); -it('throws exception when record not found by id', function() { +it('throws exception when record not found by id', function(): void { $this->repository->shouldReceive('createModel')->andReturn($this->model); $this->repository->shouldReceive('prepareQuery')->andReturn($this->model); $this->model->shouldReceive('find')->with(1, ['*'])->andReturn(null); @@ -49,7 +51,7 @@ $this->repository->find(1); }); -it('finds a record by attribute', function() { +it('finds a record by attribute', function(): void { $this->repository->shouldReceive('createModel')->andReturn($this->model); $this->repository->shouldReceive('prepareQuery')->andReturn($this->model); $this->model->shouldReceive('where')->with('name', 'test')->andReturnSelf(); @@ -60,7 +62,7 @@ expect($result)->toBe($this->model); }); -it('returns paginated results when model does not have scopeListFrontEnd', function() { +it('returns paginated results when model does not have scopeListFrontEnd', function(): void { $noScopeListFrontEndModel = Mockery::mock(\Illuminate\Database\Eloquent\Model::class)->makePartial(); $this->repository->shouldReceive('createModel')->andReturn($noScopeListFrontEndModel); $this->repository->shouldReceive('paginate')->with(15, null)->andReturn('paginated_result'); @@ -70,7 +72,7 @@ expect($result)->toBe('paginated_result'); }); -it('returns frontend list results when model has scopeListFrontEnd', function() { +it('returns frontend list results when model has scopeListFrontEnd', function(): void { $builder = Mockery::mock(Builder::class); $builder->shouldReceive('listFrontEnd')->with(['option' => 'value'])->andReturn('frontend_list_result'); $this->repository->shouldReceive('createModel')->andReturn($this->model); @@ -81,7 +83,7 @@ expect($result)->toBe('frontend_list_result'); }); -it('paginates results with default parameters', function() { +it('paginates results with default parameters', function(): void { $model = Mockery::mock(Model::class); $builder = Mockery::mock(Builder::class); $this->repository->shouldReceive('createModel')->andReturn($this->model); @@ -93,7 +95,7 @@ expect($result)->toBe('paginated_result'); }); -it('paginates results with custom parameters', function() { +it('paginates results with custom parameters', function(): void { $model = Mockery::mock(Model::class); $query = Mockery::mock(Builder::class); $repository = Mockery::mock(AbstractRepository::class)->makePartial()->shouldAllowMockingProtectedMethods(); @@ -107,7 +109,7 @@ expect($result)->toBe('paginated_result'); }); -it('creates a new record', function() { +it('creates a new record', function(): void { $attributes = ['name' => 'test']; $customer = Mockery::mock(Customer::class)->makePartial(); $customer->shouldReceive('getKey')->andReturn(1); @@ -119,7 +121,7 @@ $this->repository->shouldReceive('fireSystemEvent')->with('api.repository.afterCreate', [$this->model, true]); $this->model->shouldReceive('reload'); - DB::shouldReceive('transaction')->andReturnUsing(function($callback) { + DB::shouldReceive('transaction')->andReturnUsing(function($callback): void { $callback(); }); @@ -128,14 +130,14 @@ expect($result)->toBe($this->model); }); -it('updates an existing record', function() { +it('updates an existing record', function(): void { $attributes = ['name' => 'updated']; $this->repository->shouldReceive('find')->with(1)->andReturn($this->model); $this->repository->shouldReceive('setModelAttributes')->with($this->model, $attributes); $this->repository->shouldReceive('fireSystemEvent')->with('api.repository.beforeUpdate', [$this->model, $attributes]); $this->repository->shouldReceive('fireSystemEvent')->with('api.repository.afterUpdate', [$this->model, true]); - DB::shouldReceive('transaction')->andReturnUsing(function($callback) { + DB::shouldReceive('transaction')->andReturnUsing(function($callback): void { $callback(); }); @@ -144,7 +146,7 @@ expect($result)->toBe($this->model); }); -it('returns null when model not found for update', function() { +it('returns null when model not found for update', function(): void { $attributes = ['name' => 'updated']; $this->repository->shouldReceive('find')->with(1)->andReturn(null); @@ -153,7 +155,7 @@ expect($result)->toBeNull(); }); -it('deletes a record by id', function() { +it('deletes a record by id', function(): void { $this->repository->shouldReceive('find')->with(1)->andReturn($this->model); $this->model->shouldReceive('delete')->andReturn(true); $this->repository->shouldReceive('fireSystemEvent')->with('api.repository.afterDelete', [$this->model, true]); @@ -163,7 +165,7 @@ expect($result)->toBe($this->model); }); -it('returns null when model not found for deletion', function() { +it('returns null when model not found for deletion', function(): void { $this->repository->shouldReceive('find')->with(1)->andReturn(null); $result = $this->repository->delete(1); @@ -171,24 +173,24 @@ expect($result)->toBeNull(); }); -it('throws exception when model class is missing', function() { - expect(function() { +it('throws exception when model class is missing', function(): void { + expect(function(): void { $this->repository->getModelClass(); })->toThrow(SystemException::class, 'Missing model on'); }); -it('throws exception when model class does not exist', function() { +it('throws exception when model class does not exist', function(): void { $repository = new class extends AbstractRepository { public $modelClass = 'NonExistentModel'; }; - expect(function() use ($repository) { + expect(function() use ($repository): void { $repository->createModel(); })->toThrow(SystemException::class, 'Class NonExistentModel does NOT exist!'); }); -it('creates model instance when model class exists', function() { +it('creates model instance when model class exists', function(): void { $repository = new class extends AbstractRepository { public $modelClass = TestModel::class; @@ -197,7 +199,7 @@ protected $hidden = ['hidden']; protected $visible = ['visible']; - protected function afterCreate() {} + protected function afterCreate(): void {} }; $result = $repository->createModel(); @@ -211,7 +213,7 @@ protected function afterCreate() {} $result->fireEvent('model.afterCreate'); }); -it('sets nested model attributes when attribute is nested', function() { +it('sets nested model attributes when attribute is nested', function(): void { $nestedModel = Mockery::mock(\Igniter\Flame\Database\Model::class)->makePartial(); $nestedModel->shouldReceive('isFillable')->andReturn(true); $nestedModel->shouldReceive('hasRelation')->andReturn(false); @@ -226,9 +228,7 @@ protected function afterCreate() {} $this->model->shouldReceive('extendableGet')->andReturn($nestedModel); $this->model->shouldReceive('getKeyName')->andReturn('id'); - request()->setUserResolver(function() { - return Mockery::mock(Customer::class); - }); + request()->setUserResolver(fn() => Mockery::mock(Customer::class)); $this->repository->shouldReceive('getCustomerAwareColumn')->andReturn('customer_id'); $this->repository->shouldReceive('setModelAttributes')->passthru(); @@ -239,7 +239,7 @@ protected function afterCreate() {} callProtectedMethod($this->repository, 'setModelAttributes', [$this->model, $saveData]); }); -it('applies location aware scope with absense constraint', function() { +it('applies location aware scope with absense constraint', function(): void { $repository = new class extends AbstractRepository { protected $modelClass = Order::class; @@ -259,7 +259,7 @@ protected function afterCreate() {} callProtectedMethod($repository, 'applyLocationAwareScope', [$query]); }); -it('applies location aware scope without absense constraint', function() { +it('applies location aware scope without absense constraint', function(): void { $repository = new class extends AbstractRepository { protected $modelClass = Order::class; @@ -280,11 +280,11 @@ protected function afterCreate() {} callProtectedMethod($repository, 'applyLocationAwareScope', [$query]); }); -it('does not apply location aware scope if config is not an array', function() { +it('does not apply location aware scope if config is not an array', function(): void { $repository = new class extends AbstractRepository { protected $modelClass = Order::class; - protected static $locationAwareConfig = null; + protected static $locationAwareConfig; }; $query = Mockery::mock(Builder::class); $query->shouldReceive('whereHasOrDoesntHaveLocation')->never(); @@ -293,7 +293,7 @@ protected function afterCreate() {} callProtectedMethod($repository, 'applyLocationAwareScope', [$query]); }); -it('does not apply location aware scope if model is not locationable', function() { +it('does not apply location aware scope if model is not locationable', function(): void { $repository = new class extends AbstractRepository { protected $modelClass = Order::class; @@ -308,7 +308,7 @@ protected function afterCreate() {} callProtectedMethod($repository, 'applyLocationAwareScope', [$query]); }); -it('does not apply location aware scope if user has no active locations', function() { +it('does not apply location aware scope if user has no active locations', function(): void { $repository = new class extends AbstractRepository { protected $modelClass = Order::class; diff --git a/tests/Classes/ApiControllerTest.php b/tests/Classes/ApiControllerTest.php index be94fc9..f7747a5 100644 --- a/tests/Classes/ApiControllerTest.php +++ b/tests/Classes/ApiControllerTest.php @@ -1,5 +1,7 @@ makePartial()->shouldAllowMockingProtectedMethods(); $controller->allowedActions = ['testAction' => true]; $controller->shouldReceive('checkAction')->andReturnTrue(); @@ -21,7 +23,7 @@ expect($response->getContent())->toBe(json_encode(['key' => 'value'])); }); -it('calls action and returns Responsable response', function() { +it('calls action and returns Responsable response', function(): void { $controller = Mockery::mock(ApiController::class)->makePartial()->shouldAllowMockingProtectedMethods(); $controller->allowedActions = ['testAction' => true]; $controller->shouldReceive('checkAction')->andReturnTrue(); @@ -33,7 +35,7 @@ expect($controller->callAction('testAction'))->toBe($responseMock); }); -it('calls action returns 404 response when checkAction fails', function() { +it('calls action returns 404 response when checkAction fails', function(): void { $controller = Mockery::mock(ApiController::class)->makePartial()->shouldAllowMockingProtectedMethods(); $controller->allowedActions = ['testAction' => true]; $controller->shouldReceive('checkAction')->andReturnFalse(); @@ -42,7 +44,7 @@ expect($controller->callAction('testAction')->getStatusCode())->toBe(404); }); -it('calls action throws exception when authorization fails', function() { +it('calls action throws exception when authorization fails', function(): void { $controller = Mockery::mock(ApiController::class)->makePartial()->shouldAllowMockingProtectedMethods(); $controller->allowedActions = ['testAction' => true]; $controller->shouldReceive('checkAction')->andReturnTrue(); @@ -55,14 +57,14 @@ expect(fn() => $controller->callAction('testAction'))->toThrow(AccessDeniedHttpException::class); }); -it('returns false if action is not in allowedActions', function() { +it('returns false if action is not in allowedActions', function(): void { $controller = Mockery::mock(ApiController::class)->makePartial(); $controller->allowedActions = []; expect($controller->checkAction('testAction'))->toBeFalse(); }); -it('returns false if method does not exist', function() { +it('returns false if method does not exist', function(): void { $controller = Mockery::mock(ApiController::class)->makePartial(); $controller->allowedActions = ['testAction' => true]; $controller->shouldReceive('methodExists')->andReturnFalse(); @@ -70,7 +72,7 @@ expect($controller->checkAction('testAction'))->toBeFalse(); }); -it('returns false if method is not found', function() { +it('returns false if method is not found', function(): void { $controller = new class extends ApiController { public array $allowedActions = ['testAction' => true]; @@ -81,12 +83,12 @@ expect($result)->toBeFalse(); }); -it('returns false if method is not public', function() { +it('returns false if method is not public', function(): void { $controller = new class extends ApiController { public array $allowedActions = ['testAction' => true]; - protected function testAction() + protected function testAction(): array { return ['key' => 'value']; } @@ -97,12 +99,12 @@ protected function testAction() expect($result)->toBeFalse(); }); -it('returns true if method is public', function() { +it('returns true if method is public', function(): void { $controller = new class extends ApiController { public array $allowedActions = ['testAction' => true]; - public function testAction() + public function testAction(): array { return ['key' => 'value']; } diff --git a/tests/Classes/ApiManagerTest.php b/tests/Classes/ApiManagerTest.php index 7e6488f..c0cf6be 100644 --- a/tests/Classes/ApiManagerTest.php +++ b/tests/Classes/ApiManagerTest.php @@ -1,5 +1,7 @@ apiManager = new ApiManager(); }); -it('returns resources when they are loaded', function() { +it('returns resources when they are loaded', function(): void { expect($this->apiManager->getResources())->toHaveCount(12); }); -it('returns empty array when resource is not found', function() { +it('returns empty array when resource is not found', function(): void { $resource = $this->apiManager->getResource('non-existent-endpoint'); expect($resource)->toBe([]); }); -it('returns current resource based on route name', function() { +it('returns current resource based on route name', function(): void { Route::shouldReceive('currentRouteName')->andReturn('api.categories.index'); $currentResource = $this->apiManager->getCurrentResource(); @@ -33,7 +35,7 @@ expect($currentResource->endpoint)->toBe('categories'); }); -it('returns current action based on route action', function() { +it('returns current action based on route action', function(): void { Route::shouldReceive('currentRouteAction')->andReturn('TestController@index'); $currentAction = $this->apiManager->getCurrentAction(); @@ -41,13 +43,13 @@ expect($currentAction)->toBe('index'); }); -it('registers routes when database and table exist', function() { +it('registers routes when database and table exist', function(): void { $router = Mockery::mock(Router::class); $routerRegister = Mockery::mock(RouteRegistrar::class); Route::shouldReceive('middleware')->andReturn($routerRegister); $routerRegister->shouldReceive('as')->andReturnSelf(); $routerRegister->shouldReceive('prefix')->with('api')->andReturnSelf(); - $routerRegister->shouldReceive('group')->andReturnUsing(function($callback) use ($router) { + $routerRegister->shouldReceive('group')->andReturnUsing(function($callback) use ($router): true { $callback($router); return true; @@ -65,7 +67,7 @@ ApiManager::registerRoutes(); }); -it('does not register routes when database does not exist', function() { +it('does not register routes when database does not exist', function(): void { Igniter::shouldReceive('hasDatabase')->andReturnFalse(); Schema::shouldReceive('hasTable')->with('igniter_api_resources')->never(); Route::shouldReceive('middleware')->never(); @@ -73,7 +75,7 @@ ApiManager::registerRoutes(); }); -it('does not register routes when table does not exist', function() { +it('does not register routes when table does not exist', function(): void { Igniter::shouldReceive('hasDatabase')->andReturnTrue(); Schema::shouldReceive('hasTable')->with('igniter_api_resources')->andReturn(false); Route::shouldReceive('middleware')->never(); @@ -81,13 +83,13 @@ ApiManager::registerRoutes(); }); -it('skips invalid controllers when registering routes', function() { +it('skips invalid controllers when registering routes', function(): void { $router = Mockery::mock(Router::class); $routerRegister = Mockery::mock(RouteRegistrar::class); Route::shouldReceive('middleware')->andReturn($routerRegister); $routerRegister->shouldReceive('as')->andReturnSelf(); $routerRegister->shouldReceive('prefix')->with('api')->andReturnSelf(); - $routerRegister->shouldReceive('group')->andReturnUsing(function($callback) use ($router) { + $routerRegister->shouldReceive('group')->andReturnUsing(function($callback) use ($router): true { $callback($router); return true; diff --git a/tests/Console/IssueApiTokenTest.php b/tests/Console/IssueApiTokenTest.php index d05f9cc..4efb612 100644 --- a/tests/Console/IssueApiTokenTest.php +++ b/tests/Console/IssueApiTokenTest.php @@ -1,5 +1,7 @@ create(['email' => 'admin@example.com']); $command = Mockery::mock(IssueApiToken::class)->makePartial(); $command->shouldReceive('option')->with('name')->andReturn('Test Token'); @@ -19,7 +21,7 @@ $command->handle(); }); -it('issues token for customer user with valid email', function() { +it('issues token for customer user with valid email', function(): void { Customer::factory()->create(['email' => 'customer@example.com']); $command = Mockery::mock(IssueApiToken::class)->makePartial(); $command->shouldReceive('option')->with('name')->andReturn('Test Token'); @@ -31,7 +33,7 @@ $command->handle(); }); -it('returns error when user does not exist', function() { +it('returns error when user does not exist', function(): void { $command = Mockery::mock(IssueApiToken::class)->makePartial(); $command->shouldReceive('option')->with('name')->andReturn('Test Token'); $command->shouldReceive('option')->with('email')->andReturn('nonexistent@example.com'); diff --git a/tests/Exceptions/AuthenticationExceptionTest.php b/tests/Exceptions/AuthenticationExceptionTest.php index 66d7389..7de8eec 100644 --- a/tests/Exceptions/AuthenticationExceptionTest.php +++ b/tests/Exceptions/AuthenticationExceptionTest.php @@ -1,10 +1,12 @@ render(null); expect($response->getStatusCode())->toBe(401) diff --git a/tests/Exceptions/ErrorHandlerTest.php b/tests/Exceptions/ErrorHandlerTest.php index d53780c..14259b8 100644 --- a/tests/Exceptions/ErrorHandlerTest.php +++ b/tests/Exceptions/ErrorHandlerTest.php @@ -1,5 +1,7 @@ handler = Mockery::mock(ExceptionHandler::class); $this->request = Mockery::mock(Request::class); $this->errorHandler = new ErrorHandler($this->handler, [ @@ -22,7 +24,7 @@ ], false); }); -it('renders generic response for non-API route', function() { +it('renders generic response for non-API route', function(): void { $this->request->shouldReceive('routeIs')->with('igniter.api.*')->andReturn(false); $exception = new Exception('Test Exception'); @@ -31,7 +33,7 @@ expect($response)->toBeNull(); }); -it('renders 404 response for ModelNotFoundException', function() { +it('renders 404 response for ModelNotFoundException', function(): void { $this->request->shouldReceive('routeIs')->with('igniter.api.*')->andReturn(true); $exception = new ModelNotFoundException(); @@ -40,7 +42,7 @@ expect($response->getStatusCode())->toBe(404); }); -it('renders 422 response for ValidationException', function() { +it('renders 422 response for ValidationException', function(): void { $this->request->shouldReceive('routeIs')->with('igniter.api.*')->andReturn(true); $exception = Mockery::mock(ValidationException::class); $exception->shouldReceive('errors')->andReturn(['field' => ['error']]); @@ -52,7 +54,7 @@ ->and($response->getOriginalContent()['errors'])->toBe(['field' => ['error']]); }); -it('returns 500 status code for invalid status code above 599', function() { +it('returns 500 status code for invalid status code above 599', function(): void { $this->request->shouldReceive('routeIs')->with('igniter.api.*')->andReturn(true); $exception = new Exception('Test Exception', 600); @@ -61,7 +63,7 @@ expect($response->getStatusCode())->toBe(500); }); -it('renders 500 response for generic exception', function() { +it('renders 500 response for generic exception', function(): void { $this->request->shouldReceive('routeIs')->with('igniter.api.*')->andReturn(true); $exception = new Exception('Test Exception'); @@ -71,7 +73,7 @@ ->and($response->getOriginalContent()['message'])->toBe('Test Exception'); }); -it('renders debug information when in debug mode', function() { +it('renders debug information when in debug mode', function(): void { $this->request->shouldReceive('routeIs')->with('igniter.api.*')->andReturn(true); $exception = new Exception('Test Exception'); diff --git a/tests/Exceptions/ResourceExceptionTest.php b/tests/Exceptions/ResourceExceptionTest.php index 4382e07..0c64d9f 100644 --- a/tests/Exceptions/ResourceExceptionTest.php +++ b/tests/Exceptions/ResourceExceptionTest.php @@ -1,18 +1,20 @@ getErrors())->toBeInstanceOf(MessageBag::class) ->and($exception->getErrors()->isEmpty())->toBeTrue(); }); -it('creates ResourceException with message bag from array', function() { +it('creates ResourceException with message bag from array', function(): void { $errors = ['field' => ['Error message']]; $exception = new ResourceException('Error message', $errors); @@ -20,28 +22,28 @@ ->and($exception->getErrors()->get('field'))->toBe(['Error message']); }); -it('creates ResourceException with message bag instance', function() { +it('creates ResourceException with message bag instance', function(): void { $errors = new MessageBag(['field' => ['Error message']]); $exception = new ResourceException('Error message', $errors); expect($exception->getErrors())->toBe($errors); }); -it('returns errors as array', function() { +it('returns errors as array', function(): void { $errors = ['field' => ['Error message']]; $exception = new ResourceException('Error message', $errors); expect($exception->errors())->toBe($errors); }); -it('determines if message bag has errors', function() { +it('determines if message bag has errors', function(): void { $errors = ['field' => ['Error message']]; $exception = new ResourceException('Error message', $errors); expect($exception->hasErrors())->toBeTrue(); }); -it('determines if message bag is empty', function() { +it('determines if message bag is empty', function(): void { $exception = new ResourceException('Error message', []); expect($exception->hasErrors())->toBeFalse(); diff --git a/tests/ExtensionTest.php b/tests/ExtensionTest.php index 193764c..2493e26 100644 --- a/tests/ExtensionTest.php +++ b/tests/ExtensionTest.php @@ -1,5 +1,7 @@ toHaveKey('tables'); }); -it('returns an array with the correct permission structure', function() { +it('returns an array with the correct permission structure', function(): void { $result = (new Extension(app()))->registerPermissions(); expect($result)->toBe([ @@ -39,11 +41,11 @@ ]); }); -it('returns the correct default serializer', function() { +it('returns the correct default serializer', function(): void { expect(config('fractal.default_serializer'))->toBe(JsonApiSerializer::class); }); -it('creates access token using http', function($email, $isAdmin, $deviceName, $abilities) { +it('creates access token using http', function($email, $isAdmin, $deviceName, $abilities): void { $attributes = [ 'email' => $email, 'status' => 1, @@ -69,7 +71,7 @@ ['customer@domain.tld', false, 'Test Device', ['*']], ]); -it('creates access token using console command', function($email, $isAdmin, $deviceName, $abilities) { +it('creates access token using console command', function($email, $isAdmin, $deviceName, $abilities): void { $attributes = [ 'email' => $email, 'status' => 1, @@ -91,12 +93,12 @@ ['customer@domain.tld', false, 'Test Device', ['*']], ]); -it('configures rate limiting with user id', function() { +it('configures rate limiting with user id', function(): void { $request = Mockery::mock(Request::class); $request->shouldReceive('user')->andReturn((object)['id' => 1]); $request->shouldReceive('ip')->andReturn('127.0.0.1'); - RateLimiter::shouldReceive('for')->with('api', Mockery::on(function($callback) use ($request) { + RateLimiter::shouldReceive('for')->with('api', Mockery::on(function($callback) use ($request): true { $callback($request); return true; }))->andReturnSelf()->once(); diff --git a/tests/Fixtures/TestModel.php b/tests/Fixtures/TestModel.php index 491b7e2..80b40cc 100644 --- a/tests/Fixtures/TestModel.php +++ b/tests/Fixtures/TestModel.php @@ -1,5 +1,7 @@ controller = new CreateToken(); }); -it('creates token for valid credentials', function(bool $isAdmin, Model $model) { +it('creates token for valid credentials', function(bool $isAdmin, Model $model): void { $this->post(route('igniter.api.token.create'), [ 'email' => $model->email, 'password' => 'password', @@ -31,7 +33,7 @@ ])] ]); -it('throws validation exception for invalid admin credentials', function(bool $isAdmin, Model $model) { +it('throws validation exception for invalid admin credentials', function(bool $isAdmin, Model $model): void { $response = $this->post(route('igniter.api.token.create'), [ 'email' => $model->email, 'password' => 'wrongpassword', @@ -50,7 +52,7 @@ ])] ]); -it('throws validation exception for inactive user', function(bool $isAdmin, Model $model) { +it('throws validation exception for inactive user', function(bool $isAdmin, Model $model): void { $response = $this->post(route('igniter.api.token.create'), [ 'email' => $model->email, 'password' => 'password', diff --git a/tests/Http/Controllers/ResourcesTest.php b/tests/Http/Controllers/ResourcesTest.php index 3f920f1..4dd9199 100644 --- a/tests/Http/Controllers/ResourcesTest.php +++ b/tests/Http/Controllers/ResourcesTest.php @@ -1,16 +1,18 @@ get(route('igniter.api.resources')) ->assertOk(); }); -it('fails to load create resource page', function() { +it('fails to load create resource page', function(): void { actingAsSuperUser() ->get(route('igniter.api.resources', ['slug' => 'create'])) ->assertStatus(500); @@ -23,7 +25,7 @@ ->assertStatus(500); }); -it('loads edit resource page', function() { +it('loads edit resource page', function(): void { $resource = Resource::factory()->create([ 'endpoint' => 'categories', ]); @@ -33,7 +35,7 @@ ->assertOk(); }); -it('loads resource preview page', function() { +it('loads resource preview page', function(): void { $resource = Resource::factory()->create([ 'endpoint' => 'categories', ]); @@ -43,7 +45,7 @@ ->assertOk(); }); -it('updates resource', function() { +it('updates resource', function(): void { $resource = Resource::factory()->create(); actingAsSuperUser() @@ -63,7 +65,7 @@ ->endpoint->toBe($resource->endpoint); }); -it('deletes resource', function() { +it('deletes resource', function(): void { $resource = Resource::factory()->create(); actingAsSuperUser() diff --git a/tests/Http/Controllers/TokensTest.php b/tests/Http/Controllers/TokensTest.php index 81b5ae0..a1c3681 100644 --- a/tests/Http/Controllers/TokensTest.php +++ b/tests/Http/Controllers/TokensTest.php @@ -1,14 +1,16 @@ get(route('igniter.api.tokens')) ->assertOk(); }); -it('deletes token on tokens page', function() { +it('deletes token on tokens page', function(): void { $token = \Igniter\Api\Models\Token::factory()->create(); actingAsSuperUser() diff --git a/tests/Http/Middleware/AuthenticateTest.php b/tests/Http/Middleware/AuthenticateTest.php index 3913711..f912ed4 100644 --- a/tests/Http/Middleware/AuthenticateTest.php +++ b/tests/Http/Middleware/AuthenticateTest.php @@ -1,5 +1,7 @@ middleware = Mockery::mock(Authenticate::class) ->makePartial() ->shouldAllowMockingProtectedMethods(); $this->request = Mockery::mock(Request::class); - $this->next = function($request) { - return 'next'; - }; + $this->next = (fn($request): string => 'next'); }); -it('handles request with default guard', function() { +it('handles request with default guard', function(): void { config()->set('igniter.api.guard', null); $this->middleware->shouldReceive('authenticate')->with($this->request, [])->andReturn(true); @@ -27,7 +27,7 @@ expect($response)->toBe('next'); }); -it('handles request with custom guard', function() { +it('handles request with custom guard', function(): void { config()->set('igniter.api.guard', 'api'); $this->middleware->shouldReceive('authenticate')->with($this->request, ['api'])->andReturn(true); @@ -36,7 +36,7 @@ expect($response)->toBe('next'); }); -it('throws custom authentication exception on failure', function() { +it('throws custom authentication exception on failure', function(): void { config()->set('igniter.api.guard', 'api'); $this->middleware->shouldReceive('authenticate') ->with($this->request, ['api']) diff --git a/tests/Http/Requests/ResourceRequestTest.php b/tests/Http/Requests/ResourceRequestTest.php index 7b76262..43a47ce 100644 --- a/tests/Http/Requests/ResourceRequestTest.php +++ b/tests/Http/Requests/ResourceRequestTest.php @@ -1,10 +1,12 @@ attributes(); @@ -16,7 +18,7 @@ ->and($attributes)->toHaveKey('meta.authorization', lang('igniter.api::default.label_authorization')); }); -it('returns correct validation rules', function() { +it('returns correct validation rules', function(): void { $request = new ResourceRequest(); $rules = $request->rules(); diff --git a/tests/Listeners/TokenEventSubscriberTest.php b/tests/Listeners/TokenEventSubscriberTest.php index 5578f8f..78adcbd 100644 --- a/tests/Listeners/TokenEventSubscriberTest.php +++ b/tests/Listeners/TokenEventSubscriberTest.php @@ -1,5 +1,7 @@ subscriber = new TokenEventSubscriber(); $this->token = Token::factory()->create(); $this->event = new TokenAuthenticated($this->token); $this->route = Mockery::mock(Route::class); - request()->setRouteResolver(function() { - return $this->route; - }); + request()->setRouteResolver(fn() => $this->route); }); -it('returns access token for allowed group all', function() { +it('returns access token for allowed group all', function(): void { RouteFacade::shouldReceive('currentRouteName')->andReturn('api.categories.index'); $this->route->shouldReceive('currentRouteName')->andReturn('api.categories.index'); $this->route->shouldReceive('getActionMethod')->andReturn('index'); @@ -32,7 +32,7 @@ expect($result)->token->toBe($this->token->token); }); -it('throws unauthorized exception for missing access token', function() { +it('throws unauthorized exception for missing access token', function(): void { RouteFacade::shouldReceive('currentRouteName')->andReturn('api.categories.store'); $this->route->shouldReceive('currentRouteName')->andReturn('api.categories.store'); $this->route->shouldReceive('getActionMethod')->andReturn('store'); @@ -45,7 +45,7 @@ $this->subscriber->handleTokenAuthenticated($this->event); }); -it('throws access denied exception for restricted group', function() { +it('throws access denied exception for restricted group', function(): void { RouteFacade::shouldReceive('currentRouteName')->andReturn('api.categories.store'); $this->route->shouldReceive('currentRouteName')->andReturn('api.categories.store'); $this->route->shouldReceive('getActionMethod')->andReturn('store'); @@ -58,7 +58,7 @@ $this->subscriber->handleTokenAuthenticated($this->event); }); -it('throws access denied exception for guest group', function() { +it('throws access denied exception for guest group', function(): void { $subscriber = Mockery::mock(TokenEventSubscriber::class)->makePartial()->shouldAllowMockingProtectedMethods(); $subscriber->shouldReceive('getAllowedGroup')->andReturn('guest'); @@ -68,7 +68,7 @@ $subscriber->handleTokenAuthenticated($this->event); }); -it('throws access denied exception for customer group', function() { +it('throws access denied exception for customer group', function(): void { $subscriber = Mockery::mock(TokenEventSubscriber::class)->makePartial()->shouldAllowMockingProtectedMethods(); $subscriber->shouldReceive('getAllowedGroup')->andReturn('customer'); $this->event->token->tokenable_type = 'users'; @@ -79,7 +79,7 @@ $subscriber->handleTokenAuthenticated($this->event); }); -it('returns tokenable for valid access token', function() { +it('returns tokenable for valid access token', function(): void { RouteFacade::shouldReceive('currentRouteName')->andReturn('api.categories.store'); $this->route->shouldReceive('currentRouteName')->andReturn('api.categories.store'); $this->route->shouldReceive('getActionMethod')->andReturn('store'); diff --git a/tests/Models/ResourceTest.php b/tests/Models/ResourceTest.php index 0cbdf05..96f4547 100644 --- a/tests/Models/ResourceTest.php +++ b/tests/Models/ResourceTest.php @@ -1,12 +1,14 @@ 'test-endpoint']) extends Resource { public function testGet() @@ -19,14 +21,14 @@ public function testGet() expect($result)->toBe($resource->testGet()); }); -it('returns base endpoint attribute correctly', function() { +it('returns base endpoint attribute correctly', function(): void { $resource = new Resource(['endpoint' => 'test-endpoint']); $result = $resource->getBaseEndpointAttribute(null); expect($result)->toBe('/api/test-endpoint'); }); -it('returns controller attribute correctly', function() { +it('returns controller attribute correctly', function(): void { $resource = Mockery::mock(Resource::class)->makePartial(); $resource->shouldReceive('listRegisteredResources')->andReturn([ 'test-endpoint' => ['controller' => 'TestController'], @@ -38,7 +40,7 @@ public function testGet() expect($result)->toBe('TestController'); }); -it('syncs all resources correctly', function() { +it('syncs all resources correctly', function(): void { Resource::factory()->create(['endpoint' => 'endpoint1', 'is_custom' => true]); Resource::factory()->create(['endpoint' => 'endpoint2']); Resource::clearInternalCache(); @@ -48,13 +50,13 @@ public function testGet() expect(Resource::where('endpoint', 'endpoint2')->exists())->toBeFalse(); }); -it('returns all resources keyed by endpoint', function() { +it('returns all resources keyed by endpoint', function(): void { expect(Resource::getResources())->not->toBeEmpty(); }); -it('lists all resources correctly', function() { +it('lists all resources correctly', function(): void { Resource::clearInternalCache(); - (new Resource)->registerCallback(function(Resource $resource) { + (new Resource)->registerCallback(function(Resource $resource): void { $resource->registerResources([ 'endpoint1' => ['controller' => 'TestController'], 'endpoint2' => 'TestController', @@ -65,7 +67,7 @@ public function testGet() Resource::clearInternalCache(); }); -it('configures resource model correctly', function() { +it('configures resource model correctly', function(): void { $resource = new Resource; expect(class_uses_recursive($resource))->toContain(HasPermalink::class) diff --git a/tests/Models/TokenTest.php b/tests/Models/TokenTest.php index a96a72b..e201e1a 100644 --- a/tests/Models/TokenTest.php +++ b/tests/Models/TokenTest.php @@ -1,5 +1,7 @@ makePartial(); $tokenable->shouldReceive('tokens->create')->andReturn(new Token(['id' => 1, 'token' => 'hashedToken'])); $name = 'testToken'; @@ -20,7 +22,7 @@ expect($result)->toBeInstanceOf(NewAccessToken::class); }); -it('determines if the token belongs to an admin', function() { +it('determines if the token belongs to an admin', function(): void { $token = new Token(); $token->tokenable_type = User::make()->getMorphClass(); @@ -29,7 +31,7 @@ expect($result)->toBeTrue(); }); -it('determines if the token belongs to a customer', function() { +it('determines if the token belongs to a customer', function(): void { $token = new Token(); $token->tokenable_type = Customer::make()->getMorphClass(); @@ -38,7 +40,7 @@ expect($result)->toBeTrue(); }); -it('configures token model correctly', function() { +it('configures token model correctly', function(): void { $token = new Token(); expect($token->getTable())->toBe('igniter_api_access_tokens'); diff --git a/tests/Pest.php b/tests/Pest.php index a1054b8..9b755d1 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,5 +1,7 @@ in(__DIR__); diff --git a/tests/Traits/AuthorizesRequestTest.php b/tests/Traits/AuthorizesRequestTest.php index e87fdb5..1922516 100644 --- a/tests/Traits/AuthorizesRequestTest.php +++ b/tests/Traits/AuthorizesRequestTest.php @@ -1,5 +1,7 @@ toBe('accessToken'); }); -it('returns the authenticated user', function() { +it('returns the authenticated user', function(): void { $traitObject = new class { use AuthorizesRequest; @@ -44,7 +46,7 @@ public function testUser() expect($result)->toBe($user); }); -it('returns the auth instance', function() { +it('returns the auth instance', function(): void { $traitObject = new class { use AuthorizesRequest; @@ -62,7 +64,7 @@ public function testAuth() expect($result)->toBe($auth); }); -it('returns the token using getToken method', function() { +it('returns the token using getToken method', function(): void { $traitObject = new class { use AuthorizesRequest; @@ -81,7 +83,7 @@ public function testGetToken() expect($result)->toBe('accessToken'); }); -it('checks if the token has the given ability', function() { +it('checks if the token has the given ability', function(): void { $traitObject = new class { use AuthorizesRequest; @@ -95,7 +97,7 @@ public function testTokenCan() $user->shouldReceive('tokenCan')->with('*')->andReturn(true); request()->setUserResolver(fn() => $user); - $result = $traitObject->testTokenCan('*'); + $result = $traitObject->testTokenCan(); expect($result)->toBeTrue(); }); diff --git a/tests/Traits/CreatesResponseTest.php b/tests/Traits/CreatesResponseTest.php index 33e5b5b..3d7cf8a 100644 --- a/tests/Traits/CreatesResponseTest.php +++ b/tests/Traits/CreatesResponseTest.php @@ -1,22 +1,24 @@ response(); })->toThrow(\LogicException::class, 'Deprecated, use Fractal::create() or response()->json() instead'); }); -it('returns a Fractal instance from fractal method', function() { +it('returns a Fractal instance from fractal method', function(): void { $traitObject = new class { use CreatesResponse; diff --git a/tests/Traits/GuardsAttributesTest.php b/tests/Traits/GuardsAttributesTest.php index 07edd2f..90e218e 100644 --- a/tests/Traits/GuardsAttributesTest.php +++ b/tests/Traits/GuardsAttributesTest.php @@ -1,10 +1,12 @@ traitObject = new class extends AbstractRepository { protected $fillable = ['name', 'email']; @@ -15,7 +17,7 @@ protected $visible = ['name', 'email']; - public function getNameAttribute($value) + public function getNameAttribute($value): string { return 'John Doe'; } @@ -27,43 +29,43 @@ public function setNameAttribute($value) }; }); -it('returns fillable attributes correctly', function() { +it('returns fillable attributes correctly', function(): void { $result = $this->traitObject->getFillable(); expect($result)->toBe(['name', 'email']); }); -it('returns guarded attributes correctly', function() { +it('returns guarded attributes correctly', function(): void { $result = $this->traitObject->getGuarded(); expect($result)->toBe(['password']); }); -it('returns hidden attributes correctly', function() { +it('returns hidden attributes correctly', function(): void { $result = $this->traitObject->getHidden(); expect($result)->toBe(['password']); }); -it('returns visible attributes correctly', function() { +it('returns visible attributes correctly', function(): void { $result = $this->traitObject->getVisible(); expect($result)->toBe(['name', 'email']); }); -it('sets model attribute using mutator', function() { +it('sets model attribute using mutator', function(): void { $result = $this->traitObject->setModelAttribute('name', 'John'); expect($result)->toBe($this->traitObject); }); -it('gets model attribute using mutator', function() { +it('gets model attribute using mutator', function(): void { $result = $this->traitObject->getModelAttribute('name', 'John'); expect($result)->toBe('John Doe'); }); -it('determines if a get mutator exists for an attribute', function() { +it('determines if a get mutator exists for an attribute', function(): void { $result = $this->traitObject->hasGetMutator('name'); expect($result)->toBeTrue(); diff --git a/tests/Traits/HasGlobalScopesTest.php b/tests/Traits/HasGlobalScopesTest.php index 8f10c45..d0bdbae 100644 --- a/tests/Traits/HasGlobalScopesTest.php +++ b/tests/Traits/HasGlobalScopesTest.php @@ -1,5 +1,7 @@ addGlobalScope('testScope', $closure); expect($result)->toBe($closure); }); -it('adds a global scope using a closure', function() { +it('adds a global scope using a closure', function(): void { $traitObject = new class { use HasGlobalScopes; }; - $closure = function() {}; + $closure = function(): void {}; $result = $traitObject->addGlobalScope($closure); expect($result)->toBe($closure); }); -it('adds a global scope using a Scope instance', function() { +it('adds a global scope using a Scope instance', function(): void { $traitObject = new class { use HasGlobalScopes; @@ -40,23 +42,23 @@ expect($result)->toBe($scope); }); -it('throws an exception when adding an invalid global scope', function() { +it('throws an exception when adding an invalid global scope', function(): void { $traitObject = new class { use HasGlobalScopes; }; - expect(function() use ($traitObject) { + expect(function() use ($traitObject): void { $traitObject->addGlobalScope('invalidScope'); })->toThrow(\InvalidArgumentException::class, 'Global scope must be an instance of Closure or Scope.'); }); -it('applies all registered global scopes to the query', function() { +it('applies all registered global scopes to the query', function(): void { $traitObject = new class { use HasGlobalScopes; - public function testApplyScopes($query) + public function testApplyScopes($query): void { $this->applyScopes($query); } @@ -65,6 +67,6 @@ public function testApplyScopes($query) $scope = Mockery::mock(Scope::class); $traitObject->addGlobalScope($scope); - $query->shouldReceive('withGlobalScope')->with(Mockery::any(), [get_class($scope) => $scope])->once(); + $query->shouldReceive('withGlobalScope')->with(Mockery::any(), [$scope::class => $scope])->once(); $traitObject->testApplyScopes($query); }); diff --git a/tests/Traits/RestExtendableTest.php b/tests/Traits/RestExtendableTest.php index 667a5aa..8e6477a 100644 --- a/tests/Traits/RestExtendableTest.php +++ b/tests/Traits/RestExtendableTest.php @@ -1,5 +1,7 @@ toBe(TestModel::class); }); -it('executes restBeforeUpdate without errors', function() { +it('executes restBeforeUpdate without errors', function(): void { $traitObject = new class { use RestExtendable; @@ -32,7 +34,7 @@ expect($result)->toBeNull(); }); -it('executes restValidate without errors', function() { +it('executes restValidate without errors', function(): void { $traitObject = new class { use RestExtendable;