Fix module states task runs version, extend, files, templates, blocks,
settings and events information fix tasks

@param Module      $module
@param Config|null $oConfig If not passed uses default base shop config
498670
public function fix($module, $oConfig = null)
    {
        if ($oConfig !== null) {
            $this->setConfig($oConfig);
        }

        $moduleId = $module->getId();

        if (!$this->initialCacheClearDone) {
            //clearing some cache to be sure that fix runs not against a stale cache
            ModuleVariablesLocator::resetModuleVariables();
            if (extension_loaded('apc') && ini_get('apc.enabled')) {
                apc_clear_cache();
            }
            if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
                $this->output->writeln("initial cache cleared");
            }
            $this->initialCacheClearDone = true;
        }
        $this->module = $module;
        $this->needCacheClear = false;
        $this->restoreModuleInformation($module, $moduleId);
        if ($this->needCacheClear){
            $this->resetModuleCache($module);
            $this->output->writeln("cache cleared for $moduleId");
        }
    }
667648
public function setModule($module)
        {
            if (null !== $module && !is_string($module)) {
                throw new Exception(
                    'Invalid argument: $module must be a string or null'
                );
            }

            $this->_module    = $module;
            $this->_hrefCache = null;

            return $this;
        }
1029561
private function registerVendorConfig(Module $module)
    {
        $files = $this->app['files']->files($module->getPath().'/Config/Vendor');

        foreach ($files as $file) {
            $filename = preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($file));

            $this->mergeConfigFrom(
                $file,
                $filename
            );
        }
    }
445183
protected function _addExtensions(\OxidEsales\Eshop\Core\Module\Module $module)
    {
        $modules = $this->_removeNotUsedExtensions($this->getModulesWithExtendedClass(), $module);

        if ($module->hasExtendClass()) {
            $this->validateMetadataExtendSection($module);
            $addModules = $module->getExtensions();
            $modules = $this->_mergeModuleArrays($modules, $addModules);
        }

        $modules = $this->buildModuleChains($modules);

        $this->_saveToConfig('aModules', $modules);
    }
585585
function runModule(module, str, replacements) {
    var pattern = module.pattern,
        replace = module.replace,
        match;

    // Reset the pattern so we can re-use it
    pattern.lastIndex = 0;

    while ((match = pattern.exec(str)) !== null) {
        replacements[match.index] = {
            oldStr: match[0],
            newStr: typeof replace === "function"? replace(match) : replace
        };
        if (pattern.global === false) {
            // if the search isn't global we need to break manually
            // because pattern.exec() will always return something
            break;
        }
    }
}
182098
public function handleOnModuleActivation(ModuleSetting $moduleSetting, string $moduleId, int $shopId)
    {
        if (!$this->canHandle($moduleSetting)) {
            throw new WrongModuleSettingException($moduleSetting, self::class);
        }

        $shopConfigurationSetting = $this->getShopConfigurationSetting($shopId);

        $shopSettingValue = array_merge(
            $shopConfigurationSetting->getValue(),
            [
                $moduleId => $moduleSetting->getValue(),
            ]
        );

        $shopConfigurationSetting->setValue($shopSettingValue);

        $this->shopConfigurationSettingDao->save($shopConfigurationSetting);
    }
489901
public function run($module)
    {
        $moduleSettings = $module->getInfo('settings');
        $isTheme = $this->isTheme($module->getId());
        if (!$isTheme || ($isTheme && is_array($moduleSettings))) {
            $this->addModuleSettings($moduleSettings, $module->getId());
        }
    }
1355852
public function update($module)
    {
        $module = $this->module->findOrFail($module);

        $packages = $module->get('require', []);

        chdir(base_path());

        foreach ($packages as $name => $version) {
            $package = "\"{$name}:{$version}\"";

            $this->run("composer require {$package}");
        }
    }
320446
public final function registerModule(Module $module)
    {
        $dependencies = $module->getModules();

        foreach($dependencies as $dependency){
            $this->registerModule($dependency);
        }

        $this->modules[$module->getModuleName()] = $module;
    }
44667
public function update($module, $options = null)
    {
        $module = strtolower($module);
        $options = is_null($options) ? array() : $options;
        $modules = $this->findModules();
       
        // Resolve deps
        $deps = $this->resolveDependencies(
            $module
        );
        
        if (!$deps->offsetExists($module)) {
            $deps->offsetSet($module, 'X');
        }
        
        // Setup all dependencies
        foreach($deps as $depModule => $depVersion){

            if(!$this->hasSetupService($depModule)){
                continue;
            }
        
            $setup = $this->initSetupService($depModule);
            $operation = 'setup';
            $args = array();
        
            if ($depModule == $module) {
                $args['options'] = $options;
            }
             
            // complete existing installation
            $setup->exec(
                'setup',
                $args
            );
        }
        
        return true;
    }
