Files
2025-11-30 11:57:22 +01:00

94 lines
2.9 KiB
PHP

<?php
namespace Paymenter\Extensions\Others\SocialBase\Services;
use Illuminate\Database\Eloquent\Model;
use Paymenter\Extensions\Others\SocialBase\Models\Reaction;
use App\Models\User;
class ReactionService
{
/**
* Add or toggle a reaction on any model
*/
public function toggleReaction(Model $model, User $user, string $type): array
{
// Ensure the model uses the HasReactions trait
if (!method_exists($model, 'toggleReaction')) {
throw new \InvalidArgumentException('Model must use the HasReactions trait');
}
$action = $model->toggleReaction($user, $type);
return [
'action' => $action,
'reaction_counts' => $model->fresh()->reaction_counts,
'user_reaction' => $model->getUserReaction($user)?->type,
'total_reactions' => $model->total_reactions,
];
}
/**
* Get reactions data for a model
*/
public function getReactions(Model $model, ?User $user = null): array
{
return [
'reaction_counts' => $model->reaction_counts,
'user_reaction' => $user ? $model->getUserReaction($user)?->type : null,
'reactions_with_users' => $model->reactions_with_users,
'total_reactions' => $model->total_reactions,
'most_popular' => $model->most_popular_reaction,
];
}
/**
* Get available reaction types for a context
*/
public function getAvailableTypes(string $context = 'default'): array
{
return Reaction::getAvailableTypes($context);
}
/**
* Validate reaction type for a context
*/
public function validateReactionType(string $type, string $context = 'default'): bool
{
$availableTypes = $this->getAvailableTypes($context);
return array_key_exists($type, $availableTypes);
}
/**
* Get reaction statistics for a collection of models
*/
public function getStatistics($models): array
{
$totalReactions = 0;
$typeStats = [];
$mostReactedModel = null;
$maxReactions = 0;
foreach ($models as $model) {
$reactionCounts = $model->reaction_counts;
$modelTotal = array_sum($reactionCounts);
$totalReactions += $modelTotal;
if ($modelTotal > $maxReactions) {
$maxReactions = $modelTotal;
$mostReactedModel = $model;
}
foreach ($reactionCounts as $type => $count) {
$typeStats[$type] = ($typeStats[$type] ?? 0) + $count;
}
}
return [
'total_reactions' => $totalReactions,
'reaction_type_stats' => $typeStats,
'most_reacted_model' => $mostReactedModel,
'average_reactions_per_model' => $models->count() > 0 ? $totalReactions / $models->count() : 0,
];
}
}