You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
3.0 KiB

<?php
/**
* Created by Error202
* Date: 20.08.2018
*/
namespace core\components\modules;
use core\entities\ModuleRecord;
use core\services\ModuleService;
use Yii;
3 years ago
use yii\db\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
class ModuleManager
{
3 years ago
public array $moduleNames = [];
public array $modules = [];
3 years ago
private ModuleService $service;
public function __construct(ModuleService $service)
{
3 years ago
$this->service = $service;
}
3 years ago
/**
* @param $name
* @throws Exception
*/
public function appendToMigrationTable($name)
{
$time = time();
$connection = Yii::$app->getDb();
$command = $connection->createCommand("INSERT INTO migration (version, apply_time) VALUE ('$name', '$time')");
$command->execute();
}
3 years ago
/**
* @param $name
* @throws Exception
*/
public function removeFromMigrationTable($name)
{
$connection = Yii::$app->getDb();
$command = $connection->createCommand("DELETE FROM migration WHERE version = '$name'");
$command->execute();
}
3 years ago
public function getModules(): array
{
$modules = [];
$localModules = $this->getLocalModules();
foreach ($localModules as $local_module) {
$db_module = ModuleRecord::find()->andWhere(['name' => $local_module['name']])->one();
if ($this->isTableExist('modules') && !$db_module) {
3 years ago
$db_module = $this->service->create($local_module['name'], 'common\\modules\\' . $local_module['name'] . '\\' . $local_module['module']);
}
3 years ago
$db_module->description = $local_module['description'];
$modules[] = $db_module;
}
return $modules;
}
3 years ago
public function getLocalModules(): array
{
$this->getLocalModulesNames();
if (empty($this->modules)) {
foreach ($this->moduleNames as $module_name) {
$manifest = Yii::getAlias('@common/modules/' . $module_name . '/manifest.php');
if (file_exists($manifest)) {
$this->modules[] = require $manifest;
}
}
}
return $this->modules;
}
public function isExists($name): bool
{
$this->getLocalModules();
$modules = ArrayHelper::getColumn($this->modules, 'name');
return in_array($name, $modules);
}
private function getLocalModulesNames(): void
{
if (!empty($this->moduleNames)) {
return;
}
$names = [];
$modulePath = Yii::getAlias('@common/modules');
$modules = file_exists($modulePath) ? FileHelper::findDirectories($modulePath, [
'recursive' => false,
]) : [];
foreach ($modules as $module) {
$module = basename($module);
$names[] = $module;
}
$this->moduleNames = $names;
}
public function isTableExist($name): bool
{
return Yii::$app->db->schema->getTableSchema($name) !== null;
}
}