Files
raby/provm/common/Service/Filemanager.php
2020-03-22 17:25:11 -03:00

81 lines
2.2 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 load(string $filename) {
$filename = $this->fullPath($filename);
if (!$this->filesystem->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) {
if (is_object($data)) {
$data = (array) $data;
}
if (is_array($data)) {
$data = implode(PHP_EOL, $data);
}
$filename = $this->fullPath($filename);
file_put_contents($filename, $data);
}
}