<?php
namespace App\Models;
class MonthModel extends Model
{
const MIN_TABLE = '2020_12' const MONTH_FORMAT = 'Y_m';
protected $month;
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
if (empty($this->month)) $this->setMonthTable();
}
public function getMonth(): string
{
return $this->month;
}
public function setMonthTable(string $month = '')
{
$month = empty($month) ? date(self::MONTH_FORMAT) : date(self::MONTH_FORMAT, strtotime($month));
$month = str_replace('_', '-', $month);
$this->month = date(self::MONTH_FORMAT, strtotime($month));
$this->table = $this->getOldTableName() . '_' . $this->month;
return $this;
}
public function getAllMonthes() : array
{
$monthes = get_month_range(str_replace('_', '-', self::MIN_TABLE), date('Y-m'));
krsort($monthes);
return $monthes;
}
public function getOldTableName():string
{
$table_name = $this->getTable();
$suffix_len = strlen(self::MIN_TABLE);
$suffix = substr($table_name, -$suffix_len, $suffix_len);
if (preg_match ("/^([0-9]{4})_([0-9]{2})$/", $suffix, $parts)){
$table_name = substr($table_name, 0, -$suffix_len - 1);
}
return $table_name;
}
public function createMonthTable(string $new_table = '', $time = '', $format = self::MONTH_FORMAT, string $old_table = '')
{
$new_table = empty($new_table) ? $this->getOldTableName() . '_' . date($format, empty($time) ? time() : $time) : $new_table;
$db_prefix = env('DB_PREFIX');
return $this->setCopyTable($db_prefix . $new_table, $db_prefix . $this->getOldTableName());
}
}