mocha_report-1.0.x-dev/src/LibraryUtilities.php
src/LibraryUtilities.php
<?php declare(strict_types = 1);
namespace Drupal\mocha_report;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Asset\LibraryDiscoveryInterface;
/**
* @todo Add class description.
*/
final class LibraryUtilities {
private readonly LibraryDiscoveryInterface $libraryDiscovery;
private readonly ModuleHandlerInterface $moduleHandler;
/**
* Constructs a LibraryUtilities object.
*/
public function __construct(
LibraryDiscoveryInterface $libraryDiscovery,
ModuleHandlerInterface $moduleHandler,
) {
$this->moduleHandler = $moduleHandler;
$this->libraryDiscovery = $libraryDiscovery;
}
public function getGroupDescription(string $group) : string {
$lib_info = $this->getMochaLibraries($group);
return reset($lib_info)['mocha_report']['description'] ?: '';
}
public function getGroups() : array {
return array_map(function($lib_info) {
return $lib_info['mocha_report']['group'];
}, array_filter($this->getMochaLibraries(), function($lib_info) {
$is_lib_in_group = (isset($lib_info['mocha_report']) && isset($lib_info['mocha_report']['group']));
if ($is_lib_in_group) {
return TRUE;
}
return FALSE;
}));
}
/**
* Fetch the libraries that list mocha_report_init as a dependency.
*
* @param string|null $group
* (Optional) The group to filter the libraries.
*
* @return array
* An array of libraries.
*/
public function getMochaLibraries(?string $group = null): array {
$libraries = [];
// Create list of enabled modules.
$enabled_modules = array_keys($this->moduleHandler->getModuleList());
// Go through list of modules and build list of libraries.
foreach ($enabled_modules as $extension) {
if ($extension !== 'mocha_report') {
foreach ($this->libraryDiscovery
->getLibrariesByExtension($extension) as $lib => $lib_info) {
// Only return libraries that use the mocha_report dependency.
if (in_array('mocha_report/mocha_report_init', $lib_info['dependencies'])) {
// If the libraries are filtered by Group then only return the
// libraries that are in the correct group.
$is_filtered_by_group = (!is_null($group));
if ($is_filtered_by_group) {
$is_lib_in_group = (isset($lib_info['mocha_report']) && isset($lib_info['mocha_report']['group']) && $lib_info['mocha_report']['group'] == $group);
if ($is_lib_in_group) {
$libraries["$extension/$lib"] = $lib_info;
}
}
else {
$libraries["$extension/$lib"] = $lib_info;
}
}
}
}
}
return $libraries;
}
/**
* Parse the provided title into something that can be used as a library name.
*
* @param string $group
* The unparsed Mocha Report Group.
*
* @return string
* The Mocha Report Group with only underscores and lowercase a-z remaining.
*/
public function parseGroup(string $group) : string {
$group = str_replace([' ', '-'], '_', $group);
$group = strtolower($group);
$group = preg_replace('/[^a-z0-9_]/', '', $group);
return trim((string)$group);
}
}
