SingleNestedEnhancer.php in JSON:API Extras 8.3
File
src/Plugin/jsonapi/FieldEnhancer/SingleNestedEnhancer.php
View source
<?php
namespace Drupal\jsonapi_extras\Plugin\jsonapi\FieldEnhancer;
use Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerBase;
use Shaper\Util\Context;
class SingleNestedEnhancer extends ResourceFieldEnhancerBase {
public function defaultConfiguration() {
return [
'path' => 'value',
];
}
protected function doUndoTransform($data, Context $context) {
$output = $data;
$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;
}
protected function doTransform($data, Context $context) {
$input = $data;
$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 getOutputJsonSchema() {
return [
'oneOf' => [
[
'type' => 'string',
],
[
'type' => 'null',
],
],
];
}
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'],
],
];
}
}