<?php
namespace App\Models;
class YearModel extends MonthModel
{
const MIN_TABLE = '2020' const MONTH_SUB_TABLE = true; const MONTH_FORMAT = 'Y';
public function __construct($data = [])
{
parent::__construct($data);
if (empty($this->month)) $this->setMonthTable();
}
public function getAllMonthes(): array
{
$years = get_year_range(self::MIN_TABLE . '-01', date('Y-01', strtotime('+1 year')));
krsort($years);
return $years;
}
public function setMonthTable(string $month = '')
{
$month = empty($month) ? date(self::MONTH_FORMAT) : (strlen($month) == 4 ? $month : date(self::MONTH_FORMAT, strtotime($month)));
$month = str_replace('_', '-', $month);
$this->month = $month;
$this->table = $this->getOldTableName() . '_' . $this->month;
return $this;
}
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());
}
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})$/", $suffix, $parts)){
$table_name = substr($table_name, 0, -$suffix_len - 1);
}
return $table_name;
}
}