SingleNestedEnhancer.php in JSON:API Extras 8
File
src/Plugin/jsonapi/FieldEnhancer/SingleNestedEnhancer.php
View source
<?php
namespace Drupal\jsonapi_extras\Plugin\jsonapi\FieldEnhancer;
use Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerBase;
class SingleNestedEnhancer extends ResourceFieldEnhancerBase {
public function defaultConfiguration() {
return [
'path' => 'value',
];
}
public function postProcess($value) {
$output = $value;
$configuration = $this
->getConfiguration();
$path = $configuration['path'];
$path_parts = explode('.', $path);
while ($output && ($path_part = array_shift($path_parts))) {
$output = empty($output[$path_part]) ? NULL : $output[$path_part];
}
return $output;
}
public function prepareForInput($value) {
$input = $value;
$configuration = $this
->getConfiguration();
$path = $configuration['path'];
$path_parts = explode('.', $path);
while ($path_part = array_pop($path_parts)) {
$input = [
$path_part => $input,
];
}
return $input;
}
public function getJsonSchema() {
return [
'type' => 'string',
];
}
public function getSettingsForm(array $resource_field_info) {
$settings = empty($resource_field_info['enhancer']['settings']) ? $this
->getConfiguration() : $resource_field_info['enhancer']['settings'];
return [
'path' => [
'#type' => 'textfield',
'#title' => $this
->t('Path'),
'#description' => $this
->t('A dot separated path to extract the sub-property.'),
'#default_value' => $settings['path'],
],
];
}
}