Files
raby/provm/common/Service/Filemanager.php
2020-04-10 15:22:00 -04:00

84 lines
2.3 KiB
PHP

<?php
namespace ProVM\Common\Service;
use Spyc as Yaml;
use Symfony\Component\Filesystem\Filesystem;
class Filemanager {
protected $filesystem;
protected $base_folder;
public function __construct(Filesystem $filesystem, string $base_folder) {
$this->filesystem = $filesystem;
$this->base_folder = $base_folder;
}
protected function fullPath(string $filename): string {
if ($this->filesystem->exists($filename)) {
return $filename;
}
return implode(DIRECTORY_SEPARATOR, [
$this->base_folder,
$filename
]);
}
protected $folders;
public function addFolder(string $name, string $folder) {
if ($this->folders === null) {
$this->folders = [];
}
$this->folders[$name] = $folder;
}
public function folder(string $name) {
return new Filemanager($this->filesystem, $this->folders[$name]);
}
public function exists(string $filename) {
return $this->filesystem->exists($this->fullPath($filename));
}
public function load(string $filename) {
$filename = $this->fullPath($filename);
if (!$this->exists($filename)) {
return false;
}
$file = new \SplFileInfo($filename);
$method = 'load' . ucfirst($file->getExtension());
return $this->parseData($this->{$method}($filename));
}
protected function loadYml(string $filename) {
return Yaml::YAMLLoad($filename);
}
protected function loadYaml(string $filename) {
return $this->loadYml($filename);
}
protected function loadJson(string $filename) {
return json_decode(trim(file_get_contents($filename)));
}
protected function loadPhp(string $filename) {
return include $filename;
}
protected function parseData($data) {
$temp = $data;
if (is_array($temp)) {
$is_object = false;
foreach ($data as $i => $sub) {
if (!is_numeric($i)) {
$is_object = true;
}
$temp[$i] = $this->parseData($sub);
}
if ($is_object) {
$temp = (object) $temp;
}
}
return $temp;
}
public function save(string $filename, $data): bool {
if (is_object($data)) {
$data = (array) $data;
}
if (is_array($data)) {
$data = Yaml::YAMLDump($data, false, false, true);
}
$filename = $this->fullPath($filename);
return file_put_contents($filename, $data);
}
}