573611
async def loadmodule(self, module):
        '''
        
        '''
        self._logger.debug('Try to load module %r', module)
        if hasattr(module, '_instance'):
            self._logger.debug('Module is already initialized, module state is: %r', module._instance.state)
            if module._instance.state == ModuleLoadStateChanged.UNLOADING or module._instance.state == ModuleLoadStateChanged.UNLOADED:
                # Wait for unload
                um = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.UNLOADED)
                await um
            elif module._instance.state == ModuleLoadStateChanged.SUCCEEDED:
                pass
            elif module._instance.state == ModuleLoadStateChanged.FAILED:
                raise ModuleLoadException('Cannot load module %r before unloading the failed instance' % (module,))
            elif module._instance.state == ModuleLoadStateChanged.NOTLOADED or module._instance.state == ModuleLoadStateChanged.LOADED or module._instance.state == ModuleLoadStateChanged.LOADING:
                # Wait for succeeded or failed
                sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
                fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
                _, m = await M_(sm, fm)
                if m is sm:
                    pass
                else:
                    raise ModuleLoadException('Module load failed for %r' % (module,))
        if not hasattr(module, '_instance'):
            self._logger.info('Loading module %r', module)
            inst = module(self.server)
            # Avoid duplicated loading
            module._instance = inst
            # When reloading, some of the dependencies are broken, repair them
            if hasattr(module, 'referencedBy'):
                inst.dependedBy = set([m for m in module.referencedBy if hasattr(m, '_instance') and m._instance.state != ModuleLoadStateChanged.UNLOADED])
            # Load Module
            for d in module.depends:
                if hasattr(d, '_instance') and d._instance.state == ModuleLoadStateChanged.FAILED:
                    raise ModuleLoadException('Cannot load module %r, it depends on %r, which is in failed state.' % (module, d))
            try:
                for d in module.depends:
                    if hasattr(d, '_instance') and d._instance.state == ModuleLoadStateChanged.SUCCEEDED:
                        d._instance.dependedBy.add(module)
                preloads = [d for d in module.depends if not hasattr(d, '_instance') or \
                            d._instance.state != ModuleLoadStateChanged.SUCCEEDED]
                for d in preloads:
                    self.subroutine(self.loadmodule(d), False)
                sms = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.SUCCEEDED) for d in preloads]
                fms = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.FAILED) for d in preloads]
                def _callback(event, matcher):
                    raise ModuleLoadException('Cannot load module %r, it depends on %r, which is in failed state.' % (module, event.module))
                await self.with_callback(self.wait_for_all(*sms), _callback, *fms)
            except:
                for d in module.depends:
                    if hasattr(d, '_instance') and module in d._instance.dependedBy:
                        self._removeDepend(module, d)
                self._logger.warning('Loading module %r stopped', module, exc_info=True)
                # Not loaded, send a message to notify that parents can not 
                async def _msg():
                    await self.wait_for_send(ModuleLoadStateChanged(module, ModuleLoadStateChanged.UNLOADED, inst))
                self.subroutine(_msg(), False)
                del module._instance
                raise
            for d in preloads:
                d._instance.dependedBy.add(module)
            self.activeModules[inst.getServiceName()] = module
            await module._instance.changestate(ModuleLoadStateChanged.LOADING, self)
            await module._instance.load(self)
            if module._instance.state == ModuleLoadStateChanged.LOADED or module._instance.state == ModuleLoadStateChanged.LOADING:
                sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
                fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
                _, m = await M_(sm, fm)
                if m is sm:
                    pass
                else:
                    raise ModuleLoadException('Module load failed for %r' % (module,))
            self._logger.info('Loading module %r completed, module state is %r', module, module._instance.state)
            if module._instance.state == ModuleLoadStateChanged.FAILED:
                raise ModuleLoadException('Module load failed for %r' % (module,))
793736
public static function getDispatchDefinition(Module $module, array $config = [])
    {

        $configService = Craft::$app->getConfig()->getGeneral();

        $defaultConfig = [
            'logger' =>
            /* '\yii\log\Logger', */
                new Logger(),
            'class' => Dispatcher::class,
            'targets' => [
                /* 'file' => $fileTarget, */
                'file' => [
                    'class' => FileTarget::class,
                    'levels' => array_merge(
                        ['error', 'warning'],
                        static::isDebugModeEnabled($module) ? ['trace', 'info'] : []
                    ),
                    'logFile' => Craft::getAlias('@storage/logs/' . strtolower(str_replace(
                        '/',
                        '-',
                        $module->getUniqueId()
                    )) . '.log'),
                    'logVars' => [],
                    'fileMode' => $configService->defaultFileMode,
                    'dirMode' => $configService->defaultDirMode,
                    'prefix' => static::prefixSessionData(),
                ],
            ],
        ];

        return ArrayHelper::merge($config, $defaultConfig);
    }
