<?php namespace Phpcmf\Library;
class Config
{
private $file;
private $space = 32;
private $header;
public function file($file, $name = '', $space = 32) {
$this->file = $file;
$this->space = $space;
$this->header = '<?php'.PHP_EOL.PHP_EOL.
'if (!defined(\'BASEPATH\')) exit(\'No direct script access allowed\');'.PHP_EOL.PHP_EOL.
''.PHP_EOL.PHP_EOL
;
return $this;
}
public function to_header() {
return $this->header.$this->note;
}
public function to_require_one($var, $data = []) {
$body = $this->header.'return ['.PHP_EOL.PHP_EOL;
if ($data) {
foreach ($var as $name => $note) {
if (is_array($data[$name])) {
continue;
}
$name = dr_safe_replace($name);
$body.= ' \''.$name.'\''.$this->_space($name).'=> '.$this->_format_value($data[$name]).', }
} elseif ($var) {
foreach ($var as $name => $val) {
if (is_array($val)) {
continue;
}
$name = dr_safe_replace($name);
$body.= ' \''.$name.'\''.$this->_space($name).'=> '.$this->_format_value($val).','.PHP_EOL;
}
}
$body.= PHP_EOL.'];';
!is_dir(dirname($this->file)) && dr_mkdirs(dirname($this->file));
function_exists('opcache_reset') && opcache_reset();
return @file_put_contents($this->file, $body, LOCK_EX);
}
public function to_require($data) {
$body = $this->header.'return ';
$body .= str_replace(array(' ', '
'), array(' ', ' '), var_export($data, TRUE));
$body .= ';';
!is_dir(dirname($this->file)) && dr_mkdirs(dirname($this->file));
function_exists('opcache_reset') && opcache_reset();
return @file_put_contents($this->file, $body, LOCK_EX);
}
public function to_require_array($value) {
if (!$value) {
return NULL;
}
$body = $this->header.'return ['.PHP_EOL.PHP_EOL;
foreach ($value as $id => $data) {
$body.= ' '.$id .' => ['.PHP_EOL.PHP_EOL;
foreach ($data as $name => $val) {
if (is_array($data[$name])) {
continue;
}
$name = dr_safe_replace($name);
$body.= ' \''.$name.'\''.$this->_space($name).'=> '.$this->_format_value($data[$name]).','.PHP_EOL;
}
$body.= PHP_EOL.' ],'.PHP_EOL.PHP_EOL;
}
$body.= PHP_EOL.'];';
!is_dir(dirname($this->file)) && dr_mkdirs(dirname($this->file));
function_exists('opcache_reset') && opcache_reset();
return @file_put_contents($this->file, $body, LOCK_EX);
}
private function _space($name) {
$len = strlen($name) + 2;
$cha = $this->space - $len;
$str = '';
for ($i = 0; $i < $cha; $i ++) $str .= ' ';
return $str;
}
private function _format_value($value) {
return is_numeric($value) && strlen($value) <= 10 ? $value : '\''.str_replace(array('\'', '\\'), '', $value).'\'';
}
}