Bolt\Configuration\YamlUpdater::change PHP Method

change() public method

Updates a single value with replacement for given key in yml file.
public change ( string $key, string $value, boolean $makeBackup = true ) : boolean
$key string
$value string
$makeBackup boolean
return boolean
    public function change($key, $value, $makeBackup = true)
    {
        $pattern = str_replace('/', ':.*', $key);
        preg_match_all('/^' . $pattern . '(:\\s*)/mis', $this->file->read(), $matches, PREG_OFFSET_CAPTURE);
        if (count($matches[0]) > 0 && count($matches[1])) {
            $index = $matches[1][0][1] + strlen($matches[1][0][0]);
        } else {
            return false;
        }
        $line = substr_count($this->file->read(), "\n", 0, $index);
        $this->yaml[$line] = preg_replace('/^(.*?):(.*)/', '$1: ' . $this->prepareValue($value), $this->yaml[$line]);
        return $this->save($makeBackup);
    }

Usage Example

Ejemplo n.º 1
0
 /**
  * @see \Symfony\Component\Console\Command\Command::execute()
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $key = $input->getArgument('key');
     $value = $input->getArgument('value');
     if ($input->getOption('backup')) {
         $backup = true;
     } else {
         $backup = false;
     }
     if ($input->getOption('file')) {
         $file = $input->getOption('file');
     } else {
         $file = 'config.yml';
     }
     try {
         $yaml = new YamlUpdater($this->app, $file);
         if ($yaml->change($key, $value, $backup)) {
             $result = sprintf("New value for <info>%s: %s</info> was successful. File updated.", $key, $value);
         } else {
             $result = sprintf("<error>The key '%s' was not found in %s.</error>", $key, $file);
         }
     } catch (FileNotFoundException $e) {
         $result = sprintf("<error>Can't read file: %s.</error>", $file);
     } catch (ParseException $e) {
         $result = sprintf("<error>Invalid YAML in file: %s.</error>", $file);
     } catch (FilesystemException $e) {
         $result = sprintf('<error>' . $e->getMessage() . '</error>');
     }
     $this->auditLog(__CLASS__, "Config value '{$key}: {$value}' set");
     $output->writeln($result);
 }