summaryrefslogtreecommitdiffstats
path: root/src/Plugin/jsonapi/FieldEnhancer/SingleNestedEnhancer.php
blob: 1bb3bd5ff390c2479c1644a759f4740f74e242a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php

namespace Drupal\jsonapi_extras\Plugin\jsonapi\FieldEnhancer;

use Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerBase;

/**
 * Perform additional manipulations to date fields.
 *
 * @ResourceFieldEnhancer(
 *   id = "nested",
 *   label = @Translation("Single Nested Property"),
 *   description = @Translation("Extracts or wraps nested properties from an object.")
 * )
 */
class SingleNestedEnhancer extends ResourceFieldEnhancerBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'path' => 'value',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function postProcess($value) {
    $output = $value;
    $configuration = $this->getConfiguration();
    $path = $configuration['path'];
    $path_parts = explode('.', $path);
    // Start drilling down until there are no more path parts.
    while ($output && ($path_part = array_shift($path_parts))) {
      $output = empty($output[$path_part])
        ? NULL
        : $output[$path_part];
    }
    return $output;
  }

  /**
   * {@inheritdoc}
   */
  public function prepareForInput($value) {
    $input = $value;
    $configuration = $this->getConfiguration();
    $path = $configuration['path'];
    $path_parts = explode('.', $path);
    // Start wrapping up until there are no more path parts.
    while ($path_part = array_pop($path_parts)) {
      $input = [$path_part => $input];
    }
    return $input;
  }

  /**
   * {@inheritdoc}
   */
  public function getJsonSchema() {
    return [
      'type' => 'string',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getSettingsForm(array $resource_field_info) {
    $settings = empty($resource_field_info['settings'])
      ? $this->getConfiguration()
      : $resource_field_info['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'],
      ],
    ];
  }

}