v0.7.0
This commit is contained in:
80
provm/common/Service/Filemanager.php
Normal file
80
provm/common/Service/Filemanager.php
Normal file
@ -0,0 +1,80 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user