rest.post_update.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. /**
  3. * @file
  4. * Post update functions for Rest.
  5. */
  6. use Drupal\rest\Entity\RestResourceConfig;
  7. use Drupal\rest\RestResourceConfigInterface;
  8. /**
  9. * Create REST resource configuration entities.
  10. *
  11. * @see rest_update_8201()
  12. * @see https://www.drupal.org/node/2308745
  13. */
  14. function rest_post_update_create_rest_resource_config_entities() {
  15. $resources = \Drupal::state()->get('rest_update_8201_resources', []);
  16. foreach ($resources as $key => $resource) {
  17. $resource = RestResourceConfig::create([
  18. 'id' => str_replace(':', '.', $key),
  19. 'granularity' => RestResourceConfigInterface::METHOD_GRANULARITY,
  20. 'configuration' => $resource,
  21. ]);
  22. $resource->save();
  23. }
  24. }
  25. /**
  26. * Simplify method-granularity REST resource config to resource-granularity.
  27. *
  28. * @see https://www.drupal.org/node/2721595
  29. */
  30. function rest_post_update_resource_granularity() {
  31. /** @var \Drupal\rest\RestResourceConfigInterface[] $resource_config_entities */
  32. $resource_config_entities = RestResourceConfig::loadMultiple();
  33. foreach ($resource_config_entities as $resource_config_entity) {
  34. if ($resource_config_entity->get('granularity') === RestResourceConfigInterface::METHOD_GRANULARITY) {
  35. $configuration = $resource_config_entity->get('configuration');
  36. $format_and_auth_configuration = [];
  37. foreach (array_keys($configuration) as $method) {
  38. $format_and_auth_configuration['format'][$method] = implode(',', $configuration[$method]['supported_formats']);
  39. $format_and_auth_configuration['auth'][$method] = implode(',', $configuration[$method]['supported_auth']);
  40. }
  41. // If each method has the same formats and the same authentication
  42. // providers configured, convert it to 'granularity: resource', which has
  43. // a simpler/less verbose configuration.
  44. if (count(array_unique($format_and_auth_configuration['format'])) === 1 && count(array_unique($format_and_auth_configuration['auth'])) === 1) {
  45. $first_method = array_keys($configuration)[0];
  46. $resource_config_entity->set('configuration', [
  47. 'methods' => array_keys($configuration),
  48. 'formats' => $configuration[$first_method]['supported_formats'],
  49. 'authentication' => $configuration[$first_method]['supported_auth'],
  50. ]);
  51. $resource_config_entity->set('granularity', RestResourceConfigInterface::RESOURCE_GRANULARITY);
  52. $resource_config_entity->save();
  53. }
  54. }
  55. }
  56. }