Last active
December 21, 2015 09:59
-
-
Save crisu83/6288615 to your computer and use it in GitHub Desktop.
Component for Yii for rendering configuration files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ConfigRenderer extends CComponent | |
{ | |
/** | |
* @var string | |
*/ | |
public $tab = ' '; | |
/** | |
* @param $array | |
* @return string | |
*/ | |
public function render($array) | |
{ | |
return "<?php\nreturn " . $this->renderArray($array) . ";\n"; | |
} | |
/** | |
* @param $array | |
* @param int $depth | |
* @param bool $newLine | |
* @return string | |
*/ | |
protected function renderArray($array, $depth = 0, $newLine = true) | |
{ | |
$output = ''; | |
if ($newLine) { | |
$output .= $this->indent($depth); | |
} | |
$output .= "array(\n"; | |
foreach ($array as $key => $value) { | |
if (is_string($key)) { | |
$output .= $this->renderAssoc($key, $value, $depth + 1); | |
} else { | |
$output .= $this->renderValue($value, $depth + 1); | |
} | |
$output .= "\n"; | |
} | |
return $output . $this->indent($depth) . ')'; | |
} | |
/** | |
* @param $key | |
* @param $value | |
* @param $depth | |
* @return string | |
*/ | |
protected function renderAssoc($key, $value, $depth) | |
{ | |
return $this->renderKey($key, $depth) . ' => ' . $this->renderValue($value, $depth, false); | |
} | |
/** | |
* @param $key | |
* @param $depth | |
* @return string | |
*/ | |
protected function renderKey($key, $depth) | |
{ | |
return $this->indent($depth) . $this->quote($key); | |
} | |
/** | |
* @param $value | |
* @param $depth | |
* @param bool $newLine | |
* @return string | |
*/ | |
protected function renderValue($value, $depth, $newLine = true) | |
{ | |
$output = ''; | |
if ($newLine) { | |
$output .= $this->indent($depth); | |
} | |
if (is_array($value)) { | |
$output .= $this->renderArray($value, $depth, false); | |
} else { | |
$output .= $this->quote($value); | |
} | |
return $output; | |
} | |
/** | |
* @param $string | |
* @return string | |
*/ | |
protected function quote($string) | |
{ | |
return "'" . $string . "'"; | |
} | |
/** | |
* @param $depth | |
* @return string | |
*/ | |
protected function indent($depth) | |
{ | |
return str_repeat($this->tab, $depth); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment