Skip to content

Instantly share code, notes, and snippets.

@cawa87
Created July 10, 2024 15:06
Show Gist options
  • Save cawa87/d1422796ff71defc6a1296c1d1ce69dd to your computer and use it in GitHub Desktop.
Save cawa87/d1422796ff71defc6a1296c1d1ce69dd to your computer and use it in GitHub Desktop.
php class refactor
<?php
declare(strict_types=1);
class TagService
{
use ReplaceModelNameTrait;
private const TAG_MODELS = [
"posts" => PostTag::class,
"stories" => StoryTag::class,
"streams" => StreamTag::class,
"audio_playlists" => AudioPlaylistTag::class,
"events" => EventTag::class,
"courses" => CourseTag::class,
"giveaways" => GiveawayTag::class,
"spaces" => SpaceTag::class,
];
private const MODELS = [
"posts" => Post::class,
"stories" => Story::class,
"streams" => Stream::class,
"audio_playlists" => AudioPlaylist::class,
"events" => Event::class,
"courses" => Course::class,
"giveaways" => Giveaway::class,
];
public function getGlobalUsedTags(array $params): Collection
{
$tags = [];
$searchIds = [];
$type = $params["type"] ?? null;
$spaceId = $params["space_id"] ?? null;
if ($spaceId) {
$searchIds = $this->getSearchIdsBySpaceId($spaceId, $type);
}
foreach (self::TAG_MODELS as $key => $model) {
if (!$type || $type === $key) {
$newTags = $this->getTagIdsBySearchIds(
$model,
$searchIds,
$key
);
$tags = array_unique(array_merge($tags, $newTags));
}
}
return $this->getTagsByIds($tags);
}
public function getSpaceUsedTags(): Collection
{
return DB::table("tags")
->rightJoin("space_tags", "tags.id", "=", "space_tags.tag_id")
->distinct()
->select(
"tags.id",
"tags.name_en",
"tags.name_ru",
"tags.name_es",
"tags.color"
)
->orderBy("name_" . user()->language)
->get();
}
private function getSearchIdsBySpaceId(
string $spaceId,
?string $type
): array {
$searchIds = [];
foreach (self::MODELS as $key => $model) {
if (!$type || $type === $key) {
$newSearchIds = $model
::query()
->where("space_id", $spaceId)
->pluck("id")
->toArray();
$searchIds = array_unique(
array_merge($searchIds, $newSearchIds)
);
}
}
return $searchIds;
}
private function getTagIdsBySearchIds(
string $model,
array $searchIds,
string $key
): array {
return $model
::query()
->when(!empty($searchIds), function ($query) use (
$searchIds,
$key
) {
$query->whereIn($this->manyToOne($key) . "_id", $searchIds);
})
->distinct()
->pluck("tag_id")
->toArray();
}
private function getTagsByIds(array $tags): Collection
{
return Tag::query()
->whereIn("id", $tags)
->orderBy("name_" . user()->language)
->get([
"tags.id",
"tags.name_en",
"tags.name_ru",
"tags.name_es",
"tags.color",
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment