rest.post_update.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. }
  57. /**
  58. * Clear caches due to changes in route definitions.
  59. */
  60. function rest_post_update_161923() {
  61. // Empty post-update hook.
  62. }