Author: Fabien Potencier (fabien.potencier@symfony-project.com)
Beispiel #1
2
 /**
  * Parses YAML into a PHP array.
  *
  * The parse method, when supplied with a YAML stream (string or file),
  * will do its best to convert YAML in a file into a PHP array.
  *
  *  Usage:
  *  <code>
  *   $array = Yaml::parse('config.yml');
  *   print_r($array);
  *  </code>
  *
  * @param string $input Path to a YAML file or a string containing YAML
  *
  * @return array The YAML converted to a PHP array
  *
  * @throws \InvalidArgumentException If the YAML is not valid
  *
  * @api
  */
 public static function parse($input)
 {
     // if input is a file, process it
     $file = '';
     if (strpos($input, "\n") === false && is_file($input)) {
         if (false === is_readable($input)) {
             throw new ParseException(sprintf('Unable to parse "%s" as the file is not readable.', $input));
         }
         $file = $input;
         if (self::$enablePhpParsing) {
             ob_start();
             $retval = (include $file);
             $content = ob_get_clean();
             // if an array is returned by the config file assume it's in plain php form else in YAML
             $input = is_array($retval) ? $retval : $content;
             // if an array is returned by the config file assume it's in plain php form else in YAML
             if (is_array($input)) {
                 return $input;
             }
         } else {
             $input = file_get_contents($file);
         }
     }
     $yaml = new Parser();
     try {
         return $yaml->parse($input);
     } catch (ParseException $e) {
         if ($file) {
             $e->setParsedFile($file);
         }
         throw $e;
     }
 }
Beispiel #2
0
 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'))];
 }
 /**
  * {@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');
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $configName = $input->getArgument('config-name');
     $editor = $input->getArgument('editor');
     $config = $this->getConfigFactory()->getEditable($configName);
     $configSystem = $this->getConfigFactory()->get('system.file');
     $temporalyDirectory = $configSystem->get('path.temporary') ?: '/tmp';
     $configFile = $temporalyDirectory . '/config-edit/' . $configName . '.yml';
     $ymlFile = new Parser();
     $fileSystem = new Filesystem();
     try {
         $fileSystem->mkdir($temporalyDirectory);
         $fileSystem->dumpFile($configFile, $this->getYamlConfig($configName));
     } catch (IOExceptionInterface $e) {
         throw new \Exception($this->trans('commands.config.edit.messages.no-directory') . ' ' . $e->getPath());
     }
     if (!$editor) {
         $editor = $this->getEditor();
     }
     $processBuilder = new ProcessBuilder(array($editor, $configFile));
     $process = $processBuilder->getProcess();
     $process->setTty('true');
     $process->run();
     if ($process->isSuccessful()) {
         $value = $ymlFile->parse(file_get_contents($configFile));
         $config->setData($value);
         $config->save();
         $fileSystem->remove($configFile);
     }
     if (!$process->isSuccessful()) {
         throw new \RuntimeException($process->getErrorOutput());
     }
 }
 /**
  * Prepares test environment.
  */
 public function setUp()
 {
     $finder = new Finder();
     $finder->files()->in(__DIR__ . '/config/');
     $finder->name('*.yml');
     $this->dummyParser = $this->getMock('Symfony\\Component\\Yaml\\Parser');
     $this->dummyDumper = $this->getMock('Symfony\\Component\\Yaml\\Dumper');
     $this->dummyFilesystem = $this->getMock('Symfony\\Component\\Filesystem\\Filesystem');
     $dummyDispatcher = $this->getMock('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface');
     $dummyDispatcher->expects($this->once())->method('dispatch')->willReturnCallback(function ($name, $event) {
         /** @var GroupOptionTypeEvent $event */
         $optionTypes = ['acp' => ['twomartens.core' => ['access' => new BooleanOptionType()]]];
         $event->addOptions($optionTypes);
     });
     $this->yamlData = [];
     $this->optionData = [];
     foreach ($finder as $file) {
         /** @var SplFileInfo $file */
         $basename = $file->getBasename('.yml');
         $this->yamlData[$basename] = Yaml::parse($file->getContents());
         $this->optionData[$basename] = ConfigUtil::convertToOptions($this->yamlData[$basename]);
     }
     $this->dummyParser->expects($this->any())->method('parse')->willReturnCallback(function ($content) {
         return Yaml::parse($content);
     });
     /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $dummyDispatcher */
     $this->groupService = new GroupService($finder, $this->dummyParser, $this->dummyDumper, $this->dummyFilesystem, $dummyDispatcher);
 }
 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));
 }