74397
public function module(Module $module)
    {
        $vars = $this->model::generate_page($module, 'setting');
        
        return $this->makeResponse('module', $vars);
    }
285080
public function updateSettings()
    {
        // Load the configuration from Paymorrow

        /** @var OxpsPaymorrowRequestControllerProxy $oRequestControllerProxy */
        $oRequestControllerProxy = oxNew( 'OxpsPaymorrowRequestControllerProxy' );
        $aConfigurationResponse  = $oRequestControllerProxy->getConfiguration();

        /** @var OxpsPaymorrowResponseHandler $oResponseHandler */
        $oResponseHandler   = oxNew( 'OxpsPaymorrowResponseHandler' );
        $aConfigurationData = $oResponseHandler->parseGetConfigurationResponse( $aConfigurationResponse );

        $oConfig = oxRegistry::getConfig();

        if ( oxRegistry::get( 'OxpsPaymorrowSettings' )->isSandboxMode() ) {
            $aSettingsMap = array(
                'api_endpoint'         => 'paymorrowEndpointUrlTest',
                'api_resource_handler' => 'paymorrowResourcePathTest',
                'api_operation_mode'   => 'paymorrowOperationModeTest',
            );
        } else {
            $aSettingsMap = array(
                'api_endpoint'         => 'paymorrowEndpointUrlProd',
                'api_resource_handler' => 'paymorrowResourcePath',
                'api_operation_mode'   => 'paymorrowOperationMode',
            );
        }

        // Apply the configuration for module settings
        foreach ( $aSettingsMap as $sPaymorrowKey => $sSettingsKey ) {
            if ( !empty( $aConfigurationData[$sPaymorrowKey] ) ) {
                $sValue = trim( (string) $aConfigurationData[$sPaymorrowKey] );

                $oConfig->setConfigParam( $sSettingsKey, $sValue );
                $oConfig->saveShopConfVar(
                    'str', $sSettingsKey, $sValue, null, sprintf( 'module:%s', $this->getId() )
                );
            }
        }

        // Reset resource cache
        /** @var OxpsPaymorrowResourceCache $oResourceCache */
        $oResourceCache = oxNew( 'OxpsPaymorrowResourceCache' );
        $oResourceCache->cleanCache();
    }
834306
public function createModule(Module $module)
    {
        $dst = $this->rootDir.'/../src/Terrific/Module/'.StringUtils::camelize($module->getName());

        if($this->toolbarMode === ToolbarListener::DEMO) {
            // prevent module creation in demo mode
            throw new \Exception('This action is not supported in demo mode');
        } else {
            if($this->moduleTemplate) {
                $this->copy($this->moduleTemplate, $dst, $module);
            }

            $this->copy($this->defaultTemplate, $dst, $module);
        }
    }
62275
public function loadConfigurationFile(Module $module)
    {
        $finder = (new Finder)
            // TODO: Flip when yaml parsing will be up
//            ->name('#customer[-_\.]?group\.(?:xml|yml|yaml)#i')
            ->name('#customer[-_\.]?group\.xml#i')
            ->in($module->getAbsoluteConfigPath());
        $count = $finder->count();

        if ($count > 1) {
            throw new InvalidConfigurationException('Too many configuration file.');
        } else {
            foreach ($finder as $file) {
                if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) === 'xml') {
                    $moduleConfig = $this->parseXml($file);
                } else {
                    $moduleConfig = $this->parseYml($file);
                }

                $this->applyConfig($moduleConfig);
            }
        }
    }
185090
public function handleOnModuleActivation(ModuleSetting $moduleSetting, string $moduleId, int $shopId)
    {
        if (!$this->canHandle($moduleSetting)) {
            throw new WrongModuleSettingException($moduleSetting, self::class);
        }

        foreach ($moduleSetting->getValue() as $shopModuleSettingData) {
            $shopModuleSetting = new ShopModuleSetting();
            $shopModuleSetting
                ->setShopId($shopId)
                ->setModuleId($moduleId);

            $shopModuleSetting = $this->mapDataToShopModuleSetting($shopModuleSetting, $shopModuleSettingData);

            $this->shopModuleSettingDao->save($shopModuleSetting);
        }
    }