Class Drupal\introspector\Service\ServiceInfoManager - Source Code

Primary tabs

Location: /web/modules/custom/introspector/src/Service/ServiceInfoManager.php

    
        
namespace Drupal\introspector\Service;

use Drupal\introspector\ClassInfo;

/**
 * Class ServiceInfoManager.
 */
class ServiceInfoManager {

  public function list(string $provider='all'): array {

    $items = $this->getInfoItems();
    $items = $this->filter($items, ['provider' => $provider]);
    sort($items);

    return $items;
  }

  public function getInfoItems(): array {
    $items = [];

    $service_ids = \Drupal::getContainer()->getServiceIds();
    foreach ($service_ids as $service_id) {
      $items[$service_id] = new ClassInfo($service_id);
    }

    return $items;
  }

  public function getAllProviders() {
    $services = $this->list();

    $providers = array_unique(
      array_filter(
        array_column($services, 'provider'),
        function($value) {
          return !empty($value);
        }
      )
    );

    return $providers;
  }


  private function filter(array $items, array $params=[]): array {

    $filtered = [];

    /** @var  \Drupal\introspector\ClassInfo $item */
    foreach($items as $key => $item) {

      // Skip special things.
      // e.g. '.service_locator.tRiOYIx'
      if (str_starts_with($item->name, '.')) {
          // Skip to next item.
          continue;
      }

      // Skip if no reflection class present (= dodgy item).
      if (is_null($item->reflector)) {
          // Skip to next item.
          continue;
      }


      $service = \Drupal::service($item->name);

      // Skip if this service is just a string.
      // Example: 'container.namespaces'.
      if (!is_object($service)){
        // Skip to next item.
        continue;
      }

      // Only retain classes from the given provider.
      if ($params['provider'] && $params['provider'] != 'all') {
        if ($item->provider != $params['provider']) {
          // Skip to next item.
          continue;
        }
      }





      // Add item to filtered list.
      $filtered[$key] = $item;
    }

    return $filtered;
  }

}