Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
[email protected] webmail now available. Want one? Go here.
Cannot use outlook/hotmail/live here to register as they blocking our mail servers. #microsoftdeez
Obey the Epel!

Paste

Pasted as PHP by Noname ( 7 years ago )
// myConfig.php
<?php return (array (
));

// ClassTest.php
<?php
class ConfigActions
{
 protected $path;
 protected $array;

 function get($name = null)
 {
  if(isset($name)){
   return $this->array[$name] ?? null;
  } else {
   return $this->array ?? [];
  }
 }

 function set(array $array)
 {
  $this->array = $array;
 }

 function edit(array $data_array)
 {
  $this->array = array_merge(($this->array??[]), $data_array);
 }

 function delete()
 {
  foreach (func_get_args() as $config_key) {
   unset($this->array[$config_key]);
  }
 }

 function save(string $path=null)
 {
  $save_path = ($path ?? $this->path);
  if(is_null($save_path)){
   throw new Exception('No path to save');
  }

  $data = is_array($this->array) ? $this->array : [];
  $config = "<?php return (".var_export($data, true).");";
  $result = file_put_contents($save_path, $config, LOCK_EX);
  if($result === false){
   throw new Exception('Error saving');
  }

  return $result;
 }
}

class ConfigContainer extends ConfigActions
{
 function __construct($config_file)
 {
  $this->path = $config_file;

  if(!file_exists($config_file) || !is_file&#40;$config_file&#41;) {
   throw new \Exception('File not exist');
  } elseif(!is_readable($config_file)) {
   throw new \Exception('Can not access file');
  }

  $settings = include($config_file);
  if(!is_array($settings)) {
   throw new \Exception('Config is not array');
  }

  $this->array = $settings;
 }
}

/*
$config = new ConfigContainer('config_path')
// Удаляю не существующий элемент
var_dump($config ->delete('g85masf46y4y'));
var_dump($test_config->get());
var_dump($test_config->save());
*/

 

Revise this Paste

Parent: 85349
Your Name: Code Language: