<?php
namespace App\MyClass;
use DB;
class RenderSlug
{
protected $table; // имя таблицы где будем проверять на уникальность сформированный и искомый slug
protected $column; // колонка в которой ищем slug. По умолчанию - slug
protected $otherWhere; // дополнительные условия - Массив вида. [['status','1'],['id','<>','2']]
// + условия по умолчанию добавление в методе otherWhere()
protected $slugDefault; // сформированный по умолчанию slug из пришедшего $value
protected $returnSlug; // возвращаемый сформированный slug согласно чека базы
/**
* RenderSlug constructor.
* @param $value - входящие данные из чего будем формировать slug (т.е. title или что то подобное)
* @param $table - имя таблицы
* @param null $otherWhere - условия
* @param string $column - колонка в таблице
*/
public function __construct($value, $table, $otherWhere = null, $column = 'slug')
{
$this->slugDefault = str_slug($value);
$this->returnSlug = $this->slugDefault;
$this->table = $table;
$this->column = $column;
$this->otherWhere($otherWhere);
$this->findSlugBase();
}
protected function otherWhere($otherWhere){
if(isset($otherWhere)) {
$this->otherWhere['find'] = $otherWhere;
$this->otherWhere['findLike'] = $otherWhere;
}
$this->otherWhere['find'][] = [$this->column, '=', $this->slugDefault];
$this->otherWhere['findLike'][] = [$this->column, 'regexp', '^'.$this->slugDefault.'\-[0-9]+$'];
}
protected function findSlugBase()
{
$slug = DB::table($this->table)->select($this->column)->where($this->otherWhere['find'])->get();
if(count($slug)>0) $this->returnSlug = $this->renderSlug();
}
protected function renderSlug()
{
$slug = $this->slugDefault.'-1';
$query = DB::table($this->table)->select($this->column)->where($this->otherWhere['findLike'])->orderBy('slug', 'desc')->first();
if(isset($query)) {
$slugIncrement = str_replace($this->slugDefault.'-', '', $query->slug)+1;
$slug = $this->slugDefault.'-'.$slugIncrement;
}
return $slug;
}
public function getReturnSlug()
{
return $this->returnSlug;
}
}