MergeYaml.php in Database Sanitize 7
File
vendor/edisonlabs/merge-yaml/src/MergeYaml.php
View source
<?php
namespace EdisonLabs\MergeYaml;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;
class MergeYaml {
public $outputDir;
public $fileNamePatterns;
public $sourcePaths;
public function __construct(array $files, array $locations, $outputDir) {
$this->fileNamePatterns = $files;
$this->sourcePaths = array();
foreach ($locations as $path) {
$this->sourcePaths[] = realpath($path);
}
$this->outputDir = $outputDir;
}
public function prepareOutputDir() {
if (!is_dir($this->outputDir) && !mkdir($this->outputDir, 0700)) {
throw new \RuntimeException(sprintf('Output directory does not exist and it was not able to be created: %s.', $this->outputDir));
}
}
public function getMergedYmlContent(array $filePaths) {
$mergedValue = array();
foreach ($filePaths as $filePath) {
try {
$fileContent = file_get_contents($filePath);
$parsedFile = Yaml::parse($fileContent);
} catch (ParseException $exception) {
throw new \RuntimeException(sprintf("Unable to parse the file %s as YAML: %s", $filePath, $exception
->getMessage()));
}
if (!is_array($parsedFile)) {
$parsedFile = array();
}
$mergedValue = array_merge_recursive($mergedValue, $parsedFile);
}
return Yaml::dump($mergedValue, PHP_INT_MAX, 2);
}
public function createMergeFiles() {
$this
->prepareOutputDir();
$ymlFilesPaths = $this
->getYamlFiles();
if (empty($ymlFilesPaths)) {
return array();
}
foreach ($ymlFilesPaths as $fileName => $filePaths) {
$outputFileName = $fileName . '.merge.yml';
$yaml = $this
->getMergedYmlContent($filePaths);
file_put_contents($this->outputDir . '/' . $outputFileName, $yaml);
}
return $ymlFilesPaths;
}
public function getYamlFiles() {
$ymlFiles = array();
$finder = new Finder();
$finder
->files();
$finder
->followLinks();
$finder
->in($this->sourcePaths);
$finder
->sortByName();
foreach ($this->fileNamePatterns as $filePattern) {
$finder
->name($filePattern . '.yml');
}
if ($finder
->count() < 1) {
return array();
}
foreach ($finder as $file) {
$fileName = str_replace('.yml', '', $file
->getFilename());
$ymlFiles[$fileName][] = $file
->getRealPath();
}
return $ymlFiles;
}
}