Import definitions from directory

@param array $overrideData The overridden data
@throws \Exception
777955
private function importDefinitionsFromDirectory(array $overrideData)
    {
        if (!file_exists($this->path)) {
            throw new \Exception('Directory not found: ' . $this->path);
        }

        // Grab all yaml files in the schema directory.
        $schemaFiles = preg_grep('~\.(yml)$~', scandir($this->path));

        // Read contents of each file and add it to the definitions.
        foreach ($schemaFiles as $fileName) {
            $schemaStructure = explode('.', $this->fromSafeFileName($fileName));
            $dataTypeHandle = $schemaStructure[0];
            $recordName = $schemaStructure[1];

            $definition = Data::parseYamlFile($this->path . $fileName);

            // Check if there is data in the override file for the current record.
            if (isset($overrideData[$dataTypeHandle][$recordName])) {
                $definition = array_replace_recursive($definition, $overrideData[$dataTypeHandle][$recordName]);
            }

            $definitions[$dataTypeHandle][$recordName] = $definition;
        }

        return $definitions;
    }
1353483
public function registerData(array $entityData)
    {
        foreach ($entityData as $data) {
            $this->registerEntity($this->normalizer->denormalize(
                $data,
                $this->entityCollection->getEntityClass()
            ));
        }
    }
1361836
def _override_data(self, overrides):
        
        if overrides is not None:
            for name, val in overrides.items():
                self.log.debug('Trying to override initial data (%s=%s)', name, val)
                if name not in dir(self):
                    raise AttributeError(
                        'Can not override non-existing attribute'
                        '\'{}\' of class \'{}\'.'.format(name, type(self).__name__))

                setattr(self, name, val)
682272
public function addArray($array, $override)
    {
        foreach ($array as $key => $value) {
            $this->add($key, $value, $override);
        }
    }
186848
public function update($data, $override = null)
    {
        if (func_num_args() == 2) {
            $override['id'] = $data;
            $data = $override;
        }

        $response = $this->ontraport->put(
            $this->getNamespace(), $this->toArray($data)
        );

        return $this->ontraport->item($this, $response);
    }
520355
private static void applyOverrides() {
        // Get the appropriate InputStream to read overrides from, if any.
        InputStream stream = getContentTypesPropertiesStream();
        if (stream == null) {
            return;
        }

        try {
            try {
                // Read the properties file...
                Properties overrides = new Properties();
                overrides.load(stream);
                // And translate its mapping to ours...
                for (Map.Entry<Object, Object> entry : overrides.entrySet()) {
                    String extension = (String) entry.getKey();
                    String mimeType = (String) entry.getValue();
                    add(mimeType, extension);
                }
            } finally {
                stream.close();
            }
        } catch (IOException ignored) {
        }
    }
1157104
private function exportToSingle(array $configurations, array $overrideData)
    {
        $configurations = array_replace_recursive($configurations, $overrideData);
        FileHelper::writeToFile($this->file, Data::toYaml($configurations));
        Schematic::info('Exported schema to '.$this->file);
    }
