JsonapiResourceConfigForm.php 19 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\jsonapi_extras\Form;

5
use Drupal\Core\Config\ImmutableConfig;
6
use Drupal\Core\Entity\ContentEntityTypeInterface;
7
use Drupal\Core\Entity\EntityFieldManager;
8 9
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
10
use Drupal\Core\Entity\EntityTypeRepositoryInterface;
11
use Drupal\Core\Field\FieldDefinitionInterface;
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\jsonapi\ResourceType\ResourceType;
14
use Drupal\jsonapi\ResourceType\ResourceTypeRepository;
15
use Drupal\jsonapi_extras\Entity\JsonapiResourceConfig;
16
use Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerManager;
17
use Symfony\Component\DependencyInjection\ContainerInterface;
18
use Symfony\Component\HttpFoundation\Request;
19

20 21 22
/**
 * Base form for jsonapi_resource_config.
 */
23
class JsonapiResourceConfigForm extends EntityForm {
24 25

  /**
26 27
   * The bundle information service.
   *
28 29 30 31 32
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $bundleInfo;

  /**
33 34
   * The JSON API resource type repository.
   *
35 36 37 38
   * @var \Drupal\jsonapi\ResourceType\ResourceTypeRepository
   */
  protected $resourceTypeRepository;

39
  /**
40 41
   * The field manager.
   *
42 43 44 45
   * @var \Drupal\Core\Entity\EntityFieldManager
   */
  protected $fieldManager;

46
  /**
47 48
   * The entity type repository.
   *
49 50 51 52
   * @var \Drupal\Core\Entity\EntityTypeRepositoryInterface
   */
  protected $entityTypeRepository;

53
  /**
54 55
   * The field enhancer manager.
   *
56 57 58 59
   * @var \Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerManager
   */
  protected $enhancerManager;

60 61 62 63 64 65 66
  /**
   * The JSON API extras config.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

67 68 69 70 71 72 73
  /**
   * The current route match.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

74 75
  /**
   * JsonapiResourceConfigForm constructor.
76 77
   *
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info
78 79 80 81 82 83 84
   *   Bundle information service.
   * @param \Drupal\jsonapi\ResourceType\ResourceTypeRepository $resource_type_repository
   *   The JSON API resource type repository.
   * @param \Drupal\Core\Entity\EntityFieldManager $field_manager
   *   The entity field manager.
   * @param \Drupal\Core\Entity\EntityTypeRepositoryInterface $entity_type_repository
   *   The entity type repository.
85 86
   * @param \Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerManager $enhancer_manager
   *   The plugin manager for the resource field enhancer.
87 88
   * @param \Drupal\Core\Config\ImmutableConfig $config
   *   The config instance.
89
   * @param \Symfony\Component\HttpFoundation\Request $request
90
   */
91
  public function __construct(EntityTypeBundleInfoInterface $bundle_info, ResourceTypeRepository $resource_type_repository, EntityFieldManager $field_manager, EntityTypeRepositoryInterface $entity_type_repository, ResourceFieldEnhancerManager $enhancer_manager, ImmutableConfig $config, Request $request) {
92 93
    $this->bundleInfo = $bundle_info;
    $this->resourceTypeRepository = $resource_type_repository;
94
    $this->fieldManager = $field_manager;
95
    $this->entityTypeRepository = $entity_type_repository;
96
    $this->enhancerManager = $enhancer_manager;
97
    $this->config = $config;
98
    $this->request = $request;
99 100 101 102 103 104 105 106
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.bundle.info'),
107
      $container->get('jsonapi.resource_type.repository'),
108
      $container->get('entity_field.manager'),
109
      $container->get('entity_type.repository'),
110
      $container->get('plugin.manager.resource_field_enhancer'),
111 112
      $container->get('config.factory')->get('jsonapi_extras.settings'),
      $container->get('request_stack')->getCurrentRequest()
113 114 115 116 117 118 119 120
    );
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
121 122
    // Disable caching on this form.
    $form_state->setCached(FALSE);
123

124 125 126
    $entity_type_id = $this->request->get('entity_type_id');
    $bundle = $this->request->get('bundle');

127
    /** @var JsonapiResourceConfig $entity */
128 129 130 131
    $entity = $this->getEntity();
    $resource_id = $entity->get('id');
    // If we are editing an entity we don't want the Entity Type and Bundle
    // picker, that info is locked.
132 133 134 135 136 137 138 139 140 141
    if (!$entity_type_id || !$bundle) {
      if ($resource_id) {
        list($entity_type_id, $bundle) = explode('--', $resource_id);
        $form['#title'] = $this->t('Edit %label resource config', ['%label' => $resource_id]);
      }
      else {
        list($entity_type_id, $bundle) = $this->buildEntityTypeBundlePicker($form, $form_state);
        if (!$entity_type_id) {
          return $form;
        }
142
      }
143
    }
144

145
    if ($entity_type_id && $resource_type = $this->resourceTypeRepository->get($entity_type_id, $bundle)) {
146
      // Get the JSON API resource type.
147 148
      $resource_config_id = sprintf('%s--%s', $entity_type_id, $bundle);
      $existing_entity = $this->entityTypeManager
149
        ->getStorage('jsonapi_resource_config')->load($resource_config_id);
150 151 152 153 154 155 156 157 158
      if ($existing_entity && $entity->isNew()) {
        drupal_set_message($this->t('This override already exists, please edit it instead.'));
        return $form;
      }
      $form['bundle_wrapper']['fields_wrapper'] = $this->buildOverridesForm($resource_type, $entity);
      $form['id'] = [
        '#type' => 'hidden',
        '#value' => sprintf('%s--%s', $entity_type_id, $bundle),
      ];
159
    }
160

161 162 163
    return $form;
  }

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
    $resourceFields = $form_values['resourceFields'];
    $overrides = [];

    // Get the field values
    foreach ($resourceFields as $field => $data) {
      // Only get the overridden fields.
      if ($data['fieldName'] != $data['publicName']) {
        // Store the publicName for comparison.
        $overrides[$field] = $data['publicName'];
      }
    }

    // Compare the overrides and find any duplicate values.
    $deduped_overrides = array_unique($overrides);
    $dupes = array_diff_assoc($overrides, $deduped_overrides);
    // Set an error if there are duplicates.
    if ($dupes) {
      foreach ($dupes as $field => $value) {
        $form_state->setErrorbyName('resourceFields][' . $field . '][publicName', $this->t('The override must be unique.'));
      }
    }
    // Now compare the overrides with the default names to validate no dupes exist.
    foreach ($overrides as $field => $override) {
      if (array_key_exists($override, $resourceFields)) {
        $form_state->setErrorByName('resourceFields][' . $field . '][publicName', $this->t('The override must be unique.'));
      }
    }

    // Validate URL and resource type
    $resource_types = $this->entityTypeManager
      ->getStorage('jsonapi_resource_config')
      ->loadByProperties(['disabled' => FALSE]);
    foreach ($resource_types as $id => $resource_type) {
      if ($this->entity->id() == $id) {
        continue;
      }

      if ($resource_type->get('resourceType') == $form_values['resourceType']) {
        $form_state->setErrorByName('resourceType', $this->t('There is already resource (:name) with this override.', [':name' => $resource_type->id()]));
      }
      if ($resource_type->get('path') == $form_values['path']) {
        $form_state->setErrorByName('path', $this->t('There is already resource (:name) with this path.', [':name' => $resource_type->id()]));
      }
    }
  }

