MicroFrameWork/kernel/modules/post/service/PostService.php

56 lines
1.6 KiB
PHP
Raw Normal View History

2024-07-25 16:15:18 +03:00
<?php
2024-09-06 16:53:20 +03:00
namespace kernel\modules\post\service;
2024-07-25 16:15:18 +03:00
use kernel\helpers\Debug;
2024-09-26 14:47:13 +03:00
use kernel\helpers\Slug;
2024-09-06 16:53:20 +03:00
use kernel\modules\post\models\Post;
2024-07-25 16:15:18 +03:00
use kernel\FormModel;
class PostService
{
public function create(FormModel $form_model): false|Post
{
$model = new Post();
2024-07-26 11:57:05 +03:00
$model->content = $form_model->getItem('content');
$model->user_id = $form_model->getItem('user_id');
2024-09-26 14:47:13 +03:00
$model->title = $form_model->getItem('title');
$model->slug = $this->createSlug($form_model);
2024-07-25 16:15:18 +03:00
if ($model->save()){
return $model;
}
return false;
}
public function createSlug(FormModel $form_model): string
{
$slug = Slug::url_slug($form_model->getItem('title'), ['transliterate' => true, 'lowercase' => true]);
if (Post::where(['slug' => $slug])->exists()) {
$id = 1;
$tmpSlug = $slug . '-' . $id++;
$slug = $this->recursiveCreateSlug($slug, $tmpSlug, $id);
}
return $slug;
}
protected function recursiveCreateSlug($slug, $tmpSlug, $id): string
{
if (Post::where(['slug' => $tmpSlug])->exists()) {
$tmpSlug = $slug . '-' . $id++;
$tmpSlug = $this->recursiveCreateSlug($slug, $tmpSlug, $id);
}
return $tmpSlug;
}
2024-07-25 16:15:18 +03:00
public function update(FormModel $form_model, Post $post): false|Post
{
2024-07-26 11:57:05 +03:00
$post->content = $form_model->getItem('content');
$post->user_id = $form_model->getItem('user_id');
2024-07-25 16:15:18 +03:00
if ($post->save()){
return $post;
}
return false;
}
}