Certainly! Refactoring your Laravel 10 store method to adhere to the KISS, DRY, YAGNI, BDUF, SOLID, and APO principles involves breaking down the method into smaller, more manageable, and reusable components. This enhances readability, maintainability, and scalability.
Here's a step-by-step refactored version of your store method:
- Single Responsibility Principle (SRP): Each method should have one responsibility.
- DRY (Don't Repeat Yourself): Avoid code duplication by extracting repeated logic.
- KISS (Keep It Simple, Stupid): Simplify complex logic by breaking it into smaller methods.
- SOLID Principles: Ensure that the code is open for extension but closed for modification, among other SOLID principles.
- Error Handling: Properly handle exceptions and rollback transactions if needed.
- APO (Avoid Premature Optimization): Focus on readability and maintainability without overcomplicating the code.
Refactored Code
<?php
namespace App\Http\Controllers;
use App\Events\Adm\Chat\StoreChatEvent as AdmStoreChatEvent;
use App\Events\StoreChatEvent;
use App\Http\Requests\StoreRequest;
use App\Http\Resources\ShowChatGroupResource;
use App\Http\Resources\ShowChatResource;
use App\Models\Chat;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
class ChatController extends Controller
{
/**
* Store a newly created chat.
*
* @param StoreRequest $request
* @return JsonResponse|\Illuminate\Http\Resources\Json\JsonResource
*/
public function store(StoreRequest $request)
{
$data = $request->validated();
$userIds = $this->prepareUserIds($data['userIds']);
if ($this->isInvalidChatRequest($userIds, $data['is_group'])) {
return response()->json(['store' => false]);
}
try {
DB::beginTransaction();
$chat = $this->createChat($data, $userIds);
$this->syncChatUsers($chat, $userIds);
if ($chat->wasRecentlyCreated) {
$this->broadcastChatCreation($chat, $userIds);
}
DB::commit();
} catch (\Exception $exception) {
DB::rollBack();
// Optionally log the exception
// Log::error($exception->getMessage());
return response()->json(['store' => false]);
}
return $chat->is_group
? $this->handleGroupChatResponse($chat)
: ShowChatResource::make($chat);
}
/**
* Prepare and merge user IDs with the authenticated user's ID.
*
* @param array $userIds
* @return array
*/
private function prepareUserIds(array $userIds): array
{
$mergedUserIds = array_unique(array_merge($userIds, [auth()->id()]));
sort($mergedUserIds);
return $mergedUserIds;
}
/**
* Validate the chat creation request based on user count and group flag.
*
* @param array $userIds
* @param bool $isGroup
* @return bool
*/
private function isInvalidChatRequest(array $userIds, bool $isGroup): bool
{
return count($userIds) > 2 && !$isGroup;
}
/**
* Create a chat based on whether it's a group or private chat.
*
* @param array $data
* @param array $userIds
* @return Chat
*/
private function createChat(array $data, array $userIds): Chat
{
if ($this->isPrivateChat($userIds, $data['is_group'])) {
return $this->getOrCreatePrivateChat($userIds);
}
return $this->getOrCreateGroupChat($data);
}
/**
* Determine if the chat is a private chat.
*
* @param array $userIds
* @param bool $isGroup
* @return bool
*/
private function isPrivateChat(array $userIds, bool $isGroup): bool
{
return count($userIds) === 2 && !$isGroup;
}
/**
* Get an existing private chat or create a new one.
*
* @param array $userIds
* @return Chat
*/
private function getOrCreatePrivateChat(array $userIds): Chat
{
$existingChat = Chat::whereHas('users', function ($query) use ($userIds) {
$query->whereIn('user_id', $userIds);
}, '=', count($userIds))
->where('is_group', false)
->first();
if ($existingChat) {
return $existingChat;
}
return Chat::create([
'creator_id' => auth()->id(),
'title' => implode('-', $userIds),
'is_group' => false,
]);
}
/**
* Get or create a group chat and handle image upload if present.
*
* @param array $data
* @return Chat
*/
private function getOrCreateGroupChat(array $data): Chat
{
$chat = Chat::firstOrCreate(
[
'creator_id' => auth()->id(),
'is_group' => true,
],
[
'title' => $data['title'] ?? 'Чат ' . (Chat::latest()->value('id') + 1),
]
);
if (request()->hasFile('image')) {
$chat->image = $this->storeChatImage($chat->id, $data['image']);
$chat->save();
}
return $chat;
}
/**
* Store the chat image in the designated storage path.
*
* @param int $chatId
* @param \Illuminate\Http\UploadedFile $image
* @return string
*/
private function storeChatImage(int $chatId, $image): string
{
$folder = now()->format('Y-m-d');
return Storage::disk('public')->put("images/chats/{$chatId}/{$folder}", $image);
}
/**
* Sync users to the chat.
*
* @param Chat $chat
* @param array $userIds
* @return void
*/
private function syncChatUsers(Chat $chat, array $userIds): void
{
$chat->users()->sync($userIds);
}
/**
* Broadcast chat creation events to users.
*
* @param Chat $chat
* @param array $userIds
* @return void
*/
private function broadcastChatCreation(Chat $chat, array $userIds): void
{
foreach ($userIds as $userId) {
broadcast(new StoreChatEvent($chat, $userId));
}
}
/**
* Handle the response for group chats, including broadcasting to admins.
*
* @param Chat $chat
* @return \Illuminate\Http\Resources\Json\JsonResource
*/
private function handleGroupChatResponse(Chat $chat)
{
$adminIds = User::where('is_admin', true)->pluck('id');
foreach ($adminIds as $adminId) {
broadcast(new AdmStoreChatEvent($chat, $adminId));
}
return ShowChatGroupResource::make($chat);
}
}
Explanation of Changes
-
Method Extraction:
prepareUserIds: Merges and sorts user IDs, ensuring the authenticated user is included.
isInvalidChatRequest: Validates the chat creation conditions based on user count and group flag.
createChat: Determines whether to create a private or group chat.
isPrivateChat: Checks if the chat is private.
getOrCreatePrivateChat: Retrieves an existing private chat or creates a new one.
getOrCreateGroupChat: Retrieves or creates a group chat and handles image uploads.
storeChatImage: Handles storing the chat image in the designated storage path.
syncChatUsers: Syncs the users to the chat.
broadcastChatCreation: Broadcasts the chat creation event to all users involved.
handleGroupChatResponse: Handles broadcasting to admins and returning the appropriate resource for group chats.
-
Error Handling:
- Wrapped the transactional operations within a
try-catch block to ensure that any exceptions result in a transaction rollback and a JSON response indicating failure.
-
Adherence to SOLID Principles:
- Single Responsibility: Each method has a single responsibility, making the code easier to test and maintain.
- Open/Closed Principle: The code is structured in a way that allows for easy extension without modifying existing methods.
- Dependency Inversion: Utilizing Laravel's dependency injection and facades maintains a level of abstraction.
-
DRY (Don't Repeat Yourself):
- Removed duplicate logic by extracting common functionalities into reusable methods.
-
KISS (Keep It Simple, Stupid):
- Simplified complex logic by breaking it down into smaller, understandable methods.
-
Performance and Optimization:
- While adhering to APO (Avoid Premature Optimization), the code ensures efficient querying and minimal resource usage by leveraging Laravel's Eloquent ORM features effectively.
Additional Recommendations
-
Logging: Consider adding logging within the catch block to record exceptions for debugging purposes.
use Illuminate\Support\Facades\Log;
catch (\Exception $exception) {
DB::rollBack();
Log::error('Chat creation failed: ' . $exception->getMessage());
return response()->json(['store' => false]);
}
-
Validation Enhancements: Although StoreRequest handles validation, ensure that it includes all necessary validation rules for user IDs, group flags, titles, and image uploads.
-
Event Optimization: If broadcasting to a large number of users or admins, consider queueing the events to improve performance.
broadcast(new StoreChatEvent($chat, $userId))->onQueue('broadcast');
-
Resource Optimization: Utilize eager loading in resources if displaying related data to minimize database queries.
-
Testing: Write unit and feature tests to ensure that each method behaves as expected, enhancing reliability.
This refactored approach makes your store method cleaner, more maintainable, and aligned with the best software development practices.