flatrr/src/SelfReferencingFlatArray.php

122 lines
3.1 KiB
PHP
Raw Normal View History

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;
}
2020-06-23 03:32:03 +00:00
public function set(?string $name, $value)
{
return $this->filter(parent::set($name,$value));
}
public function push(?string $name, $value)
{
return $this->filter(parent::push($name,$value));
}
public function pop(?string $name)
{
return $this->filter(parent::pop($name));
}
public function unshift(?string $name, $value)
{
return $this->filter(parent::unshift($name,$value));
}
public function shift(?string $name)
{
return $this->filter(parent::shift($name));
}
public function rewind()
{
return $this->filter(parent::rewind());
}
public function next()
{
return $this->filter(parent::next());
}
public function current()
{
return $this->filter(parent::current());
}
2018-08-17 21:02:50 +00:00
protected function unescape($value)
{
2020-06-23 03:32:03 +00:00
//map this function onto array values
if (is_array($value)) {
return array_map(
[$this, 'unescape'],
$value
);
2018-08-17 21:02:50 +00:00
}
//search/replace on string values
if (is_string($value)) {
//unescape references
$value = preg_replace(
2020-06-23 03:32:03 +00:00
'/\$\\\?\{([^\}\\\]+)\\\?\}/S',
2018-08-17 21:02:50 +00:00
'\${$1}',
$value
);
//return
return $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
}