215 216 217 218 219 220 221 222 223
  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $resource_config = $this->entity;
    $status = $resource_config->save();

    switch ($status) {
      case SAVED_NEW:
224
        drupal_set_message($this->t('Created the %label JSON API Resource overwrites.', [
225 226 227 228 229
          '%label' => $resource_config->label(),
        ]));
        break;

      default:
230
        drupal_set_message($this->t('Saved the %label JSON API Resource overwrites.', [
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
          '%label' => $resource_config->label(),
        ]));
    }
    $form_state->setRedirectUrl($resource_config->urlInfo('collection'));
  }

  /**
   * Implements callback for Ajax event on entity type or bundle selection.
   *
   * @param array $form
   *   From render array.
   *
   * @return array
   *   Color selection section of the form.
   */
  public function bundleCallback(array &$form) {
    return $form['bundle_wrapper'];
  }

250 251 252 253 254
  /**
   * Builds the part of the form that contains the overrides.
   *
   * @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
   *   The resource type being overridden.
255
   * @param \Drupal\jsonapi_extras\Entity\JsonapiResourceConfig $entity
256
   *   The configuration entity backing this form.
257 258 259 260
   *
   * @return array
   *   The partial form.
   */
261
  protected function buildOverridesForm(ResourceType $resource_type, JsonapiResourceConfig $entity) {
262
    $entity_type_id = $resource_type->getEntityTypeId();
263
    $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
264
    $bundle = $resource_type->getBundle();
265 266 267 268 269 270 271 272
    if ($entity_type instanceof ContentEntityTypeInterface) {
      $field_names = array_map(function (FieldDefinitionInterface $field_definition) {
        return $field_definition->getName();
      }, $this->fieldManager->getFieldDefinitions($entity_type_id, $bundle));
    }
    else {
      $field_names = array_keys($entity_type->getKeys());
    }
273 274 275 276 277

    $overrides_form['overrides']['entity'] = [
      '#type' => 'details',
      '#title' => $this->t('Entity'),
      '#description' => $this->t('Override configuration for the resource entity.'),
278
      '#open' => !$entity->get('resourceType') || !$entity->get('path'),
279
    ];
280 281

    $overrides_form['overrides']['entity']['disabled'] = [
282 283 284
      '#type' => 'checkbox',
      '#title' => $this->t('Disabled'),
      '#description' => $this->t('Check this if you want to disable this resource. Disabling a resource can have unexpected results when following relationships belonging to that resource.'),
285
      '#default_value' => $entity->get('disabled'),
286
    ];
287 288 289 290 291

    $resource_type_name = $entity->get('resourceType');
    if (!$resource_type_name) {
      $resource_type_name = sprintf('%s--%s', $entity_type_id, $bundle);
    }
292
    $overrides_form['overrides']['entity']['resourceType'] = [
293 294 295
      '#type' => 'textfield',
      '#title' => $this->t('Resource Type'),
      '#description' => $this->t('Overrides the type of the resource. Example: Change "node--article" to "articles".'),
296
      '#default_value' => $resource_type_name,
297 298 299 300 301
      '#states' => [
        'visible' => [
          ':input[name="disabled"]' => ['checked' => FALSE],
        ],
      ],
302
    ];
303 304 305 306 307 308

    $path = $entity->get('path');
    if (!$path) {
      $path = sprintf('%s/%s', $entity_type_id, $bundle);
    }

309
    $prefix = $this->config->get('path_prefix');
310
    $overrides_form['overrides']['entity']['path'] = [
311 312
      '#type' => 'textfield',
      '#title' => $this->t('Resource Path'),
313 314 315 316
      '#field_prefix' => sprintf('/%s/', $prefix),
      '#description' => $this->t('Overrides the path of the resource. Example: Use "articles" to change "/@prefix/node/article" to "/@prefix/articles".', [
        '@prefix' => $prefix,
      ]),
317 318
      '#default_value' => $path,
      '#required' => TRUE,
319 320 321 322 323
      '#states' => [
        'visible' => [
          ':input[name="disabled"]' => ['checked' => FALSE],
        ],
      ],
324 325
    ];

326 327 328 329 330 331 332 333 334 335 336 337
    $overrides_form['overrides']['fields'] = [
      '#type' => 'details',
      '#title' => $this->t('Fields'),
      '#description' => $this->t('Override configuration for the resource fields.'),
      '#open' => TRUE,
    ];

    $overrides_form['overrides']['fields']['info'] = [
      '#theme' => 'item_list',
      '#items' => [
        $this->t('<strong>Disabled</strong>: Check this if you want to disable this field completely. Disabling required fields will cause problems when writing to the resource.'),
        $this->t('<strong>Alias</strong>: Overrides the field name with a custom name. Example: Change "field_tags" to "tags".'),
338
        $this->t('<strong>Enhancer</strong>: Select an enhancer to manipulate the public output coming in and out.'),
339 340 341 342 343 344 345 346 347
      ],
    ];

    $overrides_form['overrides']['fields']['resourceFields'] = [
      '#type' => 'table',
      '#header' => [
        'disabled' => $this->t('Disabled'),
        'fieldName' => $this->t('Field name'),
        'publicName' => $this->t('Alias'),
348
        'enhancer' => $this->t('Enhancer'),
349 350
      ],
      '#empty' => $this->t('No fields available.'),
351 352 353 354 355 356
      '#states' => [
        'visible' => [
          ':input[name="disabled"]' => ['checked' => FALSE],
        ],
      ],
    ];
357

358
    foreach ($field_names as $field_name) {
359
      $overrides_form['overrides']['fields']['resourceFields'][$field_name] = $this->buildOverridesField($field_name, $entity);
360
    }
361

362 363 364
    return $overrides_form;
  }

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
  /**
   * {@inheritdoc}
   */
  public function buildEntity(array $form, FormStateInterface $form_state) {
    /** @var JsonapiResourceConfig $entity */
    $entity = parent::buildEntity($form, $form_state);

    // Trim slashes from path.
    $path = trim($form_state->getValue('path'), '/');
    if (strlen($path) > 0) {
      $entity->set('path', $path);
    }

    return $entity;
  }

381 382 383
  /**
   * Builds the part of the form that overrides the field.
   *
384 385
   * @param string $field_name
   *   The field name of the field being overridden.
386
   * @param \Drupal\jsonapi_extras\Entity\JsonapiResourceConfig $entity
387
   *   The config entity backed by this form.
388 389 390 391
   *
   * @return array
   *   The partial form.
   */
392
  protected function buildOverridesField($field_name, JsonapiResourceConfig $entity) {
393 394 395 396
    $resource_fields = array_filter($entity->get('resourceFields'), function (array $resource_field) use ($field_name) {
      return $resource_field['fieldName'] == $field_name;
    });
    $resource_field = array_shift($resource_fields);
397
    $overrides_form = [];
398 399 400
    $overrides_form['disabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Disabled'),
401
      '#title_display' => 'hidden',
Mateu Aguiló Bosch's avatar
Mateu Aguiló Bosch committed
402
      '#default_value' => $resource_field['disabled'],
403
    ];
404 405
    $overrides_form['fieldName'] = [
      '#type' => 'hidden',
406
      '#value' => $field_name,
407
      '#prefix' => $field_name,
408 409 410
    ];
    $overrides_form['publicName'] = [
      '#type' => 'textfield',
411
      '#title' => $this->t('Override Public Name'),
412
      '#title_display' => 'hidden',
413
      '#default_value' => empty($resource_field['publicName']) ? $field_name : $resource_field['publicName'],
414 415
      '#states' => [
        'visible' => [
416
          ':input[name="resourceFields[' . $field_name . '][disabled]"]' => [
417 418 419 420
            'checked' => FALSE,
          ],
        ],
      ],
421
    ];
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
    // Build the select field for the list of enhancers.
    $overrides_form['enhancer'] = [
      '#type' => 'fieldgroup',
      '#states' => [
        'visible' => [
          ':input[name="resourceFields[' . $field_name . '][disabled]"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];
    $options = array_reduce(
      $this->enhancerManager->getDefinitions(),
      function (array $carry, array $definition) {
        $carry[$definition['id']] = $definition['label'];
        return $carry;
      },
      ['' => $this->t('- Select -')]
    );
    $id = empty($resource_field['enhancer']['id'])
      ? ''
      : $resource_field['enhancer']['id'];
    $overrides_form['enhancer']['id'] = [
      '#type' => 'select',
      '#options' => $options,
      '#ajax' => [
        'callback' => '::getEnhancerSettings',
        'wrapper' => $field_name . '-settings-wrapper',
      ],
      '#default_value' => $id,
    ];
    $overrides_form['enhancer']['settings'] = [
      '#type' => 'container',
      '#attributes' => ['id' => $field_name . '-settings-wrapper'],
    ];
    if (!empty($resource_field['enhancer']['id'])) {
      /** @var \Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerInterface $enhancer */
      $enhancer = $this->enhancerManager
        ->createInstance($resource_field['enhancer']['id'], []);
      $overrides_form['enhancer']['settings'] += $enhancer
        ->getSettingsForm($resource_field);
    }
464 465 466
    return $overrides_form;
  }

467 468 469 470 471 472
  /**
   * Build the entity picker widget and return the entity type and bundle IDs.
   *
   * @param array $form
   *   The form passed by reference to update it.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
473
   *   The state of the form.
474 475 476 477 478 479 480 481
   *
   * @return array
   *   The entity types ID and the bundle ID.
   */
  protected function buildEntityTypeBundlePicker(array &$form, FormStateInterface $form_state) {
    $form['_entity_type_id'] = [
      '#title' => $this->t('Entity Type'),
      '#type' => 'select',
482
      '#options' => $this->entityTypeRepository->getEntityTypeLabels(TRUE),
483 484 485 486 487 488 489 490
      '#empty_option' => $this->t('- Select -'),
      '#required' => TRUE,
      '#ajax' => [
        'callback' => '::bundleCallback',
        'wrapper' => 'bundle-wrapper',
      ],
    ];

491 492 493 494 495 496 497
    if (isset($parameter['entity_type_id'])) {
      $form['_entity_type_id'] = [
        '#type' => 'hidden',
        '#value' => $parameter['entity_type_id'],
      ];
    }

498 499 500 501 502 503 504 505 506 507 508 509 510
    $form['bundle_wrapper'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'bundle-wrapper'],
    ];
    if (!$entity_type_id = $form_state->getValue('_entity_type_id')) {
      return [$entity_type_id, NULL];
    }
    $has_bundles = (bool) $this->entityTypeManager
      ->getDefinition($entity_type_id)->getBundleEntityType();
    if ($has_bundles) {
      $bundles = [];
      $bundle_info = $this->bundleInfo->getBundleInfo($entity_type_id);
      foreach ($bundle_info as $bundle_id => $info) {
511
        $bundles[$bundle_id] = $info['translatable'] ? $this->t($info['label']) : $info['label'];
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
      }
      $form['bundle_wrapper']['_bundle_id'] = [
        '#type' => 'select',
        '#empty_option' => $this->t('- Select -'),
        '#title' => $this->t('Bundle'),
        '#options' => $bundles,
        '#required' => TRUE,
        '#ajax' => [
          'callback' => '::bundleCallback',
          'wrapper' => 'bundle-wrapper',
        ],
      ];
    }
    else {
      $form['bundle_wrapper']['_bundle_id'] = [
        '#type' => 'hidden',
        '#value' => $entity_type_id,
      ];
    }
    $bundle = $has_bundles
      ? $form_state->getValue('_bundle_id')
      : $entity_type_id;
    return [$entity_type_id, $bundle];
  }

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
  /**
   * AJAX callback to get the form settings for the enhancer for a field.
   *
   * @param array $form
   *   The reference to the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return mixed
   *   The specific form sub-tree in the form.
   */
  public static function getEnhancerSettings(array &$form, FormStateInterface $form_state) {
    // Find what is the field name that triggered the AJAX request.
    $user_input = $form_state->getUserInput();
    $parts = explode('[', $user_input['_triggering_element_name']);
    $field_name = rtrim($parts[1], ']');
    // Now return the sub-tree for the settings on the enhancer plugin.
    return $form['bundle_wrapper']['fields_wrapper']['overrides']['fields']['resourceFields'][$field_name]['enhancer']['settings'];
  }

557
}