Beispiel #7
0
 function __construct($configFile)
 {
     $yaml = new Parser();
     $config = $yaml->parse(file_get_contents($configFile));
     $processor = new Processor();
     $this->config = $processor->processConfiguration(new Schema(), $config);
 }
Beispiel #8
0
 /**
  * Read yml file to load config vars.
  *
  * @param string $file
  *
  * @return self
  */
 public function loadFile($file = '')
 {
     try {
         $yaml = new Parser();
         if (empty($file)) {
             $file = GLOBAL_PATH . '/App/Config.yml';
         }
         $elements = $yaml->parse(file_get_contents($file));
         if (!empty($this->vars)) {
             $this->vars += $elements;
         } else {
             $this->vars = $elements;
             $this->setParams();
         }
         // Enable debugBar
         if ($this['core']['DEBUG_BAR'] === true) {
             $debugbarResourcesPath = '/vendor/maximebf/debugbar/src/DebugBar/Resources';
             if (isset($this['app']['RESOURCES'][GLOBAL_PATH . $debugbarResourcesPath])) {
                 $debugbarResourcesPath = $this['app']['RESOURCES'][GLOBAL_PATH . $debugbarResourcesPath];
             }
             $this->debugbar = new StandardDebugBar();
             $this->debugbarRenderer = $this->debugbar->getJavascriptRenderer($debugbarResourcesPath)->setEnableJqueryNoConflict(false);
             $this->debugbar['time']->startMeasure('render');
             $this->debugbar->addCollector(new \DebugBar\DataCollector\ConfigCollector($this->vars));
         }
         return $this;
     } catch (ParseException $e) {
         throw new QException(sprintf('Unable to parse the YAML string: %s', $e->getMessage()));
     }
 }
