Files
animal_management/services/ModuleSetupService.php

73 lines
2.2 KiB
PHP

<?php
namespace humhub\modules\animal_management\services;
use humhub\modules\space\models\Space;
use Yii;
class ModuleSetupService
{
public static function runForSpace(Space $space): array
{
$result = static::applyModuleMigrations();
$settings = Yii::$app->getModule('animal_management')->settings->contentContainer($space);
if ($settings->get('searchBlockHeading') === null) {
$settings->set('searchBlockHeading', 'Animals Available for Intake & Transfer');
$result['defaultsApplied'] = ['searchBlockHeading'];
} else {
$result['defaultsApplied'] = [];
}
return $result;
}
private static function applyModuleMigrations(): array
{
$migrationDir = dirname(__DIR__) . '/migrations';
$files = glob($migrationDir . '/m*.php') ?: [];
sort($files, SORT_NATURAL);
$existingVersions = Yii::$app->db->createCommand('SELECT version FROM migration')->queryColumn();
$history = array_fill_keys($existingVersions, true);
$applied = [];
$skipped = [];
foreach ($files as $file) {
$version = pathinfo($file, PATHINFO_FILENAME);
if (isset($history[$version])) {
$skipped[] = $version;
continue;
}
if (!class_exists($version, false)) {
require_once $file;
}
if (!class_exists($version, false)) {
throw new \RuntimeException('Migration class not found: ' . $version);
}
$migration = new $version();
$ok = method_exists($migration, 'safeUp') ? $migration->safeUp() : $migration->up();
if ($ok === false) {
throw new \RuntimeException('Migration failed: ' . $version);
}
Yii::$app->db->createCommand()->insert('migration', [
'version' => $version,
'apply_time' => time(),
])->execute();
$applied[] = $version;
$history[$version] = true;
}
return [
'applied' => $applied,
'skipped' => $skipped,
];
}
}