public static function updateAppVersion(CommandEvent $event) { $configs = self::getConfigs($event); $yamlParser = new Parser(); foreach ($configs as $config) { $config = self::processConfig($config); $realFile = $config['file']; $parameterKey = $config['parameter-key']; $versionKey = $config['app-version-key']; try { $distValues = $yamlParser->parse(file_get_contents($config['dist-file'])); $actualValues = $yamlParser->parse(file_get_contents($realFile)); // Checking on dist file is enough as Incenteev's parameter builder runs first if (array_key_exists($versionKey, $distValues[$parameterKey])) { $currentVersion = $actualValues[$parameterKey][$versionKey]; $newVersion = $distValues[$parameterKey][$versionKey]; // Replace the current version with the updated from the dist file if changed if ($currentVersion != $newVersion) { $actualValues[$parameterKey][$versionKey] = $newVersion; file_put_contents($realFile, Yaml::dump($actualValues, 99)); $event->getIO()->write(sprintf('<info>App version updated to "%s"</info>', $newVersion)); } } } catch (ParseException $e) { printf("Unable to parse the YAML string: %s", $e->getMessage()); } } }
/** * @param string $data * @param string $format * @param array $context * * @return mixed */ public function decode($data, $format, array $context = array()) { if ($this->native) { return yaml_parse($data); } return $this->decoder->parse($data); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $configName = $input->getArgument('name'); $fileName = $input->getArgument('file'); $config = $this->getDrupalService('config.factory')->getEditable($configName); $ymlFile = new Parser(); if (!empty($fileName) && file_exists($fileName)) { $value = $ymlFile->parse(file_get_contents($fileName)); } else { $value = $ymlFile->parse(stream_get_contents(fopen("php://stdin", "r"))); } if (empty($value)) { $io->error($this->trans('commands.config.import.single.messages.empty-value')); return; } $config->setData($value); try { $config->save(); } catch (\Exception $e) { $io->error($e->getMessage()); return 1; } $io->success(sprintf($this->trans('commands.config.import.single.messages.success'), $configName)); }
/** * Loads and parses the config file * * @param string $env Environment * @param string $file Config filename * @return void * @throws \Exception */ private function load($env = 'local', $file = 'config') { $path = BASE_PATH . ($file === '.env' ? '' : '/config'); // File paths $configPath = "{$path}/{$file}.yml"; $envConfigPath = "{$path}/{$file}_{$env}.yml"; if (!file_exists($configPath)) { throw new \Exception("Config file not found at \"{$configPath}\"."); } $data = file_get_contents($configPath); if ($data === false) { throw new \Exception("Unable to load configuration from: {$configPath}"); } $yaml = new Parser(); // Load config $config = $yaml->parse($data); $this->config = $config ? $config : []; // Load environment specific config if (file_exists($envConfigPath)) { $data = file_get_contents($envConfigPath); if ($data) { $config = $yaml->parse($data); $config = $config ? $config : []; // Merge config values $this->config = array_merge($this->config, $config); } } }
/** * @param string $filePath * * @throws ConfigNotFoundException * @throws ParseException * * @return array The parsed configuration */ public function parseConfig($filePath) { if (!file_exists($filePath)) { throw new ConfigNotFoundException(sprintf('Configuration file not found: %s', $filePath)); } return $this->yamlParser->parse(file_get_contents($filePath)); }
/** * @param string $file * @return array */ protected function loadFile($file) { if (!class_exists('Symfony\\Component\\Yaml\\Parser')) { throw new \RuntimeException('Unable to load YAML config files as the Symfony Yaml Component is not installed.'); } if (!stream_is_local($file)) { throw new \InvalidArgumentException(sprintf('This is not a local file "%s".', $file)); } if (!file_exists($file)) { throw new \InvalidArgumentException(sprintf('The service file "%s" is not valid.', $file)); } if (null === $this->yamlParser) { $this->yamlParser = new Parser(); } try { $config = $this->yamlParser->parse(file_get_contents($file)); if (!is_array($config)) { throw new \InvalidArgumentException(sprintf('The contents of the file "%s" is not an array.', $file)); } } catch (ParseException $e) { throw new \InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML.', $file), 0, $e); } $this->app->parseParameters($config); return $config; }
public function setConfig($config) { if (!file_exists($config) || !is_readable($config)) { throw new \Exception('Unable to parse configuration file.'); } $this->config = $this->parser->parse(file_get_contents($config)); }
public function configureAction() { $data = []; $data['data']['page'] = 'config'; $parametersFile = __DIR__ . '/../../../../app/config/parameters.yml'; $parametersFileDist = $parametersFile . '.dist'; $formData = new Config(); $parser = new Parser(); if (file_exists($parametersFile)) { $formDataFile = $parser->parse(file_get_contents($parametersFile)); } else { $formDataFile = $parser->parse(file_get_contents($parametersFileDist)); } foreach ($formDataFile['parameters'] as $key => $value) { $setter = 'set' . implode('', array_map(function ($s) { return ucfirst($s); }, explode('_', $key))); if (method_exists($formData, $setter)) { $formData->{$setter}($value); } } $form = $this->createForm(new ConfigType(), $formData, ['method' => 'post', 'action' => $this->get('router')->generate('ojs_installer_save_configure')]); $data['form'] = $form->createView(); return $this->render("OjsInstallerBundle:Default:configure.html.twig", $data); }
public function processFile(array $config) { $config = $this->processConfig($config); $realFile = $config['file']; $distFile = $config['dist-file']; $parameterKey = $config['parameter-key']; $exists = is_file($realFile); $yamlParser = new Parser(); if (!$exists) { if ($this->checkPermissionToInstall()) { $this->io->write(sprintf('<info>%s the "%s" file</info>', 'Creating', $realFile)); // Find the expected params $expectedValues = $yamlParser->parse(file_get_contents($distFile)); if (!isset($expectedValues[$parameterKey])) { throw new \InvalidArgumentException(sprintf('The top-level key %s is missing.', $parameterKey)); } $expectedParams = (array) $expectedValues[$parameterKey]['endpoints']; // find the actual params $actualValues = array_merge($expectedValues, array($parameterKey => array('endpoints' => array()))); $actualValues[$parameterKey]['endpoints'] = $this->processParams($config, $expectedParams, (array) $actualValues[$parameterKey]['endpoints']); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://' . $actualValues[$parameterKey]['endpoints'][$this->getEndPointName()]['host'] . ':' . $actualValues[$parameterKey]['endpoints'][$this->getEndPointName()]['port'] . $actualValues[$parameterKey]['endpoints'][$this->getEndPointName()]['path'] . '/admin/cores?action=CREATE&name=' . $actualValues[$parameterKey]['endpoints'][$this->getEndPointName()]['core'] . '&configSet=configset1'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_exec($ch); curl_close($ch); $this->processWriteValuesToFile($actualValues, $realFile); $this->importToConfigFile($realFile); } else { $this->processWriteValuesToFile($yamlParser->parse(file_get_contents($distFile)), $realFile); } } }
/** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $this->bindParameters($container, $this->getAlias(), $config); // Fallback for missing intl extension $intlExtensionInstalled = extension_loaded('intl'); $container->setParameter('lunetics_locale.intl_extension_installed', $intlExtensionInstalled); $iso3166 = array(); $iso639one = array(); $iso639two = array(); $localeScript = array(); if (!$intlExtensionInstalled) { $yamlParser = new YamlParser(); $file = new FileLocator(__DIR__ . '/../Resources/config'); $iso3166 = $yamlParser->parse(file_get_contents($file->locate('iso3166-1-alpha-2.yml'))); $iso639one = $yamlParser->parse(file_get_contents($file->locate('iso639-1.yml'))); $iso639two = $yamlParser->parse(file_get_contents($file->locate('iso639-2.yml'))); $localeScript = $yamlParser->parse(file_get_contents($file->locate('locale_script.yml'))); } $container->setParameter('lunetics_locale.intl_extension_fallback.iso3166', $iso3166); $mergedValues = array_merge($iso639one, $iso639two); $container->setParameter('lunetics_locale.intl_extension_fallback.iso639', $mergedValues); $container->setParameter('lunetics_locale.intl_extension_fallback.script', $localeScript); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('validator.xml'); $loader->load('guessers.xml'); $loader->load('services.xml'); $loader->load('switcher.xml'); $loader->load('form.xml'); if (!$config['strict_match']) { $container->removeDefinition('lunetics_locale.best_locale_matcher'); } }
/** * Loads a resource. * * @param mixed $resource The resource * @param string $type The resource type * @return array */ public function load($resource, $type = NULL) { $path = $this->locator->locate($resource); $file = $this->filesystem->openFile($path); $configValues = $this->yamlParser->parse($file->getContents()); return $configValues; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $configName = $input->getArgument('name'); $fileName = $input->getArgument('file'); $ymlFile = new Parser(); if (!empty($fileName) && file_exists($fileName)) { $value = $ymlFile->parse(file_get_contents($fileName)); } else { $value = $ymlFile->parse(stream_get_contents(fopen("php://stdin", "r"))); } if (empty($value)) { $io->error($this->trans('commands.config.import.single.messages.empty-value')); return; } try { $source_storage = new StorageReplaceDataWrapper($this->configStorage); $source_storage->replaceData($configName, $value); $storage_comparer = new StorageComparer($source_storage, $this->configStorage, $this->configManager); if ($this->configImport($io, $storage_comparer)) { $io->success(sprintf($this->trans('commands.config.import.single.messages.success'), $configName)); } } catch (\Exception $e) { $io->error($e->getMessage()); return 1; } }
/** * Load the YAML config's */ public function load() { if (file_exists($this->config_path . '/' . $this->config_file)) { $yaml = new Parser(); global $config; $config = (array) $yaml->parse(file_get_contents($this->config_path . '/' . $this->config_file)); if (!empty($config['WP_ENV']) && file_exists($this->config_path . '/config_' . $config['WP_ENV'] . '.yml')) { $env = $yaml->parse(file_get_contents($this->config_path . '/config_' . $config['WP_ENV'] . '.yml')); if (!empty($env)) { $config = array_merge($config, $env); } } if (!empty($config['imports'])) { foreach ($config['imports'] as $import) { if (!empty($import['resource']) && file_exists($this->config_path . '/' . $import['resource'])) { $import = $yaml->parse(file_get_contents($this->config_path . '/' . $import['resource'])); $config = array_merge($config, $import); } } unset($config['imports']); } foreach ($config as $key => $value) { if (!is_array($value)) { define($key, $value); unset($config[$key]); } } } }
private function configureParameters() { $yaml = new Parser(); $this['root_dir'] = __DIR__ . '/../..'; $this['config_dir'] = __DIR__ . '/Resources/config'; $this['config'] = ['settings' => $yaml->parse(file_get_contents($this['config_dir'] . '/settings.yml')), 'heroes' => $yaml->parse(file_get_contents($this['config_dir'] . '/heroes.yml')), 'items' => $yaml->parse(file_get_contents($this['config_dir'] . '/items.yml')), 'map' => $yaml->parse(file_get_contents($this['config_dir'] . '/map.yml'))]; }
/** * @param $file * @return array */ public function getFileContents($file) { if (file_exists($file)) { return $this->parser->parse(file_get_contents($file)); } return []; }
public function processFile(array $config) { $config = $this->processConfig($config); $realFile = $config['file']; $parameterKey = $config['parameter-key']; $exists = is_file($realFile); $yamlParser = new Parser(); $action = $exists ? 'Updating' : 'Creating'; $this->io->write(sprintf('<info>%s the "%s" file</info>', $action, $realFile)); // Find the expected params $expectedValues = $yamlParser->parse(file_get_contents($config['dist-file'])); if (!isset($expectedValues[$parameterKey])) { throw new \InvalidArgumentException(sprintf('The top-level key %s is missing.', $parameterKey)); } $expectedParams = (array) $expectedValues[$parameterKey]; // find the actual params $actualValues = array_merge($expectedValues, array($parameterKey => array())); if ($exists) { $existingValues = $yamlParser->parse(file_get_contents($realFile)); if ($existingValues === null) { $existingValues = array(); } if (!is_array($existingValues)) { throw new \InvalidArgumentException(sprintf('The existing "%s" file does not contain an array', $realFile)); } $actualValues = array_merge($actualValues, $existingValues); } $actualValues[$parameterKey] = $this->processParams($config, $expectedParams, (array) $actualValues[$parameterKey]); if (!is_dir($dir = dirname($realFile))) { mkdir($dir, 0755, true); } file_put_contents($realFile, "# This file is auto-generated during the composer install\n" . Yaml::dump($actualValues, 99)); }
public function getDataFormSpecifications() { $parser = new Parser(); $path = __DIR__.'/Fixtures'; $tests = array(); $files = $parser->parse(file_get_contents($path.'/index.yml')); foreach ($files as $file) { $yamls = file_get_contents($path.'/'.$file.'.yml'); // split YAMLs documents foreach (preg_split('/^---( %YAML\:1\.0)?/m', $yamls) as $yaml) { if (!$yaml) { continue; } $test = $parser->parse($yaml); if (isset($test['todo']) && $test['todo']) { // TODO } else { $expected = var_export(eval('return '.trim($test['php']).';'), true); $tests[] = array($file, $expected, $test['yaml'], $test['test']); } } } return $tests; }
public function testLoad() { $this->yamlParser->parse(file_get_contents(__DIR__ . '/../Resources/Yaml/routes.yml'))->willReturn(['user' => ['channel' => 'notification/user/{username}', 'handler' => ['callback' => ['Gos\\Bundle\\PubSubRouterBundle\\Tests\\Model', 'setPushers'], 'args' => ['gos_redis', 'gos_websocket']], 'requirements' => ['username' => ['pattern' => '[a-zA-Z0-9]+', 'wildcard' => true]]], 'application' => ['channel' => 'notification/application/{applicationName}', 'handler' => ['callback' => ['Gos\\Bundle\\PubSubRouterBundle\\Tests\\Model', 'setPushers'], 'args' => ['gos_redis', 'gos_websocket']], 'requirements' => ['applicationName' => ['pattern' => '[a-zA-Z0-9]+', 'wildcard' => true]]]]); $this->injectYamlParser(); $routeCollection = $this->loader->load('@Resource/routes.yml'); $this->assertEquals(['user' => new Route('notification/user/{username}', ['Gos\\Bundle\\PubSubRouterBundle\\Tests\\Model', 'setPushers'], ['gos_redis', 'gos_websocket'], ['username' => ['pattern' => '[a-zA-Z0-9]+', 'wildcard' => true]]), 'application' => new Route('notification/application/{applicationName}', ['Gos\\Bundle\\PubSubRouterBundle\\Tests\\Model', 'setPushers'], ['gos_redis', 'gos_websocket'], ['applicationName' => ['pattern' => '[a-zA-Z0-9]+', 'wildcard' => true]])], $this->readProperty($routeCollection, 'routes')); }
/** * {@inheritdoc} */ public function getUsergroups() { $usergroups = []; $iterator = new DirectoryIterator($this->folder); foreach ($iterator as $file) { /** @var DirectoryIterator $file */ if (false !== strpos($file->getBasename(), '.html')) { $content = file_get_contents($file->getRealPath()); if (empty($content)) { continue; } // "extract" the YAML Parts from the input file $content = explode('---', $content); if (!isset($content[1]) || count($content) !== 3) { continue; } $content = $content[1]; $values = $this->yamlParser->parse($content); $slug = isset($values['title']) ? $values['title'] : null; $type = isset($values['eventFeed'], $values['eventFeed']['type']) ? $values['eventFeed']['type'] : null; $eventLink = isset($values['eventFeed'], $values['eventFeed']['url']) ? $values['eventFeed']['url'] : null; if (null === $slug || null === $type || null === $eventLink) { continue; } $usergroups[] = new Usergroup($slug, $type, $eventLink); } } return $usergroups; }
/** * @param string $path The path to a file defining \Assimtech\Tempo\Infrastructure * defaults to 'tempo/infrastructure.yml' * @return \Assimtech\Tempo\Infrastructure */ public function load($path) { $this->validatePath($path); $yaml = file_get_contents($path); $config = $this->yamlParser->parse($yaml); $infrastructure = $this->factory->create($config); return $infrastructure; }
/** * @inheritdoc */ public function getConfig() { $config = []; foreach ($this->iterate($this->pattern) as $file) { $config = ArrayUtil::merge($config, $this->parser->parse(file_get_contents($file->getRealPath()))); } return $config; }
/** * @return Label */ public function getLabels() { $array = $this->yamlParser->parse($this->rawData); if (!isset($array['columns']) || !isset($array['rows'])) { throw new \RuntimeException('file in unexpected format'); } return $this->labelFactory->getFromRaw($array); }
public static function setUpBeforeClass() { $yamlParser = new YamlParser(); $file = new FileLocator(__DIR__ . '/../../Resources/config'); self::$iso3166 = $yamlParser->parse(file_get_contents($file->locate('iso3166-1-alpha-2.yml'))); self::$iso639 = array_merge($yamlParser->parse(file_get_contents($file->locate('iso639-1.yml'))), $yamlParser->parse(file_get_contents($file->locate('iso639-2.yml')))); self::$script = $yamlParser->parse(file_get_contents($file->locate('locale_script.yml'))); }
/** * @param string $configPath */ public function loadData($configPath) { $data = $this->parser->parse($this->loader->load($configPath)); if (!is_array($data)) { throw new \RuntimeException('Error parsing config file'); } $this->data = $data; }
public function loadGuests() { $guestConfigFilename = $this->getConfigPath() . '/' . $this->getEnvironment() . '.guests.yml'; $guests = $this->yamlParser->parse(file_get_contents($guestConfigFilename)); foreach ($guests as $label => $guestAppConfig) { $this->addGuestAppConfig($label, $guestAppConfig); } }
/** * {@inheritdoc} */ public function parse(string $payload) : array { try { return $this->parser->parse(trim(preg_replace('/\\t+/', '', $payload))); } catch (YamlParseException $exception) { throw new ParseException(['message' => $exception->getMessage()]); } }
/** * Returns a property provider primed with property info from the stam file * @return PropertyProvider */ protected function getPropertyProvider() { $structure = $this->yamlParser->parse($this->stamFile->getContents()); foreach ($structure['stam']['properties'] as $name => $spec) { $this->propertyProvider->addProperty($name, $spec); } return $this->propertyProvider; }
/** * @param $file * @return mixed * @throws YamlProviderException */ public function parse($file) { try { return $this->parser->parse(file_get_contents($file)); } catch (ParseException $e) { throw new YamlProviderException($e->getMessage()); } }
protected function execute(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $yaml = new Parser(); $yaml_left = $input->getArgument('yaml-left'); $yaml_right = $input->getArgument('yaml-right'); $stats = $input->getOption('stats'); $negate = $input->getOption('negate'); $limit = $input->getOption('limit'); $offset = $input->getOption('offset'); if ($negate == 1 || $negate == 'TRUE') { $negate = true; } else { $negate = false; } try { $yamlLeftParsed = $yaml->parse(file_get_contents($yaml_left)); if (empty($yamlLeftParsed)) { $io->error(sprintf($this->trans('commands.yaml.merge.messages.wrong-parse'), $yaml_left)); } $yamlRightParsed = $yaml->parse(file_get_contents($yaml_right)); if (empty($yamlRightParsed)) { $io->error(sprintf($this->trans('commands.yaml.merge.messages.wrong-parse'), $yaml_right)); } } catch (\Exception $e) { $io->error($this->trans('commands.yaml.merge.messages.error-parsing') . ': ' . $e->getMessage()); return; } $statistics = ['total' => 0, 'equal' => 0, 'diff' => 0]; /* print_r($yamlLeftParsed); print_r($yamlRightParsed);*/ $diff = $this->nestedArray->arrayDiff($yamlLeftParsed, $yamlRightParsed, $negate, $statistics); print_r($diff); if ($stats) { $io->info(sprintf($this->trans('commands.yaml.diff.messages.total'), $statistics['total'])); $io->info(sprintf($this->trans('commands.yaml.diff.messages.diff'), $statistics['diff'])); $io->info(sprintf($this->trans('commands.yaml.diff.messages.equal'), $statistics['equal'])); return; } // FLAT YAML file to display full yaml to be used with command yaml:update:key or yaml:update:value $diffFlatten = array(); $keyFlatten = ''; $this->nestedArray->yamlFlattenArray($diff, $diffFlatten, $keyFlatten); if ($limit !== null) { if (!$offset) { $offset = 0; } $diffFlatten = array_slice($diffFlatten, $offset, $limit); } $tableHeader = [$this->trans('commands.yaml.diff.messages.key'), $this->trans('commands.yaml.diff.messages.value')]; $tableRows = []; foreach ($diffFlatten as $yamlKey => $yamlValue) { $tableRows[] = [$yamlKey, $yamlValue]; print $yamlKey . "\n"; print $yamlValue . "\n"; } $io->table($tableHeader, $tableRows, 'compact'); }
protected function syncTranslations($io, $language = null, $languages, $file, $appRoot) { $englishFilesFinder = new Finder(); $yaml = new Parser(); $dumper = new Dumper(); $englishDirectory = $appRoot . 'config/translations/en'; if ($file) { $englishFiles = $englishFilesFinder->files()->name($file)->in($englishDirectory); } else { $englishFiles = $englishFilesFinder->files()->name('*.yml')->in($englishDirectory); } foreach ($englishFiles as $file) { $resource = $englishDirectory . '/' . $file->getBasename(); $filename = $file->getBasename('.yml'); try { $englishFile = file_get_contents($resource); $englishFileParsed = $yaml->parse($englishFile); } catch (ParseException $e) { $io->error($filename . '.yml: ' . $e->getMessage()); continue; } foreach ($languages as $langCode => $languageName) { $languageDir = $appRoot . 'config/translations/' . $langCode; if (isset($language) && $langCode != $language) { continue; } if (!isset($statistics[$langCode])) { $statistics[$langCode] = ['total' => 0, 'equal' => 0, 'diff' => 0]; } $resourceTranslated = $languageDir . '/' . $file->getBasename(); if (!file_exists($resourceTranslated)) { file_put_contents($resourceTranslated, $englishFile); $io->info(sprintf($this->trans('commands.translation.sync.messages.created-file'), $file->getBasename(), $languageName)); continue; } try { //print $resourceTranslated . "\n"; $resourceTranslatedParsed = $yaml->parse(file_get_contents($resourceTranslated)); } catch (ParseException $e) { $io->error($resourceTranslated . ':' . $e->getMessage()); continue; } $resourceTranslatedParsed = array_replace_recursive($englishFileParsed, $resourceTranslatedParsed); try { $resourceTranslatedParsedYaml = $dumper->dump($resourceTranslatedParsed, 10); } catch (\Exception $e) { $io->error(sprintf($this->trans('commands.translation.sync.messages.error-generating'), $resourceTranslated, $languageName, $e->getMessage())); continue; } try { file_put_contents($resourceTranslated, $resourceTranslatedParsedYaml); } catch (\Exception $e) { $io->error(sprintf('%s: %s', $this->trans('commands.translation.sync.messages.error-writing'), $resourceTranslated, $languageName, $e->getMessage())); return 1; } } } }