1103282
public function install(array $installData)
	{
		try
		{
            /**
             * It's a quick hack for solving reinstall issue.
             * Should be a better option.
             */
            @unlink($this->options['root_path'].'config/generis.conf.php');

			/*
			 * 0 - Check input parameters. 
			 */
			$this->log('i', "Checking install data");
			self::checkInstallData($installData);
			
			$this->log('i', "Starting TAO install");
	        
			// Sanitize $installData if needed.
			if(!preg_match("/\/$/", $installData['module_url'])){
				$installData['module_url'] .= '/';
			}

			if(isset($installData['extensions'])) {
			    $extensionIDs = is_array($installData['extensions'])
			     ? $installData['extensions']
			     : explode(',',$installData['extensions']);
			} else {
			    $extensionIDs = array('taoCe');
			}

			$this->log('d', 'Extensions to be installed: ' . var_export($extensionIDs, true));

            $installData['file_path'] = rtrim($installData['file_path'], DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
	
			/*
			 *  1 - Check configuration with checks described in the manifest.
			 */
			$configChecker = tao_install_utils_ChecksHelper::getConfigChecker($extensionIDs);
			
			// Silence checks to have to be escaped.
			foreach ($configChecker->getComponents() as $c){
				if (method_exists($c, 'getName') && in_array($c->getName(), $this->getEscapedChecks())){
					$configChecker->silent($c);
				}
			}
			
			$reports = $configChecker->check();
			foreach ($reports as $r){
				$msg = $r->getMessage();
				$component = $r->getComponent();
				$this->log('i', $msg);

				if ($r->getStatus() !== common_configuration_Report::VALID && !$component->isOptional()){
					throw new tao_install_utils_Exception($msg);
				}
			}
			
			/*
			 *  X - Setup Oatbox
			 */
			
			$this->log('d', 'Removing old config');
			$consistentOptions = array_merge($installData, $this->options);
            $consistentOptions['config_path'] = $this->getConfigPath();
			$this->oatBoxInstall->setOptions($consistentOptions);
			$this->oatBoxInstall->install();
            $this->log('d', 'Oatbox was installed!');

            ServiceManager::setServiceManager($this->getServiceManager());

			/*
			 *  2 - Test DB connection (done by the constructor)
			 */
			$this->log('i', "Spawning DbCreator");
			$dbName = $installData['db_name'];
			if($installData['db_driver'] == 'pdo_oci'){
				$installData['db_name'] = $installData['db_host'];
				$installData['db_host'] = '';
			}
			$dbConfiguration = array(
						'driver' => $installData['db_driver'],
						'host' => $installData['db_host'],
						'dbname' => $installData['db_name'],
						'user' => $installData['db_user'],
						'password' => $installData['db_pass'],
	
			);
			$hostParts = explode(':', $installData['db_host']);
			if (count($hostParts) == 2) {
                $dbConfiguration['host'] = $hostParts[0];
			    $dbConfiguration['port'] = $hostParts[1];
			}
				
			if($installData['db_driver'] == 'pdo_mysql'){
			    $dbConfiguration['dbname'] = '';
			}
			if($installData['db_driver'] == 'pdo_oci'){
				$dbConfiguration['wrapperClass'] = 'Doctrine\DBAL\Portability\Connection';
				$dbConfiguration['portability'] = \Doctrine\DBAL\Portability\Connection::PORTABILITY_ALL;
				$dbConfiguration['fetch_case'] = PDO::CASE_LOWER;
			}
				
			$dbCreator = new tao_install_utils_DbalDbCreator($dbConfiguration);
			
			$this->log('d', "DbCreator spawned");

			/*
			 *   3 - Load the database schema
			 */

			// If the database already exists, drop all tables
			if ($dbCreator->dbExists($dbName)) {

				try {
				    //If the target Sgbd is mysql select the database after creating it
				    if ($installData['db_driver'] == 'pdo_mysql'){
				        $dbCreator->setDatabase($installData['db_name']);
				    }
					$dbCreator->cleanDb($dbName);
					
				} catch (Exception $e){
					$this->log('i', 'Problem cleaning db will try to erase the whole db: '.$e->getMessage());
					try {
					$dbCreator->destroyTaoDatabase($dbName);
					} catch (Exception $e){
						$this->log('i', 'isssue during db cleaning : ' . $e->getMessage());
					}
				}
				$this->log('i', "Dropped all tables");
			}
			// Else create it
			else {
				try {

					$dbCreator->createDatabase($installData['db_name']);
					$this->log('i', "Created database ".$installData['db_name']);
				} catch (Exception $e){
					throw new tao_install_utils_Exception('Unable to create the database, make sure that '.$installData['db_user'].' is granted to create databases. Otherwise create the database with your super user and give to  '.$installData['db_user'].' the right to use it.');
				}
				
				//If the target Sgbd is mysql select the database after creating it
				if ($installData['db_driver'] == 'pdo_mysql'){
				    $dbCreator->setDatabase($installData['db_name']);
				}

			}
			
			// reset db name for mysql
			if ($installData['db_driver'] == 'pdo_mysql'){
			    $dbConfiguration['dbname'] = $installData['db_name'];
			}
	
			// Create tao tables
			$dbCreator->initTaoDataBase();	
            $this->log('i', 'Created tables');
            
            $storedProcedureFile = __DIR__ . DIRECTORY_SEPARATOR . 'db' . DIRECTORY_SEPARATOR . 'tao_stored_procedures_' . str_replace('pdo_', '', $installData['db_driver']) . '.sql';
			if (file_exists($storedProcedureFile) && is_readable($storedProcedureFile)){
				$this->log('i', 'Installing stored procedures for ' . $installData['db_driver'] . ' from file: ' . $storedProcedureFile);
				$dbCreator->loadProc($storedProcedureFile);
			}
			else {
			    $this->log('e', 'Could not find storefile : ' . $storedProcedureFile);
			}
			
			/*
			 *  4 - Create the generis config files
			 */
			
			$this->log('d', 'Writing generis config');
			$generisConfigWriter = new tao_install_utils_ConfigWriter(
				$this->options['root_path'].'generis/config/sample/generis.conf.php',
                $this->getGenerisConfig()
			);

			$session_name = (isset($installData['session_name']))?$installData['session_name']:self::generateSessionName();
			$generisConfigWriter->createConfig();
			$constants = array(
                'LOCAL_NAMESPACE'			=> $installData['module_namespace'],
                'GENERIS_INSTANCE_NAME'		=> $installData['instance_name'],
                'GENERIS_SESSION_NAME'		=> $session_name,
                'ROOT_PATH'					=> $this->options['root_path'],
                'FILES_PATH'                => $installData['file_path'],
                'ROOT_URL'					=> $installData['module_url'],
                'DEFAULT_LANG'				=> $installData['module_lang'],
                'DEBUG_MODE'				=> ($installData['module_mode'] == 'debug') ? true : false,
                'TIME_ZONE'                 => $installData['timezone']
            );

            $constants['DEFAULT_ANONYMOUS_INTERFACE_LANG'] = (isset($installData['anonymous_lang'])) ? $installData['anonymous_lang'] : $installData['module_lang'];


			$generisConfigWriter->writeConstants($constants);
            $this->log('d', 'The following constants were written in generis config:' . PHP_EOL . var_export($constants, true));

			/*
			 * 4b - Prepare the file/cache folder (FILES_PATH) not yet defined)
			 * @todo solve this more elegantly
			 */
			$file_path = $installData['file_path'];
			if (is_dir($file_path)) {
			    $this->log('i', 'Data from previous install found and will be removed');
                if (!helpers_File::emptyDirectory($file_path, true)) {
                    throw new common_exception_Error('Unable to empty ' . $file_path . ' folder.');
                }
			} else {
                if (mkdir($file_path, 0700, true)) {
                    $this->log('d', $file_path . ' directory was created!');
                } else {
                    throw new Exception($file_path . ' directory creation was failed!');
                }
		 	}
		 	$cachePath = $file_path . 'generis' . DIRECTORY_SEPARATOR . 'cache';
            if (mkdir($cachePath, 0700, true)) {
                $this->log('d', $cachePath . ' directory was created!');
            } else {
                throw new Exception($cachePath . ' directory creation was failed!');
            }

            foreach ((array)$installData['extra_persistences'] as $k => $persistence) {
                common_persistence_Manager::addPersistence($k, $persistence);
            }

			/*
			 * 5 - Run the extensions bootstrap
			 */
			$this->log('d', 'Running the extensions bootstrap');
			common_Config::load($this->getGenerisConfig());
			
			/*
			 * 5b - Create cache persistence
			*/
			$this->log('d', 'Creating cache persistence..');
			common_persistence_Manager::addPersistence('cache', array(
                'driver' => 'phpfile'
			));
			common_persistence_KeyValuePersistence::getPersistence('cache')->purge();
			
			/*
			 * 5c - Create generis persistence 
			 */
            $this->log('d', 'Creating generis persistence..');
			common_persistence_Manager::addPersistence('default', $dbConfiguration);

			/*
			 * 5d - Create generis user
			*/
					
			// Init model creator and create the Generis User.
            $this->log('d', 'Creating generis user..');
			$modelCreator = new tao_install_utils_ModelCreator(LOCAL_NAMESPACE);
			$modelCreator->insertGenerisUser(helpers_Random::generateString(8));

			/*
			 * 6 - Add languages
			 */
            $this->log('d', 'Adding languages..');
			$models = $modelCreator->getLanguageModels();
                        foreach ($models as $ns => $modelFiles){
                            foreach ($modelFiles as $file){
                                $this->log('d', "Inserting language description model '".$file."'");
                                $modelCreator->insertLocalModel($file);
                            }
                        }

			/*
			 * 7 - Finish Generis Install
			 */

            $this->log('d', 'Finishing generis install..');
			$generis = common_ext_ExtensionsManager::singleton()->getExtensionById('generis');

			$generisInstaller = new common_ext_GenerisInstaller($generis, true);
			$generisInstaller->initContainer($this->getContainer());
			$generisInstaller->install();

	        /*
			 * 8 - Install the extensions
			 */
	        InstallHelper::initContainer($this->container);
			$installed = InstallHelper::installRecursively($extensionIDs, $installData);
			$this->log('ext', $installed);

            /*
             *  8b - Generates client side translation bundles (depends on extension install)
             */
			$this->log('i', 'Generates client side translation bundles');
            
			$files = tao_models_classes_LanguageService::singleton()->generateAll();

			/*
			 *  9 - Insert Super User
			 */
			$this->log('i', 'Spawning SuperUser '.$installData['user_login']);
			$modelCreator->insertSuperUser(array(
				'login'			=> $installData['user_login'],
				'password'		=> core_kernel_users_Service::getPasswordHash()->encrypt($installData['user_pass1']),
				'userLastName'	=> $installData['user_lastname'],
				'userFirstName'	=> $installData['user_firstname'],
				'userMail'		=> $installData['user_email'],
				'userDefLg'		=> 'http://www.tao.lu/Ontologies/TAO.rdf#Lang'.$installData['module_lang'],
				'userUILg'		=> 'http://www.tao.lu/Ontologies/TAO.rdf#Lang'.$installData['module_lang'],
                'userTimezone'  => TIME_ZONE
			));


			/*
			 *  10 - Secure the install for production mode
			 */
			if($installData['module_mode'] == 'production'){
				$extensions = common_ext_ExtensionsManager::singleton()->getInstalledExtensions();
				$this->log('i', 'Securing tao for production');
				
				// 11.1 Remove Generis User
				$dbCreator->removeGenerisUser();
				
				// 11.2 Protect TAO dist
	 			$shield = new tao_install_utils_Shield(array_keys($extensions));
	 			$shield->disableRewritePattern(array("!/test/", "!/doc/"));
                                $shield->denyAccessTo(array(
                                    'views/sass',
                                    'views/js/test',
                                    'views/build'
                                ));
	 			$shield->protectInstall();
			}

			/*
			 *  11 - Create the version file
			 */
			$this->log('d', 'Creating TAO version file');
			file_put_contents($installData['file_path'].'version', TAO_VERSION);
            
            /*
             * 12 - Register Information about organization operating the system
             */
            $this->log('t', 'Registering information about the organization operating the system');
            $operatedByService = $this->getServiceManager()->get(OperatedByService::SERVICE_ID);
            
            if (!empty($installData['operated_by_name'])) {
                $operatedByService->setName($installData['operated_by_name']);
            }
            
            if (!empty($installData['operated_by_email'])) {
                $operatedByService->setEmail($installData['operated_by_email']);
            }
            
            $this->getServiceManager()->register(OperatedByService::SERVICE_ID, $operatedByService);
            
		}
		catch(Exception $e){
			if ($this->retryInstallation($e)) {
				return;
			}

			// In any case, we transmit a single exception type (at the moment)
			// for a clearer API for client code.
            $this->log('e', 'Error Occurs : ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString());
			throw new tao_install_utils_Exception($e->getMessage(), 0, $e);
		}
	}
51456
private function getDictionaryOverrides(array &$data): array
    {
        $overrides = [];
        foreach (['source_language', 'target_language'] as $key) {
            if (array_key_exists($key, $data)) {
                $overrides[$key] = $data[$key];
                unset($data[$key]);
            }
        }

        return $overrides;
    }
85971
public function import($data) {
		
		if (! is_array($data)) {
			$data = $this->makeArray($data);
		}
		
		foreach($data as $key => $value) {
			$this->set($key, $value);
		}
	}
998146
private function overrideConfiguration(array $configuration, array $override)
    {
        $configuration['parameters'] = array_replace(
            $configuration['parameters'],
            $override['parameters']
        );

        unset($override['parameters']);

        return array_replace($configuration, $override);
    }
835229
public function translate(array $overrides = [])
    {
        array_replace_recursive($this->parameters, $overrides);

        $id = isset($this->parameters['id']) ? $this->parameters['id'] : null;
        $value = isset($this->parameters['value']) ? $this->parameters['value'] : null;
        $arguments = isset($this->parameters['arguments']) ? $this->parameters['arguments'] : [];
        $source = isset($this->parameters['source']) ? $this->parameters['source'] : 'Main';
        $package = isset($this->parameters['package']) ? $this->parameters['package'] : null;
        $quantity = isset($this->parameters['quantity']) ? $this->parameters['quantity'] : null;
        $locale = isset($this->parameters['locale']) ? $this->parameters['locale'] : null;

        if ($id === null) {
            return $this->translator->translateByOriginalLabel($value, $arguments, $quantity, $locale, $source, $package);
        }

        $translation = $this->translator->translateById($id, $arguments, $quantity, $locale, $source, $package);
        if ($translation === null && $value !== null) {
            return $this->translator->translateByOriginalLabel($value, $arguments, $quantity, $locale, $source, $package);
        }

        return $translation;
    }
862541
public function append($append = [], $override = false)
    {
        $this->append = $override ? $append : array_merge($this->append, $append);

        return $this;
    }
972810
public function import($data)
    {
        if (isset($data['OXUSERNAME'])) {
            $id = $data['OXID'];
            $userName = $data['OXUSERNAME'];

            $user = oxNew(\OxidEsales\Eshop\Application\Model\User::class, "core");
            $user->oxuser__oxusername = new \OxidEsales\Eshop\Core\Field($userName, \OxidEsales\Eshop\Core\Field::T_RAW);

            if ($user->exists($id) && $id != $user->getId()) {
                throw new Exception("USER $userName already exists!");
            }
        }

        return parent::import($data);
    }
757302
public void updateConfigAll(AbstractInterfaceConfig config, String overridePath, List<ChildData> currentData)
        throws UnsupportedEncodingException {
        if (CommonUtils.isEmpty(currentData)) {
            if (LOGGER.isInfoEnabled(config.getAppName())) {
                LOGGER.infoWithApp(config.getAppName(), "Receive updateAll data is null");
            }
        } else {
            if (LOGGER.isInfoEnabled(config.getAppName())) {
                for (ChildData data : currentData) {
                    LOGGER.infoWithApp(config.getAppName(),
                        "Receive updateAll data: path=[" + data.getPath() + "], data=[" +
                            StringSerializer.decode(data.getData()) + "]" + ", stat=[" + data.getStat() + "]");
                }
            }
            List<ConfigListener> configListeners = configListenerMap.get(config);
            if (CommonUtils.isNotEmpty(configListeners)) {
                List<Map<String, String>> attributes = ZookeeperRegistryHelper.convertOverrideToAttributes(
                    config, overridePath, currentData);
                for (ConfigListener listener : configListeners) {
                    for (Map<String, String> attribute : attributes) {
                        listener.attrUpdated(attribute);
                    }
                }
            }
        }
    }
1338469
protected function _importData()
    {
        if (Import::BEHAVIOR_DELETE == $this->getBehavior()) {
            $this->deleteCategories();
        } else {
            $this->saveCategories();
            $this->saveOnTab();
        }

        //$this->reindexImportedCategories();

        $this->eventManager->dispatch('catalog_category_import_finish_before', ['adapter' => $this]);

        return true;
    }
239769
public function import(array $data): void
    {
        if(!$this->isDataSetProperly($data)) {
            return;
        }

        $wakeup = function (array $array): EncapsulatedEdge {
            return EncapsulatedEdge::fromArray($array);
        };

        $this->out = array_map($wakeup, $data["out"]); 
        $this->in = array_map($wakeup, $data["in"]); 
        foreach($data["from"] as $from => $frozen) {
            $this->from[$from] = array_map($wakeup, $frozen); 
        }
        foreach($data["to"] as $to => $frozen) {
            $this->to[$to] = array_map($wakeup, $frozen); 
        }
    }