2018-08-17 21:02:50 +00:00
|
|
|
<?php
|
2018-08-17 22:09:45 +00:00
|
|
|
/* Flatrr | https://gitlab.com/byjoby/flatrr | MIT License */
|
|
|
|
namespace Flatrr;
|
2018-08-17 21:02:50 +00:00
|
|
|
|
|
|
|
class SelfReferencingFlatArray extends FlatArray
|
|
|
|
{
|
2020-06-22 23:19:41 +00:00
|
|
|
public function get(string $name = null, bool $raw = false, $unescape = true)
|
2018-08-17 21:02:50 +00:00
|
|
|
{
|
|
|
|
$out = parent::get($name);
|
|
|
|
if ($raw) {
|
|
|
|
return $out;
|
|
|
|
}
|
|
|
|
$out = $this->filter($out);
|
|
|
|
if ($unescape) {
|
|
|
|
$out = $this->unescape($out);
|
|
|
|
}
|
|
|
|
return $out;
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function unescape($value)
|
|
|
|
{
|
|
|
|
if ($value === null) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
//search/replace on string values
|
|
|
|
if (is_string($value)) {
|
|
|
|
//unescape references
|
|
|
|
$value = preg_replace(
|
|
|
|
'/\$\\\?\{([^\}\\\]+)\\\?\}/',
|
|
|
|
'\${$1}',
|
|
|
|
$value
|
|
|
|
);
|
|
|
|
//return
|
|
|
|
return $value;
|
|
|
|
}
|
|
|
|
//map this function onto array values
|
|
|
|
if (is_array($value)) {
|
|
|
|
return array_map(
|
|
|
|
function ($i) {
|
|
|
|
return $this->filter($i);
|
|
|
|
},
|
|
|
|
$value
|
|
|
|
);
|
|
|
|
}
|
|
|
|
//fall back to just returning value, it's some other datatype
|
|
|
|
return $value;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Recursively replace ${var/name} type strings in string values with
|
|
|
|
*/
|
|
|
|
protected function filter($value)
|
|
|
|
{
|
2020-06-22 23:19:41 +00:00
|
|
|
//map this function onto array values
|
|
|
|
if (is_array($value)) {
|
|
|
|
return array_map(
|
|
|
|
[$this, 'filter'],
|
|
|
|
$value
|
|
|
|
);
|
2018-08-17 21:02:50 +00:00
|
|
|
}
|
|
|
|
//search/replace on string values
|
2020-06-22 23:19:41 +00:00
|
|
|
if (is_string($value) && strpos($value, '${') !== false) {
|
2018-08-17 21:02:50 +00:00
|
|
|
//search for valid replacements
|
2020-06-22 23:19:41 +00:00
|
|
|
return preg_replace_callback(
|
2018-08-17 21:02:50 +00:00
|
|
|
//search for things like ${var/name}, escape with \ before last brace
|
2020-06-22 23:19:41 +00:00
|
|
|
'/\$\{([^\}]*[^\.\\\])\}/S',
|
2018-08-17 21:02:50 +00:00
|
|
|
//replace match with value from $this if it exists
|
2020-06-22 23:19:41 +00:00
|
|
|
[$this, 'filter_regex'],
|
2018-08-17 21:02:50 +00:00
|
|
|
//applied to $value
|
|
|
|
$value
|
|
|
|
);
|
|
|
|
}
|
|
|
|
//fall back to just returning value, it's some other datatype
|
|
|
|
return $value;
|
|
|
|
}
|
2020-06-22 23:19:41 +00:00
|
|
|
|
|
|
|
protected function filter_regex($matches)
|
|
|
|
{
|
|
|
|
if (null !== $value = $this->get($matches[1], false, false)) {
|
|
|
|
if (!is_array($value)) {
|
|
|
|
return $value;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return $matches[0];
|
|
|
|
}
|
2018-08-17 21:02:50 +00:00
|
|
|
}
|