View source
<?php
namespace Drupal\forena\Token;
use Drupal\forena\AppService;
use Drupal\forena\FrxPlugin\FieldFormatter\FormatterInterface;
class ReportReplacer extends TokenReplacerBase {
public $fields = [];
public $format_callbacks = [];
public $formats = [];
public function __construct() {
parent::__construct('/\\{[^\\n^\\r^}]+}/', '{}');
$this
->setFormatter($this);
$formatters = AppService::instance()
->getFormatterPlugins();
foreach ($formatters as $class) {
$formatter = new $class();
$formats = $formatter
->formats();
foreach ($formats as $method => $label) {
$this->format_callbacks[$method] = array(
$formatter,
$method,
);
$this->formats[$method] = $label;
}
}
}
public function replaceNested(&$data, $raw = TRUE) {
if (is_array($data)) {
$values = $data;
foreach ($values as $k => $value) {
$key = $k;
if (strpos($k, '{') !== FALSE) {
$key = $this
->replace($key);
unset($data[$k]);
$data[$key] = $value;
}
if (is_array($value)) {
$this
->replaceNested($data[$key], $raw);
}
else {
$data[$key] = $this
->replace($value, $raw);
}
}
}
else {
$data = $this
->replace($data, $raw);
}
}
protected function get_value($key, $raw = FALSE) {
$context = '';
$raw_key = $key;
$dataSvc = $this
->dataService();
if ($key && strpos($key, '.')) {
@(list($context, $key) = explode('.', $key, 2));
$o = $this
->getDataContext($context);
}
else {
$o = $this
->currentDataContext();
}
$value = htmlentities($dataSvc
->getValue($key, $context));
if ($this->formatter) {
$value = $this->formatter
->format($value, $raw_key, $raw);
}
return $value;
}
public function defineField($key, $field) {
$def = [];
foreach ($field as $attr => $value) {
$def[$attr] = $value;
}
$this->fields[$key] = $def;
}
public function format($value, $key, $raw = FALSE) {
$default = '';
$link = '';
$format = '';
$format_string = '';
$calc = '';
$context = '';
$field = [];
if (isset($this->fields[$key])) {
$field = $this->fields[$key];
extract($field);
if (isset($field['format-string'])) {
$format_string = $field['format-string'];
}
}
if ($calc) {
if ($context) {
$context .= ".";
}
$calc = $this
->replace($calc, TRUE);
if ($calc) {
$value = $this
->replace('{' . $context . '=' . $calc . '}', TRUE);
}
}
if ($format && !$raw) {
if (!empty($this->format_callbacks[$format])) {
$value = call_user_func($this->format_callbacks[$format], $value, $format_string, $this, $default);
}
$value = trim($value);
}
if (is_array($value) && !$raw) {
$value = implode(' ', $value);
}
if (!$value && $default) {
$value = $default;
}
if ($link && !$raw) {
$link_fields = array_merge(array_fill_keys([
'link',
'target',
'rel',
'class',
'add_query',
], ''), $field);
$this
->replaceNested($link_fields, TRUE);
$value = AppService::instance()
->reportLink($value, $link_fields);
}
return $value;
}
}