Beispiel #9
0
 /**
  * Parses YAML into a PHP array.
  *
  * The parse method, when supplied with a YAML stream (string or file),
  * will do its best to convert YAML in a file into a PHP array.
  *
  *  Usage:
  *  <code>
  *   $array = Yaml::parse('config.yml');
  *   print_r($array);
  *  </code>
  *
  * @param string $input Path to a YAML file or a string containing YAML
  *
  * @return array The YAML converted to a PHP array
  *
  * @throws \InvalidArgumentException If the YAML is not valid
  *
  * @api
  */
 public static function parse($input)
 {
     $file = '';
     // if input is a file, process it
     if (strpos($input, "\n") === false && is_file($input) && is_readable($input)) {
         $file = $input;
         ob_start();
         $retval = (include $input);
         $content = ob_get_clean();
         // if an array is returned by the config file assume it's in plain php form else in YAML
         $input = is_array($retval) ? $retval : $content;
     }
     // if an array is returned by the config file assume it's in plain php form else in YAML
     if (is_array($input)) {
         return $input;
     }
     $yaml = new Parser();
     try {
         return $yaml->parse($input);
     } catch (ParseException $e) {
         if ($file) {
             $e->setParsedFile($file);
         }
         throw $e;
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $yaml = new Parser();
     $dumper = new Dumper();
     $yaml_file = $input->getArgument('yaml-file');
     $yaml_key = $input->getArgument('yaml-key');
     $yaml_value = $input->getArgument('yaml-value');
     try {
         $yaml_parsed = $yaml->parse(file_get_contents($yaml_file));
     } catch (\Exception $e) {
         $output->writeln('[+] <error>' . $this->trans('commands.yaml.merge.messages.error-parsing') . ': ' . $e->getMessage() . '</error>');
         return;
     }
     if (empty($yaml_parsed)) {
         $output->writeln('[+] <info>' . sprintf($this->trans('commands.yaml.merge.messages.wrong-parse'), $yaml_file) . '</info>');
     }
     $nested_array = $this->getNestedArrayHelper();
     $parents = explode(".", $yaml_key);
     $nested_array->setValue($yaml_parsed, $parents, $yaml_value, true);
     try {
         $yaml = $dumper->dump($yaml_parsed, 10);
     } catch (\Exception $e) {
         $output->writeln('[+] <error>' . $this->trans('commands.yaml.merge.messages.error-generating') . ': ' . $e->getMessage() . '</error>');
         return;
     }
     try {
         file_put_contents($yaml_file, $yaml);
     } catch (\Exception $e) {
         $output->writeln('[+] <error>' . $this->trans('commands.yaml.merge.messages.error-writing') . ': ' . $e->getMessage() . '</error>');
         return;
     }
     $output->writeln('[+] <info>' . sprintf($this->trans('commands.yaml.update.value.messages.updated'), $yaml_file) . '</info>');
 }
Beispiel #11
0
 /**
  * Filter value against a blueprint field definition.
  *
  * @param  mixed  $value
  * @param  array  $field
  * @return mixed  Filtered value.
  */
 public static function filter($value, array $field)
 {
     $validate = isset($field['validate']) ? (array) $field['validate'] : array();
     // If value isn't required, we will return null if empty value is given.
     if (empty($validate['required']) && ($value === null || $value === '')) {
         return null;
     }
     // special case for files, value is never empty and errors with code 4 instead
     if (empty($validate['required']) && $field['type'] == 'file' && (isset($value['error']) && ($value['error'] == UPLOAD_ERR_NO_FILE || in_array(UPLOAD_ERR_NO_FILE, $value['error'])))) {
         return null;
     }
     // if this is a YAML field, simply parse it and return the value
     if (isset($field['yaml']) && $field['yaml'] === true) {
         try {
             $yaml = new Parser();
             return $yaml->parse($value);
         } catch (ParseException $e) {
             throw new \RuntimeException($e->getMessage());
         }
     }
     // Validate type with fallback type text.
     $type = (string) isset($field['validate']['type']) ? $field['validate']['type'] : $field['type'];
     $method = 'filter' . strtr($type, '-', '_');
     if (method_exists(__CLASS__, $method)) {
         $value = self::$method($value, $validate, $field);
     } else {
         $value = self::filterText($value, $validate, $field);
     }
     return $value;
 }
 public function import($filename)
 {
     $fname = basename($filename);
     $this->output->writeln("Processing <info>" . $filename . "</info>...");
     list($name, $locale, $type) = explode('.', $fname);
     $this->setIndexes();
     switch ($type) {
         case 'yml':
             $yaml = new Parser();
             $value = $yaml->parse(file_get_contents($filename));
             $data = $this->getContainer()->get('server_grove_translation_editor.storage_manager')->getCollection()->findOne(array('filename' => $filename));
             if (!$data) {
                 $data = array('filename' => $filename, 'locale' => $locale, 'type' => $type, 'entries' => array());
             }
             $this->output->writeln("  Found " . count($value) . " entries...");
             $data['entries'] = $value;
             if (!$this->input->getOption('dry-run')) {
                 $this->updateValue($data);
             }
             break;
         case 'xliff':
             $this->output->writeln("  Skipping, not implemented");
             break;
     }
 }
 public function updateBundleRouting()
 {
     $filename = $this->parameters['bundlePath'] . '/' . $this->filename;
     switch ($this->format) {
         case 'yml':
             if (file_exists($filename)) {
                 $current = file_get_contents($filename);
                 $parser = new Parser();
                 $array = $parser->parse($current);
             } else {
                 $array = array();
                 $current = '';
             }
             if (empty($array[$this->parameters['bundleAlias'] . '_' . $this->parameters['entityUS']])) {
                 $code = $this->parameters['bundleAlias'] . '_' . $this->parameters['entityUS'] . ':';
                 $code .= "\n";
                 $code .= sprintf("    resource: \"@%s/Controller/%sController.php\"", $this->parameters['bundleName'], $this->parameters['entity']);
                 $code .= "\n";
                 $code .= sprintf("    type:     annotation ");
                 $code .= "\n \n";
                 $code .= $current;
                 if (false === file_put_contents($filename, $code)) {
                     throw new \RuntimeException('Could not write to routing.yml');
                 }
             }
             break;
     }
 }
Beispiel #14
0
 /**
  * @param $file
  * @return array
  */
 public function getFileContents($file)
 {
     if (file_exists($file)) {
         return $this->parser->parse(file_get_contents($file));
     }
     return [];
 }
 /**
  * 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;
 }
 public function detailAction($pkg)
 {
     $paquets = shell_exec("sudo /usr/bin/opsi-admin -rd method getProduct_hash '" . $pkg . "'");
     $yaml = new Parser();
     $paquets = $yaml->parse($paquets);
     return $this->render('OWMBundle:Paquets:detail.html.twig', array('paquets' => $paquets));
 }
Beispiel #17
0
 public static function readModules()
 {
     $filePermissions = array();
     $permissions = array();
     $modulePermissions = array();
     foreach (glob(APPPATH . 'modules/*', GLOB_ONLYDIR) as $m) {
         $module = substr(strrchr($m, "/"), 1);
         $file = $m . '/config/permissions.yml';
         if (file_exists($file)) {
             $yaml = new Parser();
             $perms = $yaml->parse(file_get_contents($file));
             $filePermissions[$module] = $perms;
             foreach ($perms as $p) {
                 $permissions[] = $p['name'];
                 $modulePermissions[$module][] = $p['name'];
                 // store permission per modules for db entry
                 // $p['module'] = $module;
                 // $filePermissions[] = $p;
             }
         }
     }
     self::$permissions = $permissions;
     self::$filePermissions = $filePermissions;
     self::$modulePermissions = $modulePermissions;
 }
 public function modifierAction()
 {
     $conf = shell_exec("sudo opsi-admin -rd method getNetworkConfig_hash");
     $yaml = new Parser();
     $conf = $yaml->parse($conf);
     return $this->render('OWMBundle:Configuration:modifier.html.twig', array('depotDrive' => $conf['depotDrive'], 'nextBootServiceURL' => $conf['nextBootServiceURL'], 'utilsUrl' => $conf['utilsUrl'], 'configUrl' => $conf['configUrl'], 'utilsDrive' => $conf['utilsDrive'], 'opsiServer' => $conf['opsiServer'], 'nextBootServerType' => $conf['nextBootServerType'], 'depotUrl' => $conf['depotUrl'], 'depotId' => $conf['depotId'], 'configDrive' => $conf['configDrive'], 'winDomain' => $conf['winDomain']));
 }
Beispiel #19
0
 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);
 }
 /**
  * {@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;
     }
 }
Beispiel #21
0
 public function load(ObjectManager $manager)
 {
     $yaml = new Parser();
     // TODO: find a way of obtainin Bundle's path with the help of $this->container
     $bpath = $this->container->get('kernel')->getBundle('SiwappEstimateBundle')->getPath();
     $value = $yaml->parse(file_get_contents($bpath . '/DataFixtures/estimates.yml'));
     foreach ($value['Item'] as $ref => $values) {
         $item = new Item();
         $estimate = new Estimate();
         foreach ($values as $fname => $fvalue) {
             if ($fname == 'Estimate') {
                 $fvalue = $manager->merge($this->getReference($fvalue));
                 $fvalue->addItem($item);
                 $manager->persist($fvalue);
             }
             $method = 'set' . Inflector::camelize($fname);
             if (is_callable(array($item, $method))) {
                 call_user_func(array($item, $method), $fvalue);
             }
         }
         $manager->persist($item);
         $manager->flush();
         $this->addReference($ref, $item);
     }
     foreach ($value['ItemTax'] as $ref => $values) {
         $item = $this->getReference($values['Item']);
         $tax = $this->getReference($values['Tax']);
         $item->addTax($tax);
         $manager->persist($item);
         $manager->flush();
     }
 }
Beispiel #22
0
 /**
  * Parses YAML into a PHP value.
  *
  *  Usage:
  *  <code>
  *   $array = Yaml::parse(file_get_contents('config.yml'));
  *   print_r($array);
  *  </code>
  *
  * @param string $input A string containing YAML
  * @param int    $flags A bit field of PARSE_* constants to customize the YAML parser behavior
  *
  * @return mixed The YAML converted to a PHP value
  *
  * @throws ParseException If the YAML is not valid
  */
 public static function parse($input, $flags = 0)
 {
     if (is_bool($flags)) {
         @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
         if ($flags) {
             $flags = self::PARSE_EXCEPTION_ON_INVALID_TYPE;
         } else {
             $flags = 0;
         }
     }
     if (func_num_args() >= 3) {
         @trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the PARSE_OBJECT flag instead.', E_USER_DEPRECATED);
         if (func_get_arg(2)) {
             $flags |= self::PARSE_OBJECT;
         }
     }
     if (func_num_args() >= 4) {
         @trigger_error('Passing a boolean flag to toggle object for map support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED);
         if (func_get_arg(3)) {
             $flags |= self::PARSE_OBJECT_FOR_MAP;
         }
     }
     $yaml = new Parser();
     return $yaml->parse($input, $flags);
 }
Beispiel #23
0
 public function load(ObjectManager $manager)
 {
     $yaml = new Parser();
     $bpath = $this->container->get('kernel')->getBundle('SiwappRecurringInvoiceBundle')->getPath();
     $value = $yaml->parse(file_get_contents($bpath . '/DataFixtures/recurring_invoices.yml'));
     foreach ($value['Item'] as $ref => $values) {
         $item = new Item();
         $recurring_invoice = new RecurringInvoice();
         foreach ($values as $fname => $fvalue) {
             if ($fname == 'RecurringInvoice') {
                 $fvalue = $manager->merge($this->getReference($fvalue));
             }
             $method = 'set' . Inflector::camelize($fname);
             if (is_callable(array($item, $method))) {
                 call_user_func(array($item, $method), $fvalue);
             }
         }
         $manager->persist($item);
         $manager->flush();
         $this->addReference($ref, $item);
     }
     foreach ($value['ItemTax'] as $ref => $values) {
         $item = $this->getReference($values['Item']);
         $tax = $this->getReference($values['Tax']);
         $item->addTax($tax);
         $manager->persist($item);
         $manager->flush();
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $yaml = new Parser();
     $dumper = new Dumper();
     $yaml_file = $input->getArgument('yaml-file');
     $yaml_key = $input->getArgument('yaml-key');
     $yaml_new_key = $input->getArgument('yaml-new-key');
     try {
         $yaml_parsed = $yaml->parse(file_get_contents($yaml_file));
     } catch (\Exception $e) {
         $io->error($this->trans('commands.yaml.merge.messages.error-parsing') . ': ' . $e->getMessage());
         return;
     }
     if (empty($yaml_parsed)) {
         $io->info(sprintf($this->trans('commands.yaml.merge.messages.wrong-parse'), $yaml_file));
     }
     $nested_array = $this->getNestedArrayHelper();
     $parents = explode(".", $yaml_key);
     $nested_array->replaceKey($yaml_parsed, $parents, $yaml_new_key);
     try {
         $yaml = $dumper->dump($yaml_parsed, 10);
     } catch (\Exception $e) {
         $io->error($this->trans('commands.yaml.merge.messages.error-generating') . ': ' . $e->getMessage());
         return;
     }
     try {
         file_put_contents($yaml_file, $yaml);
     } catch (\Exception $e) {
         $io->error($this->trans('commands.yaml.merge.messages.error-writing') . ': ' . $e->getMessage());
         return;
     }
     $io->info(sprintf($this->trans('commands.yaml.update.value.messages.updated'), $yaml_file));
 }
 /**
  * @Route("/setup/_int_create_si_prefixes")
  */
 public function intCreateSiPrefixes()
 {
     $response = array("success" => true, "errors" => [], "message" => "SI Prefixes successfully created/updated");
     $path = $this->get("kernel")->locateResource(self::SIPREFIX_PATH . self::SIPREFIX_DATA);
     try {
         $yaml = new Parser();
         $data = $yaml->parse(file_get_contents($path));
         $entityManager = $this->get("doctrine.orm.default_entity_manager");
         foreach ($data as $prefixName => $prefixData) {
             $prefix = $this->getSiPrefix($prefixName);
             if ($prefix === null) {
                 $prefix = new SiPrefix();
                 $prefix->setPrefix($prefixName);
                 $entityManager->persist($prefix);
             }
             $prefix->setExponent($prefixData["exponent"]);
             $prefix->setSymbol($prefixData["symbol"]);
             $prefix->setBase($prefixData["base"]);
         }
         $entityManager->flush();
     } catch (\Exception $e) {
         $response["success"] = false;
         $response["message"] = "SI Prefix creation error";
         $response["errors"] = [$e->getMessage()];
     }
     return new JsonResponse($response);
 }
Beispiel #26
0
 /**
  * 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]);
             }
         }
     }
 }
 /**
  * {@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));
 }
 /**
  * Imports units.
  *
  * @return array An array with the keys "skipped" and "imported" which contain the number of units skipped and imported
  * @throws \Exception If an error occured
  */
 public function importUnits()
 {
     $path = $this->kernel->locateResource(self::UNIT_PATH . self::UNIT_DATA);
     $yaml = new Parser();
     $data = $yaml->parse(file_get_contents($path));
     $count = 0;
     $skipped = 0;
     foreach ($data as $unitName => $unitData) {
         $unit = $this->getUnit($unitName);
         if ($unit === null) {
             $unit = new Unit();
             $unit->setName($unitName);
             $unit->setSymbol($unitData["symbol"]);
             if (array_key_exists("prefixes", $unitData)) {
                 if (!is_array($unitData["prefixes"])) {
                     throw new \Exception($unitName . " doesn't contain a prefix list, or the prefix list is not an array.");
                 }
                 foreach ($unitData["prefixes"] as $name) {
                     $prefix = $this->getSiPrefix($name);
                     if ($prefix === null) {
                         throw new \Exception("Unable to find SI Prefix " . $name);
                     }
                     $unit->getPrefixes()->add($prefix);
                 }
             }
             $this->entityManager->persist($unit);
             $this->entityManager->flush();
             $count++;
         } else {
             $skipped++;
         }
     }
     return array("imported" => $count, "skipped" => $skipped);
 }
Beispiel #29
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $magento = new Magento($input->getOption('magento-root'));
     $config_adapter = new ConfigurationAdapter($magento);
     $yaml = new Parser();
     if ($input->getArgument('config-yaml-file')) {
         $config_yaml_file = $input->getArgument('config-yaml-file');
         if (!file_exists($config_yaml_file)) {
             throw new \Exception("File ({$config_yaml_file}) does not exist");
         }
         if (!is_readable($config_yaml_file)) {
             throw new \Exception("File ({$config_yaml_file}) is not readable");
         }
         $config_db_yaml = ConfigYaml::build($config_adapter);
         $config_file_contents = $yaml->parse(file_get_contents($config_yaml_file));
         $config_file_yaml = new ConfigYaml($config_file_contents, $input->getOption('env'));
         $diff = ConfigYaml::compare($config_file_yaml, $config_db_yaml);
         if (count($diff) > 0) {
             $db_data = $config_db_yaml->getData();
             $file_data = $config_file_yaml->getData();
             $diff_count = 0;
             foreach ($diff as $scope => $scope_data) {
                 foreach ($scope_data as $key => $value) {
                     $diff_count++;
                     $diff_message = sprintf("%s/%s is different (File: %s, DB: %s)", $scope, $key, $this->decorateValue($file_data[$scope][$key]), $this->decorateValue($db_data[$scope][$key]));
                     $output->writeln($diff_message);
                 }
             }
             return $diff_count;
         } else {
             return 0;
         }
     }
 }
Beispiel #30
0
 public function handle(RequestInterface $request, ParametersInterface $configuration, ContextInterface $context)
 {
     $yaml = new Parser();
     $rules = $yaml->parse($configuration->get('rules'));
     if (is_array($rules)) {
         $validator = $this->buildValidator($rules);
         // fragments
         $fragments = $request->getUriFragments();
         foreach ($fragments as $key => $value) {
             $validator->validateProperty('/~path/' . $key, $value);
         }
         // parameters
         $parameters = $request->getParameters();
         foreach ($parameters as $key => $value) {
             $validator->validateProperty('/~query/' . $key, $value);
         }
         // body
         $validator->validate($request->getBody());
         // check whether all required fields are available
         $fields = $validator->getRequiredNames();
         if (!empty($fields)) {
             throw new StatusCode\ClientErrorException('Missing required fields: ' . implode(', ', $fields));
         }
     }
     return $this->processor->execute($configuration->get('action'), $request, $context);
 }