You are here

public function RegisterSerializationClassesCompilerPass::process in Drupal 10

Same name in this branch
  1. 10 core/modules/serialization/src/RegisterSerializationClassesCompilerPass.php \Drupal\serialization\RegisterSerializationClassesCompilerPass::process()
  2. 10 core/modules/jsonapi/src/DependencyInjection/Compiler/RegisterSerializationClassesCompilerPass.php \Drupal\jsonapi\DependencyInjection\Compiler\RegisterSerializationClassesCompilerPass::process()
Same name and namespace in other branches
  1. 8 core/modules/serialization/src/RegisterSerializationClassesCompilerPass.php \Drupal\serialization\RegisterSerializationClassesCompilerPass::process()
  2. 9 core/modules/serialization/src/RegisterSerializationClassesCompilerPass.php \Drupal\serialization\RegisterSerializationClassesCompilerPass::process()

Adds services to the Serializer.

Parameters

\Symfony\Component\DependencyInjection\ContainerBuilder $container: The container to process.

File

core/modules/serialization/src/RegisterSerializationClassesCompilerPass.php, line 20

Class

RegisterSerializationClassesCompilerPass
Adds services tagged 'normalizer' and 'encoder' to the Serializer.

Namespace

Drupal\serialization

Code

public function process(ContainerBuilder $container) {
  $definition = $container
    ->getDefinition('serializer');

  // Retrieve registered Normalizers and Encoders from the container.
  foreach ($container
    ->findTaggedServiceIds('normalizer') as $id => $attributes) {

    // The 'serializer' service is the public API: mark normalizers private.
    $container
      ->getDefinition($id)
      ->setPublic(FALSE);
    $priority = $attributes[0]['priority'] ?? 0;
    $normalizers[$priority][] = new Reference($id);
  }
  foreach ($container
    ->findTaggedServiceIds('encoder') as $id => $attributes) {

    // The 'serializer' service is the public API: mark encoders private.
    $container
      ->getDefinition($id)
      ->setPublic(FALSE);
    $priority = $attributes[0]['priority'] ?? 0;
    $encoders[$priority][] = new Reference($id);
  }

  // Add the registered Normalizers and Encoders to the Serializer.
  if (!empty($normalizers)) {
    $definition
      ->replaceArgument(0, $this
      ->sort($normalizers));
  }
  if (!empty($encoders)) {
    $definition
      ->replaceArgument(1, $this
      ->sort($encoders));
  }

  // Find all serialization formats known.
  $formats = [];
  $format_providers = [];
  foreach ($container
    ->findTaggedServiceIds('encoder') as $service_id => $attributes) {
    $format = $attributes[0]['format'];
    $formats[] = $format;
    if ($provider_tag = $container
      ->getDefinition($service_id)
      ->getTag('_provider')) {
      $format_providers[$format] = $provider_tag[0]['provider'];
    }
  }
  $container
    ->setParameter('serializer.formats', $formats);
  $container
    ->setParameter('serializer.format_providers', $format_providers);
}