game/_incl_data/class/DarksLight2/Training/TrainingManager.php

140 lines
3.7 KiB
PHP
Raw Normal View History

<?php
namespace DarksLight2\Training;
use Core\Db;
use DarksLight2\Traits\Singleton;
use PDO;
use stdClass;
class TrainingManager
{
use Singleton;
private $database_records = false;
private array $steps_data;
private int $user_id;
private array $steps;
public function __construct(int $user_id)
{
$this->user_id = $user_id;
}
/**
* @param StepFactory[] $steps
*
* @return void
* @throws \DarksLight2\Training\TrainingException
*/
public function register(array $steps)
{
if (!empty($this->steps)) {
throw TrainingException::alreadyRegistered();
}
foreach ($steps as $step) {
if($step instanceof StepFactory) {
$this->steps[$step->getShortName()] = new class (
$step->getMessage(),
$step->getTitle(),
$step->getRewards(),
$this->stepData($step->getShortName())->complete,
$step->getShortName(),
$this->stepData($step->getShortName())->progress
) {
public string $message;
public string $title;
public string $short_name;
public array $rewards;
public bool $isComplete;
public stdClass $progress;
public function __construct(
string $message,
string $title,
array $rewards,
bool $isComplete,
string $short_name,
stdClass $progress
) {
$this->rewards = $rewards;
$this->title = $title;
$this->isComplete = $isComplete;
$this->message = $message;
$this->short_name = $short_name;
$this->progress = $progress;
}
public function render()
{
$path = $_SERVER['DOCUMENT_ROOT'] . '/modules_data/steps/' . $this->short_name . '.php';
if(file_exists($path)) {
require $path;
return;
}
throw TrainingException::noRenderingFile();
}
};
}
}
}
private function stepData(string $short_name): object
{
return json_decode($this->getDatabaseRecords()->data)->$short_name;
}
private function getDatabaseRecords()
{
if(!$this->database_records) {
$this->database_records = Db::run('SELECT * FROM user_training WHERE user_id = ?', [$this->user_id])
->fetch(PDO::FETCH_OBJ);
}
return $this->database_records;
}
public function createDatabaseRecord()
{
if(!$this->getDatabaseRecords()) {
Db::run('INSERT INTO user_training (user_id, data) VALUES (?, ?)', [
$this->user_id,
json_encode($this->firstRecordData())
]);
}
}
private function firstRecordData(): array
{
return [
'first_step' => [
'complete' => 0,
'progress' => [
'current' => 0,
'need' => 0,
]
]
];
}
public function __get(string $name)
{
return $this->steps[$name];
}
public function addPoint(string $short_name)
{
$this->$short_name->progress++;
}
public function store()
{
}
}